Mat src, gray_src, drawImg;
int threshold_v = ;
int threshold_max = ;
RNG rng();
void Contours_Callback(int, void*);
int main(int argc, char** argv) {
src = imread(STRPAHT2);
if (!src.data) {
printf("could not load image...\n");
return -;
}
cvtColor(src, gray_src, CV_BGR2GRAY);
blur(gray_src, gray_src, Size(, ), Point(-, -));
imshow("source_win", src);
createTrackbar("Threshold Value:", "output_win", &threshold_v, threshold_max, Contours_Callback);
Contours_Callback(, );
waitKey();
return ;
}
void Contours_Callback(int, void*) {
Mat binary_output;
vector<vector<Point>> contours;
vector<Vec4i> hierachy;
threshold(gray_src, binary_output, threshold_v, threshold_max, THRESH_BINARY);
//imshow("binary image", binary_output);
findContours(binary_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-, -));
vector<vector<Point>> contours_ploy(contours.size());
vector<Rect> ploy_rects(contours.size());
vector<Point2f> ccs(contours.size());
vector<float> radius(contours.size());
vector<RotatedRect> minRects(contours.size());
vector<RotatedRect> myellipse(contours.size());
for (size_t i = ; i < contours.size(); i++) {
//轮廓周围绘制矩形
approxPolyDP(Mat(contours[i]), contours_ploy[i], , true);
//得到轮廓周围最小矩形左上交点坐标和右下角点坐标,绘制一个矩形
ploy_rects[i] = boundingRect(contours_ploy[i]);
//得到一个旋转的矩形,返回旋转矩形
minEnclosingCircle(contours_ploy[i], ccs[i], radius[i]);
if (contours_ploy[i].size() > ) {
myellipse[i] = fitEllipse(contours_ploy[i]);
minRects[i] = minAreaRect(contours_ploy[i]);
}
}
// draw it
drawImg = Mat::zeros(src.size(), src.type());
Point2f pts[];
for (size_t t = ; t < contours.size(); t++) {
Scalar color = Scalar(rng.uniform(, ), rng.uniform(, ), rng.uniform(, ));
//矩形
//rectangle(drawImg, ploy_rects[t], color, 2, 8);
//圆
//circle(drawImg, ccs[t], radius[t], color, 2, 8);
if (contours_ploy[t].size() > ) {
ellipse(drawImg, myellipse[t], color, , );
minRects[t].points(pts);
for (int r = ; r < ; r++) {
line(drawImg, pts[r], pts[(r + ) % ], color, , );
}
}
}
imshow("output_win", drawImg);
return;
}