imfill.py 933 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env python
  2. import cv2;
  3. import numpy as np;
  4. # Read image
  5. im_in = cv2.imread("nickel.jpg", cv2.IMREAD_GRAYSCALE);
  6. # Threshold.
  7. # Set values equal to or above 220 to 0.
  8. # Set values below 220 to 255.
  9. th, im_th = cv2.threshold(im_in, 220, 255, cv2.THRESH_BINARY_INV);
  10. # Copy the thresholded image.
  11. im_floodfill = im_th.copy()
  12. # Mask used to flood filling.
  13. # Notice the size needs to be 2 pixels than the image.
  14. h, w = im_th.shape[:2]
  15. mask = np.zeros((h+2, w+2), np.uint8)
  16. # Floodfill from point (0, 0)
  17. cv2.floodFill(im_floodfill, mask, (0,0), 255);
  18. # Invert floodfilled image
  19. im_floodfill_inv = cv2.bitwise_not(im_floodfill)
  20. # Combine the two images to get the foreground.
  21. im_out = im_th | im_floodfill_inv
  22. # Display images.
  23. cv2.imshow("Thresholded Image", im_th)
  24. cv2.imshow("Floodfilled Image", im_floodfill)
  25. cv2.imshow("Inverted Floodfilled Image", im_floodfill_inv)
  26. cv2.imshow("Foreground", im_out)
  27. cv2.waitKey(0)