具体的代码已经完成了,在写的过程中我碰到了一个小问题,就是发现用findContours时会报错,后来发现findcontours只支持灰度图像,用cvtColors的Color_RGB2GRAY转一下就好了,下面是代码:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat image = imread("C:\\Users\\d\\Desktop\\2.png",WINDOW_AUTOSIZE);
cvtColor(image, image, COLOR_RGB2GRAY);
vector<vector<cv::Point>> contours;
vector<Vec4i> hierarchy;
findContours(image, contours, hierarchy, 3, 1, Point(0,0));
Point2f P1[4], P2[4];
RotatedRect rect1 = minAreaRect(contours[3]);
rect1.points(P1);
RotatedRect rect2 = minAreaRect(contours[4]);
rect2.points(P2);
Point2f m[1];
m[0].x = ((P1[0].x + P1[2].x) / 2 + (P2[0].x + P2[2].x) / 2) / 2;
m[0].y = ((P1[0].y + P1[2].y) / 2 + (P2[0].y + P2[2].y) / 2) / 2;
cvtColor(image, image, COLOR_GRAY2BGR);
for (int j = 0; j <= 3; j++)
{
line(image, P1[j], P1[(j + 1) % 4], Scalar(0, 255, 255), 5);
}
for (int j = 0; j <= 3; j++)
{
line(image, P2[j], P2[(j + 1) % 4], Scalar(255, 0, 255), 5);
}
circle(image, m[0], 6, Scalar(0, 255, 0), -1);
imshow("窗口", image);
waitKey(0);
}
然后来上一个效果图:
总的来说还是不太难的,就是上面说的那个坑我卡了很久,不能只看VS里面的报错,还要看控制台上面的报错,泪目。
Point2f m[1];
m[0].x = ((P1[0].x + P1[2].x) / 2 + (P2[0].x + P2[2].x) / 2) / 2;
m[0].y = ((P1[0].y + P1[2].y) / 2 + (P2[0].y + P2[2].y) / 2) / 2;
关于这一段代码我要说明一下,这个就是先分别求出两个矩形中心点的坐标,然后求俩矩形的中心点连线中点的坐标(就是装甲板中心的坐标)。