shape.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import numpy as np
  2. import PIL.Image
  3. import PIL.ImageDraw
  4. from labelme import logger
  5. def polygons_to_mask(img_shape, polygons):
  6. mask = np.zeros(img_shape[:2], dtype=np.uint8)
  7. mask = PIL.Image.fromarray(mask)
  8. xy = list(map(tuple, polygons))
  9. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  10. mask = np.array(mask, dtype=bool)
  11. return mask
  12. def shapes_to_label(img_shape, shapes, label_name_to_value, type='class'):
  13. assert type in ['class', 'instance']
  14. cls = np.zeros(img_shape[:2], dtype=np.int32)
  15. if type == 'instance':
  16. ins = np.zeros(img_shape[:2], dtype=np.int32)
  17. instance_names = ['_background_']
  18. for shape in shapes:
  19. polygons = shape['points']
  20. label = shape['label']
  21. if type == 'class':
  22. cls_name = label
  23. elif type == 'instance':
  24. cls_name = label.split('-')[0]
  25. if label not in instance_names:
  26. instance_names.append(label)
  27. ins_id = len(instance_names) - 1
  28. cls_id = label_name_to_value[cls_name]
  29. mask = polygons_to_mask(img_shape[:2], polygons)
  30. cls[mask] = cls_id
  31. if type == 'instance':
  32. ins[mask] = ins_id
  33. if type == 'instance':
  34. return cls, ins
  35. return cls
  36. def labelme_shapes_to_label(img_shape, shapes):
  37. logger.warn('labelme_shapes_to_label is deprecated, so please use '
  38. 'shapes_to_label.')
  39. label_name_to_value = {'_background_': 0}
  40. for shape in shapes:
  41. label_name = shape['label']
  42. if label_name in label_name_to_value:
  43. label_value = label_name_to_value[label_name]
  44. else:
  45. label_value = len(label_name_to_value)
  46. label_name_to_value[label_name] = label_value
  47. lbl = shapes_to_label(img_shape, shapes, label_name_to_value)
  48. return lbl, label_name_to_value