createMask.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. # File : createMask.py
  3. # Time :2024-04-15 9:47
  4. # Author :FEANGYANG
  5. # version :python 3.7
  6. # Contact :1071082183@qq.com
  7. # Description:
  8. """
  9. import json
  10. import numpy as np
  11. import cv2
  12. import os
  13. def json2mask(json_path):
  14. # read json file
  15. with open(json_path, "r") as f:
  16. data = f.read()
  17. # convert str to json objs
  18. data = json.loads(data)
  19. # get the points
  20. points = data["shapes"][0]["points"]
  21. points = np.array(points, dtype=np.int32) # tips: points location must be int32
  22. imh = int(data["imageHeight"])
  23. imw = int(data["imageWidth"])
  24. # create a blank image
  25. mask = np.zeros((imh, imw, 3), dtype=np.uint8)
  26. # fill the contour with 255
  27. cv2.fillPoly(mask, [points], (255, 255, 255))
  28. _mask_path = os.path.splitext(json_path)[0]
  29. mask_path = str(_mask_path).replace('json', 'mask')+'.jpg'
  30. # save the mask
  31. cv2.imwrite(mask_path, mask)
  32. if __name__ == '__main__':
  33. path = 'data/json'
  34. path2 = './data/mask'
  35. if not os.path.exists(path2): # 判断是否存在文件夹如果不存在则创建为文件夹
  36. os.makedirs(path2)
  37. json_paths = os.listdir(path)
  38. for json_path in json_paths:
  39. json2mask(os.path.join(path, json_path))