imfill.cpp 914 B

1234567891011121314151617181920212223242526272829303132333435
  1. #include "opencv2/opencv.hpp"
  2. using namespace cv;
  3. int main(int argc, char **argv)
  4. {
  5. // Read image
  6. Mat im_in = imread("nickel.jpg", IMREAD_GRAYSCALE);
  7. // Threshold.
  8. // Set values equal to or above 220 to 0.
  9. // Set values below 220 to 255.
  10. Mat im_th;
  11. threshold(im_in, im_th, 220, 255, THRESH_BINARY_INV);
  12. // Floodfill from point (0, 0)
  13. Mat im_floodfill = im_th.clone();
  14. floodFill(im_floodfill, cv::Point(0,0), Scalar(255));
  15. // Invert floodfilled image
  16. Mat im_floodfill_inv;
  17. bitwise_not(im_floodfill, im_floodfill_inv);
  18. // Combine the two images to get the foreground.
  19. Mat im_out = (im_th | im_floodfill_inv);
  20. // Display images
  21. imshow("Thresholded Image", im_th);
  22. imshow("Floodfilled Image", im_floodfill);
  23. imshow("Inverted Floodfilled Image", im_floodfill_inv);
  24. imshow("Foreground", im_out);
  25. waitKey(0);
  26. }