I have picked up a code segement from the top voted author's answer from this question:
https://answers.opencv.org/question/9863/fill-holes-of-a-binary-image/
Refomatted it as:
cv::Mat image = cv::imread("image.jpg", 0);
cv::Mat image_thresh;
cv::threshold(image, image_thresh, 125, 255, cv::THRESH_BINARY);
// Loop through the border pixels and if they're black, floodFill from there
cv::Mat mask;
image_thresh.copyTo(mask);
for (int i = 0; i < mask.cols; i++) {
if (mask.at<char>(0, i) == 0) {
cv::floodFill(mask, cv::Point(i, 0), 255, 0, 10, 10);
}
if (mask.at<char>(mask.rows-1, i) == 0) {
cv::floodFill(mask, cv::Point(i, mask.rows-1), 255, 0, 10, 10);
}
}
for (int i = 0; i < mask.rows; i++) {
if (mask.at<char>(i, 0) == 0) {
cv::floodFill(mask, cv::Point(0, i), 255, 0, 10, 10);
}
if (mask.at<char>(i, mask.cols-1) == 0) {
cv::floodFill(mask, cv::Point(mask.cols-1, i), 255, 0, 10, 10);
}
}
// Compare mask with original.
cv::Mat newImage;
image.copyTo(newImage);
for (int row = 0; row < mask.rows; ++row) {
for (int col = 0; col < mask.cols; ++col) {
if (mask.at<char>(row, col) == 0) {
newImage.at<char>(row, col) = 255;
}
}
}
cv::imshow("filled image", mask);
cv::imshow("Final image", newImage);
cv::imwrite("final.jpg", newImage);
cv::waitKey(0);
return 0;
I understand it used floodfill algorithm to try to fill holes, and I've tested on another sample image:
and it works really well by detecting all the 9 holes.
However, I tried another slighly complex image:
This time it won't work and it will fill the whole graph with white, and the number of holes it detects is 1700.
I think I might be lacking a siginificant amnout of morphological knowledge here, but I assume maybe I should do a "shirnking" on the failed image first, before insert it into the author's code?
Could experts share some thoughts with me because I could not find very similar graphs on google for hole detection. So what is the special about holes when two holes are connected with a white path in the binary image?Thanks in advance!