mask-create.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import cv2
  2. import numpy as np
  3. # Callback function for drawing the rectangle
  4. def draw_mask(event, x, y, flags, param):
  5. global drawing, img_mask
  6. if event == cv2.EVENT_LBUTTONDOWN:
  7. drawing = True
  8. cv2.circle(img_mask, (x, y), 10, (255), -1)
  9. elif event == cv2.EVENT_MOUSEMOVE:
  10. if drawing:
  11. cv2.circle(img_mask, (x, y), 10, (255), -1)
  12. elif event == cv2.EVENT_LBUTTONUP:
  13. drawing = False
  14. cv2.circle(img_mask, (x, y), 10, (255), -1)
  15. # Load an image
  16. img = cv2.imread('/path/to/your/image')
  17. #img = cv2.resize(img, (512,512))
  18. img_mask = np.zeros(img.shape[:2], dtype=np.uint8)
  19. drawing = False
  20. # Create a window and bind the function to window
  21. cv2.namedWindow('image')
  22. cv2.setMouseCallback('image', draw_mask)
  23. while True:
  24. # Display the image
  25. cv2.imshow('image', cv2.addWeighted(img, 0.8, cv2.cvtColor(img_mask, cv2.COLOR_GRAY2BGR), 0.2, 0))
  26. k = cv2.waitKey(1) & 0xFF
  27. if k == 27: # Press ESC to exit
  28. break
  29. # Create a binary mask
  30. binary_mask = (img_mask > 0).astype(np.uint8) * 255
  31. # Save the binary mask
  32. cv2.imwrite('saved_mask.png', binary_mask)
  33. # Show the binary mask and wait until any key is pressed
  34. cv2.imshow('Binary Mask', binary_mask)
  35. cv2.waitKey(0)
  36. cv2.destroyAllWindows()