我需要一段使用c++和opencv库编写的轮廓检测代码
时间: 2023-03-28 09:04:33 浏览: 114
你好,以下是使用 C 和 OpenCV 库编写的轮廓检测代码示例:
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
if (argc != 2)
{
printf("Usage: ./contour_detection <image_path>\n");
return -1;
}
Mat image = imread(argv[1], IMREAD_GRAYSCALE);
if (image.empty())
{
printf("Failed to read image: %s\n", argv[1]);
return -1;
}
Mat binary;
threshold(image, binary, 128, 255, THRESH_BINARY);
std::vector<std::vector<Point>> contours;
std::vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
Mat result = Mat::zeros(image.size(), CV_8UC3);
RNG rng(12345);
for (size_t i = ; i < contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(, 256), rng.uniform(, 256), rng.uniform(, 256));
drawContours(result, contours, i, color, 2, LINE_8, hierarchy, );
}
imshow("Contours", result);
waitKey();
return ;
}
希望对你有帮助。
阅读全文