labelme_on_docker 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python
  2. import argparse
  3. import json
  4. import os.path as osp
  5. import shlex
  6. import subprocess
  7. import sys
  8. def get_ip():
  9. cmd = 'ifconfig en0'
  10. output = subprocess.check_output(shlex.split(cmd))
  11. for row in output.splitlines():
  12. cols = row.strip().split(' ')
  13. if cols[0] == 'inet':
  14. ip = cols[1]
  15. return ip
  16. else:
  17. raise RuntimeError('No ip is found.')
  18. def labelme_on_docker(image_file, out_file):
  19. ip = get_ip()
  20. cmd = 'xhost + %s' % ip
  21. subprocess.check_output(shlex.split(cmd))
  22. out_file = osp.abspath(out_file)
  23. if osp.exists(out_file):
  24. raise RuntimeError('File exists: %s' % out_file)
  25. else:
  26. open(osp.abspath(out_file), 'w')
  27. cmd = 'docker run -it --rm -e DISPLAY={0}:0' \
  28. ' -v /tmp/.X11-unix:/tmp/.X11-unix' \
  29. ' -v {1}:{2}' \
  30. ' -v {3}:{4}' \
  31. ' -w /root' \
  32. ' labelme' \
  33. ' labelme {2} -O {4}'
  34. cmd = cmd.format(
  35. ip,
  36. osp.abspath(image_file),
  37. osp.join('/root', osp.basename(image_file)),
  38. osp.abspath(out_file),
  39. osp.join('/root', osp.basename(out_file)),
  40. )
  41. subprocess.call(shlex.split(cmd))
  42. try:
  43. json.load(open(out_file))
  44. return out_file
  45. except Exception as e:
  46. raise RuntimeError('Annotation is cancelled.')
  47. def main():
  48. parser = argparse.ArgumentParser()
  49. parser.add_argument('image_file')
  50. parser.add_argument('-O', '--output', required=True)
  51. args = parser.parse_args()
  52. try:
  53. out_file = labelme_on_docker(args.image_file, args.output)
  54. print('Saved to: %s' % out_file)
  55. except RuntimeError as e:
  56. sys.stderr.write(e.__str__() + '\n')
  57. sys.exit(1)
  58. if __name__ == '__main__':
  59. main()