2015-11-11 170 views
0

,這個矩形中心是孔。 (白的各像素值= 255,黑色值= 0)如何用opencv填充輪廓線?例如,

enter image description here

但是,我要填充該孔。 (如下面圖)

enter image description here

如何通過使用矩形的OpenCV填充孔。

+0

Python,C++還是Java? – rayryeng

+0

這就是所謂的區域填充,如果你在matlab上,那麼這可能會幫助你:http://www.mathworks.com/matlabcentral/answers/111131-how-to-fill-the-region-of-interest-by-白色 – mumair

+0

同樣的問題在這裏回答:http://stackoverflow.com/questions/1716274/fill-the-holes-in-opencv – mumair

回答

2

首先找到它的凸包,然後在它的內部區域填寫:

cv::Mat inputImage = cv::imread("input.jpg", CV_LOAD_IMAGE_GRAYSCALE); 
cv::threshold(inputImage, inputImage, 10, 255, 0); 

// find non-zero elements 
cv::Mat nonZeroCoordinates; 
cv::findNonZero(inputImage, nonZeroCoordinates); 

cv::vector<cv::Point> points; 
for (int i = 0; i < nonZeroCoordinates.total(); i++) 
{ 
    points.push_back(nonZeroCoordinates.at<cv::Point>(i)); 
} 

// Find convex hull 
std::vector<int> hull; 
cv::convexHull(cv::Mat(points), hull, false); 

cv::vector<cv::Point> hullpoints; 
int hullcount = (int)hull.size(); 

for (int i = 0; i < hullcount; i++) 
{ 
    cv::Point pt = points[hull[i]]; 
    hullpoints.push_back(pt); 
} 

std::vector<std::vector<cv::Point> > fillContAll; 
fillContAll.push_back(hullpoints); 

cv::Mat result = cv::Mat::zeros(inputImage.size(), CV_8UC1); 
cv::fillPoly(result, fillContAll, cv::Scalar(255)); 

鑑於你的原始圖像:

enter image description here

這是你最後的結果:

enter image description here