19,469
社区成员
发帖
与我相关
我的任务
分享
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
using namespace std;
using namespace cv;
Mat img,smallImg,gray,bw;
vector<Vec4i> hierarchy;
vector<vector<Point> > contours;
int threshval=64;
Rect r;
Rect maxrect,brect;
int idx,n;
const static Scalar colors[15]={
CV_RGB( 0, 0,128),
CV_RGB( 0,128, 0),
CV_RGB( 0,128,128),
CV_RGB(128, 0, 0),
CV_RGB(128, 0,128),
CV_RGB(128,128, 0),
CV_RGB(128,128,128),
CV_RGB(160,160,160),
CV_RGB( 0, 0,255),
CV_RGB( 0,255, 0),
CV_RGB( 0,255,255),
CV_RGB(255, 0, 0),
CV_RGB(255, 0,255),
CV_RGB(255,255, 0),
CV_RGB(255,255,255),
};
Scalar color;
int main() {
cvNamedWindow("display",1);
smallImg=imread("test.png",1);
cvtColor(smallImg,gray,CV_BGR2GRAY);
imshow("display",gray);
waitKey(0);
bw=(gray>threshval);
imshow("display",bw);
waitKey(0);
Mat Structure1=getStructuringElement(MORPH_ELLIPSE,Size(16,16));
dilate(bw,bw,Structure1, Point(-1,-1));
imshow("display",bw);
waitKey(0);
Mat Structure0=getStructuringElement(MORPH_ELLIPSE,Size(20,20));
erode(bw,bw,Structure0,Point(-1,-1));
imshow("display",bw);
waitKey(0);
findContours(bw,contours,hierarchy,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
if (!contours.empty()&&!hierarchy.empty()) {
idx=0;
n=0;
vector<Point> approx;
for (;idx>=0;idx=hierarchy[idx][0]) {
color=colors[idx%15];
// drawContours(smallImg,contours,idx,color,1,8,hierarchy);
approxPolyDP(Mat(contours[idx]), approx, arcLength(Mat(contours[idx]), true)*0.005, true);//0.005为将毛边拉直的系数
const Point* p = &approx[0];
int m=(int)approx.size();
polylines(smallImg, &p, &m, 1, true, color);
circle(smallImg,Point(p[0].x,p[0].y),3,color);
circle(smallImg,Point(p[1].x,p[1].y),2,color);
for (int i=2;i<m;i++) circle(smallImg,Point(p[i].x,p[i].y),1,color);
n++;
if (1==n) {
maxrect=boundingRect(Mat(contours[idx]));
} else {
brect=boundingRect(Mat(contours[idx]));
if (brect.width*brect.height>maxrect.width*maxrect.height) maxrect=brect;
}
}
circle(smallImg,Point(maxrect.x+maxrect.width/2,maxrect.y+int(maxrect.height/2*1.17)),int(maxrect.height/2*1.1),CV_RGB(255,255,0),8);
}
imshow("display",smallImg);
waitKey(0);
cvDestroyWindow("display");
return 0;
}