代码
#include <opencv2\opencv.hpp>
#include <vector>
#include <algorithm>
using namespace cv;
using namespace std;
Mat toBinary(Mat src);
bool ascendSort(vector<Point> a, vector<Point> b);
Mat getContour(Mat src, Mat binary);
Mat srcImage, binaryImage, contourImage;
int main()
{
srcImage = imread("222.png");//input image
/*namedWindow("srcImage", 0);
imshow("srcImage", srcImage);*/
binaryImage = toBinary(srcImage);//convert to binary image
/*namedWindow("binaryImage", 0);
imshow("binaryImage", binaryImage);*/
contourImage = getContour(srcImage, binaryImage);
namedWindow("contourImage", 0);
imshow("contourImage", contourImage);
waitKey(0);
return 0;
}
Mat toBinary(Mat src)
{
Mat temp = src.clone();
int thresh = 200, maxValue = 255;
cvtColor(temp, temp, COLOR_BGR2GRAY);//convert to gray image
threshold(temp, temp, thresh, maxValue, THRESH_BINARY);//binary processing
return temp;
}
bool ascendSort(vector<Point> a, vector<Point> b)
{
return a.size() > b.size();
}
Mat getContour(Mat src, Mat binary)
{
Mat temp = src.clone();
vector< vector< Point> > contours;//save all contours data
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_LIST, CHAIN_APPROX_NONE);//find contours
//sort(contours.begin(), contours.end(), ascendSort);//ascending sort
vector< vector<Point> >::iterator itc = contours.begin(); //iterator of contour vector
int i = 0;
while (itc != contours.end())
{
if (itc->size() > 150)//ignore the small object
{
if (i > 0)
{
Rect rect = boundingRect(*itc);//get the rectangle bounding
rectangle(temp, rect, { 0, 0, 255 }, 2, 8);//draw the rectangle
RotatedRect resultRect;
resultRect = minAreaRect(*itc);//get the min area rectangle
Point2f pt[4];
resultRect.points(pt);//get the coordinate of vertex
//draw the min area rectangle
line(temp, pt[0], pt[1], Scalar(255, 0, 0), 2, 8);
line(temp, pt[1], pt[2], Scalar(255, 0, 0), 2, 8);
line(temp, pt[2], pt[3], Scalar(255, 0, 0), 2, 8);
line(temp, pt[3], pt[0], Scalar(255, 0, 0), 2, 8);
circle(temp, resultRect.center, 5, Scalar(0, 255, 0), -1, 8, 0);
cout << "**************形心*************" << endl;
cout << "X坐标:" << resultRect.center.x << " Y坐标:" << resultRect.center.y << " 偏转角度:" << resultRect.angle << endl;
cout << "*******************************" << endl;
}
i++;
}
++itc;
}
return temp;
}
效果