OpenCV的drawContours()不能正常使用
void showImage(Mat image) {
namedWindow("outPut",WINDOW_NORMAL);
Size size(960,720);
Mat result;
resize(image, result, size);
resizeWindow("outPut",size);
while (true)
{
imshow("outPut", result);
int exit;
exit = waitKey(24);
if (27 == exit) {
break;
}
}
destroyAllWindows();
}
void m_findContours() {
Mat image,gray,result, result_1;
Mat soleColor(720,640, CV_8UC3, Scalar(0, 0, 0));
double square,circumference;
image = imread(hand);//0表示单通道
cvtColor(image, gray, COLOR_BGR2GRAY);
threshold(gray, result, 150, 255,THRESH_BINARY);
vector> contours;//储存查找出来的轮廓点
vector hierarchy;//储存层级,每一个vector数据存储四个int值
findContours(result, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);//result_1是查找出来的轮廓
vector> poly(contours.size());
vector hull;
drawContours(soleColor,contours,-1,Scalar(255,255,255), 2);//绘制轮廓时会直接绘制在原图上,第一个drawContours
for (int i = 0; i < contours.size();i++) {
approxPolyDP(contours[i], poly[i], 10, false);
}
drawContours(soleColor, poly, -1,Scalar(255,0,0), 2);//第二个drawContours
showImage(soleColor);
convexHull(contours[0], hull);
drawContours(soleColor, hull, -1, Scalar(0, 0, 255),2);//第三个drawContours,不能正常完成绘图
showImage(soleColor);
}
报的错如下所示:
但是将倒数第二行的drawContours的第二个参数改成(Mat)hull又能运行,但是只显示其中一两个点(手掌空地方的红点),查看了drawContours的函数说明,该参数只要是vector类型的即可,前面证明第一个和第二个drawContours可以运行,不太理解为什么强转行mat,不能全部绘制,而不转成mat类型又不能运行。
两份对比图如下:
不是Mat不Mat的问题,你可以试下将39行用下面三行代替:
vector<vector<Point> > hullvec;
hullvec.push_back(hull);
drawContours(soleColor, hullvec, -1, Scalar(0, 0, 255),2);
该回答引用GPTᴼᴾᴱᴺᴬᴵ
根据您提供的代码,可以看出第一个和第二个drawContours函数的第二个参数是vector类型的,而第三个drawContours函数的第二个参数是Mat类型的。这是因为drawContours函数有两种用法:
建议您重新检查一下代码中使用drawContours函数的场景,确认参数类型是否正确,以及使用的方法是否符合要求。