#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
Mat src,dst;
void contours(int, void*);
int thresholdMax = 255;
int thresholdvalue = 100;
int main(int argc, char** argv)
{
src = imread("D:/test/fish.png");
if (!src.data)
{
printf("图片为空");
return -1;
}
cvtColor(src, dst, CV_BGR2GRAY);
namedWindow("output image");
createTrackbar("Canny thresh", "output image", &thresholdvalue, thresholdMax, contours);
contours(0,0);
imshow("input image", src);
waitKey(0);
return 0;
}
void contours(int, void *)
{
Mat canny_output;
dst = Mat::zeros(src.size(), CV_8UC3);
vector<vector<Point>> contours;
vector<Vec4i> hierachy;
/*边缘检测,thresholdvalue,thresholdvalue*2这两个参数比值一般来说是1:1.5、1:2、1:3*/
Canny(src, canny_output, thresholdvalue, thresholdvalue * 2, 3, false);
findContours(canny_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
RNG rng(12345);
for (size_t i = 0; i < contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255),rng.uniform(0, 255));
drawContours(dst, contours, (int)i, color, 1, LINE_AA, hierachy, 0, Point(0, 0));
}
imshow("output image", dst);
}
大致步骤:
- 先将图片转化为灰度图像
- 进行边缘检测
- 找到轮廓findContours
- 绘制轮廓drawContours
运行结果: