本文共 1897 字,大约阅读时间需要 6 分钟。
今天,我们将学习如何使用OpenCV进行图像轮廓检测。通过本文的步骤,您将能够创建一个能够检测并绘制图像轮廓的C++程序。
#include#include #include using namespace cv;using namespace std;Mat src, temp, dst;int threshold_value = 100;int threshold_max = 255;char *output = "output image";RNG rng;void COutours_Demo(int, void*);int main() { // 加载图像 src = imread("E:\\vs2015\\opencvstudy\\27police.jpg"); if (!src.data) { cout << "could not load image!" << endl; return -1; } imshow("inputImage", src); // 转换为灰度图像 cvtColor(src, src, CV_BGR2GRAY); imshow("grayImage", src); // 创建滑动条 namedWindow(output, CV_WINDOW_AUTOSIZE); createTrackbar("Size", output, &threshold_value, threshold_max, COutours_Demo); COutours_Demo(0, 0); waitKey(0); return 0;}void COutours_Demo(int, void*) { Mat canny_output; Canny(src, canny_output, threshold_value, threshold_value * 2, 3, false); vector contours; vector hierarchy; findContours(canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); dst = Mat::zeros(src.size(), src.type()); RNG rng(12345); for (size_t i = 0; i < contours.size(); i++) { Vec3b color = Vec3b(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); drawContours(dst, contours, i, color, 2, 8, hierarchy, 0, Point(0, 0)); } imshow(output, dst);}
加载图像:使用imread函数加载输入图像。如果图像无法加载,程序会输出错误信息并退出。
转换为灰度图像:使用cvtColor将源图像转换为灰度图像,以便后续的轮廓检测。
创建滑动条:使用createTrackbar创建一个滑动条,用户可以通过滑动条调整阈值值,从而改变轮廓检测的结果。
检测轮廓:调用findContours函数,使用Canny算法检测图像中的轮廓,并将结果存储在contours和hierarchy中。
绘制轮廓:使用drawContours函数绘制轮廓,并为每个轮廓选择随机的颜色显示。
显示结果:最后使用imshow函数显示最终的轮廓图像,并通过waitKey函数等待用户输入后退出程序。
希望本文的代码和解释能帮助您成功实现图像轮廓检测。如果有任何问题或需要进一步的帮助,请随时联系我。
转载地址:http://pmsfk.baihongyu.com/