加入blur(image, image, Size(3, 3));就变成了下面的情况
不知道为什么
代码
。
// #include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main()
{
// Read input binary image
Mat image = imread("test.jpg", 0);
if (!image.data) { printf("读取图片错误,请确定目录下是否有imread函数指定图片存在~! \n"); return false; }
//blur(image, image, Size(3, 3));//加上变为两倍??
imshow("Image", image);
// 转为2值图
threshold(image, image, 200, 255, THRESH_BINARY_INV);
imshow("binary", image);
imwrite("binary.jpg", image);
vector<vector<Point>> contours;//保存所有轮廓数据save all contours data
vector<Vec4i> hierarchy;
findContours(image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//find contours
cout << "Contours: " << contours.size() << endl;
Mat imageContours = Mat::zeros(image.size(), CV_8UC1); //最小外接矩形画布
for (int i = 0; i<contours.size(); i++)
{
//绘制轮廓
drawContours(imageContours, contours, i, Scalar(255), 1, 8, hierarchy);
//绘制轮廓的最小外结矩形
RotatedRect resultRect;
resultRect = minAreaRect(contours[i]);//获取轮廓的最小外接矩形
Point2f P[4];
resultRect.points(P);//获取最小外接矩形的四个顶点坐标
for (int j = 0; j <= 3; j++)
{
line(imageContours, P[j], P[(j + 1) % 4], Scalar(255), 2);
}
cout << "X:" << resultRect.center.x << "Y:" << resultRect.center.y << "Angle:" << resultRect.angle << endl;
}
imshow("MinAreaRect", imageContours);
waitKey(0);
return 0;
}
另一种代码,但是不知道哪里有问题,画不出矩形图。
//cout << "Contours: " <&