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, thresh*2, 3);
//寻找轮廓
findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
//绘出轮廓
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, i, color, 2, 8, hierarchy, 0, Point());
}
//保存结果
imwrite("Contours.jpg", drawing);
}
int main()
{
//加载源图像
Mat src = imread("7.jpeg", 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.运行及其结果
7.jpegContours.jpg
网友评论