opencv中boxPoints的返回值问题
boxPoints在c++环境下调用时,返回的是一个mat对象,与python的返回值不同
void minRcet() {
Mat image,result;
Mat contrast(720,640,CV_8UC4,Scalar(0,0,0));
image = imread(rectHello,0);
//showImage(image);
threshold(image, result, 5, 255,THRESH_BINARY);
//contrastImage(image, result);
vector<vector<Point>> contours;
vector<Vec4i> hierachy;
Mat position;
findContours(result, contours, hierachy, RETR_TREE,CHAIN_APPROX_SIMPLE);
drawContours(contrast, contours, -1, Scalar(0, 0, 255), 2);
//contrastImage(result,contrast);
RotatedRect rectPoint = minAreaRect(contours[1]);
Mat boxPts;
boxPoints(rectPoint,boxPts);
cout << endl << boxPts << endl;
//drawContours(contrast, boxPts, -1, Scalar(0, 255, 0));
// showImage(contrast);
}
输出的mat值为
又因drawContours绘制需要使用point类型的坐标才能绘制,但是boxPoints函数返回的mat对象信息如上图所示,不能把一个个点分开来作为point2f的坐标格式,就是想知道如何将 minAreaRect的图形用C++语言绘制出来
初学opencv不太懂,希望得到有经验的伙伴帮助
基于Monster 组和GPT的调写:
在C++中,boxPoints函数的第二个参数是一个Mat类型的输出参数,它会被用来存储旋转矩形的四个顶点坐标。因此,你需要先创建一个大小为(4, 2)的Mat对象,并将其作为boxPoints函数的第二个参数传入。最后,你可以将输出的Mat对象转换为一个vector类型,以便在drawContours函数中使用。
下面是修改后的代码示例:
void minRcet() {
Mat image, result;
Mat contrast(720, 640, CV_8UC4, Scalar(0, 0, 0));
image = imread(rectHello, 0);
threshold(image, result, 5, 255, THRESH_BINARY);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(result, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
drawContours(contrast, contours, -1, Scalar(0, 0, 255), 2);
RotatedRect rectPoint = minAreaRect(contours[1]);
Mat boxPts;
boxPoints(rectPoint, boxPts);
// 将Mat对象转换为vector<Point2f>类型
vector<Point2f> boxPtsVec;
boxPtsVec.reserve(4);
for (int i = 0; i < 4; ++i) {
boxPtsVec.emplace_back(boxPts.at<float>(i, 0), boxPts.at<float>(i, 1));
}
// 绘制旋转矩形
vector<vector<Point>> boxContours{boxPtsVec};
drawContours(contrast, boxContours, 0, Scalar(0, 255, 0), 2);
// showImage(contrast);
}
创建了一个名为boxPtsVec的vector类型的对象,并用boxPts的数据填充了它。然后,创建了一个vector<vector>类型的对象boxContours,其中包含了boxPtsVec。最后,我们将boxContours传递给drawContours函数来绘制旋转矩形。
既然得到了旋转矩形,别用boxPoints,直接用RotatedRect.points可以直接得到矩形的4个点,将它们依次相连即可
15行下面替换成如下即可:
cv::Point2f vertex[4];
rectPoint.points(vertex);
for (int i = 0; i < 4; i++)
{
cv::line(contrast, vertex[i], vertex[(i + 1) % 4], cv::Scalar(255, 100, 200),2,CV_AA);
}
不知道你这个问题是否已经解决, 如果还没有解决的话: