轮廓周围绘制矩形
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int threshold_value = 50;
int threshold_max = 255;
Mat src, dst;
const char* output = "output_image";
void contours_demo(int,void*);
RNG rng;
int main() {
src = imread("D:/b.jpeg");
if (src.empty()) {
printf("could not load image");
return -1;
}
namedWindow(output, WINDOW_AUTOSIZE);
imshow("input", src);
cvtColor(src,src,COLOR_BGR2GRAY);
const char* threshold_bar = "threshold_bar";
createTrackbar(threshold_bar, output, &threshold_value, threshold_max, contours_demo);
contours_demo(0,0);
waitKey(0);
return 0;
}
void contours_demo(int , void*) {
Mat binary_output;
vector<vector<Point >> contours;
vector<Vec4i> hierary;
threshold(src,binary_output,threshold_value,threshold_max,THRESH_BINARY);
//imshow(output, binary_output);
findContours(binary_output,contours,hierary,RETR_TREE,CHAIN_APPROX_SIMPLE,Point(-1,-1));
vector<vector<Point>>contours_ploy(contours.size());
vector<Rect>ploy_rect(contours.size());
vector<Point2f> ccs(contours.size());
vector<float> radius(contours.size());
for (size_t i = 0; i < contours.size(); i++) {
approxPolyDP(Mat(contours[i]), contours_ploy[i], 3, true);
ploy_rect[i] = boundingRect(contours_ploy[i]);
minEnclosingCircle(contours_ploy[i], ccs[i], radius[i]);
}
//画
//src.copyTo(dst);
dst = Mat::zeros(src.size(), CV_8UC4);
for (size_t i = 0; i < contours.size(); i++) {
Scalar color = Scalar(rng.uniform(0,255), rng.uniform(0, 255), rng.uniform(0, 255));
rectangle(dst,ploy_rect[i],color,2,8);
circle(dst, ccs[i], radius[i], color, 2, 8);
}
imshow(output,dst);
return;
}