1.源码实现
#include <cstdio>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
void thresh_callback(Mat &src_gray, const int thresh)
{
Mat canny_output;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
RNG rng(12345);
//用Canny算子检测边缘
Canny(src_gray, canny_output, thresh, 255, 3);
//寻找轮廓
findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
//多边形逼近轮廓 + 获取矩形和圆形边界框
vector<vector<Point>> contours_poly(contours.size());
vector<Rect> boundRect(contours.size());
vector<Point2f>center(contours.size());
vector<float>radius(contours.size());
for(int i = 0; i < contours.size(); i++)
{
approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);
boundRect[i] = boundingRect(Mat(contours_poly[i]));
minEnclosingCircle(contours_poly[i], center[i], radius[i]);
}
//画多边形轮廓 + 包围的矩形框 + 圆形框
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
for(int i = 0; i< contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));
//drawContours(drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point());
//rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0);
circle(src_gray, center[i], (int)radius[i], color, 2, 8, 0);
}
//保存结果
imwrite("Contours.jpg", src_gray);
}
int main()
{
//加载源图像
Mat src = imread("10.jpg", 1);
Mat src_gray;
//转成灰度并模糊化降噪
cvtColor(src, src_gray, CV_BGR2GRAY);
blur(src_gray, src_gray, Size(3,3));
thresh_callback(src_gray, 65);
return 0;
}
2.编译源码
$ g++ -o test test.cpp -std=c++11 -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_ml -Wl,-rpath=/usr/local/lib
3.运行及其结果
10.jpgContours.jpg
网友评论