基于 mathematical.coffee 的答案,测试过的 C++ 代码:
vector< Point> merge_contours(vector <Point>& contour1, vector <Point>& contour2, int type){
Rect work_area = boundingRect( contour1 ) | boundingRect( contour2 );
Mat merged = Mat::zeros(work_area.size(), CV_8UC1);
Mat contour1_im = Mat::zeros(work_area.size(), CV_8UC1);
Mat contour2_im = Mat::zeros(work_area.size(), CV_8UC1);
vector<vector<Point> > shifted1;
shifted1.push_back(shift_contour(contour1, work_area.tl()));
drawContours( contour1_im, shifted1, -1, 255, -1);
vector<vector<Point> > shifted2;
shifted2.push_back(shift_contour(contour2, work_area.tl()));
drawContours( contour2_im, shifted2, -1, 255, -1);
if( type == 0 )
bitwise_or( contour1_im, contour2_im, merged);
else
bitwise_and( contour1_im, contour2_im, merged);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(merged,contours,hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
if(contours.size() > 1){
printf("Warn: merge_contours has output of more than one contours.");
}
return shift_contour(contours[0], work_area.tl() * -1);
}
drawContours
只填充轮廓,不是整个区域。这样会导致轮廓之间的交叉。因此,我必须添加cv2.FILLED
作为参数:img2 = cv2.drawContours(blank.copy(), contours, 0, 1, cv2.FILLED)
。 - Jeppe