#include <opencv2/opencv.hpp> using namespace std; using namespace cv; Mat fillHold(const cv::Mat src) { // Fim_thloodfill from point (0, 0) Mat im_floodfill = src.clone(); floodFill(im_floodfill, cv::Point(0, 0), Scalar(255)); // Invert floodfilled image Mat im_floodfill_inv; bitwise_not(im_floodfill, im_floodfill_inv); // Combine the two images to get the foreground. Mat im_out = (src | im_floodfill_inv); return im_out; } void fillHole(const Mat srcBw, Mat &dstBw) { Size m_Size = srcBw.size(); Mat Temp = Mat::zeros(m_Size.height + 2, m_Size.width + 2, srcBw.type());//延展图像 srcBw.copyTo(Temp(Range(1, m_Size.height + 1), Range(1, m_Size.width + 1))); floodFill(Temp, Point(0, 0), Scalar(255)); Mat cutImg;//裁剪延展的图像 Temp(Range(1, m_Size.height + 1), Range(1, m_Size.width + 1)).copyTo(cutImg); dstBw = srcBw | (~cutImg); } int main() { Mat img = imread("a.jpg"); Mat gray; cvtColor(img, gray, CV_RGB2GRAY); Mat bw; threshold(gray, bw, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); Mat bwFill; fillHole(bw, bwFill); imshow("填充前", gray); imshow("填充后", bwFill); waitKey(); return 0; }