从cv::Mat中的cv::Point的矢量转换轮廓

Converting contours from vector of cv::Point in cv::Mat

本文关键字:cv 转换 轮廓 Point Mat 中的      更新时间:2023-10-16

假设我的目标是从初始图像中提取轮廓。我使用OpenCV:执行了此操作

cv::Mat gray, edges;
cv::cvtColor(image, gray, CV_BGRA2GRAY);
cv::Canny(gray, edges, 100, 300, 3);
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(edges, contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

现在,轮廓包含在一个点数组中。我想重建一个与初始图像具有相同尺寸的cv::Mat结构,以便通过将其叠加到图像上来强调轮廓。

特别是,我对立即绘制轮廓不感兴趣。我将执行以下操作:

  • 提取轮廓
  • 扩大轮廓
  • 将轮廓叠加在图像上(就像在边缘锐化中一样)

因此,轮廓必须是与输入图像大小相同的矩阵。

我该怎么做?

提前谢谢。

您可以重新构建矩阵

Mat image_contours_grayscale = Mat::zeros(gray.size(),gray.type());
Scalar color(255);
drawContours( image_contours_grayscale, contours,-1,color,1);

我不确定drawContours是否适用于灰度图像,但如果不适用,你可以试试这个

Mat image_contours_color = Mat::zeros(image.size(),image.type());
Scalar color(255,255,255);
drawContours( image_contours_color, contours,-1,color,1);
Mat image_contours_grayscale;
cv::cvtColor(image_contours_color, image_contours_grayscale, CV_BGRA2GRAY);

image_contours_grascale应该是灰度图像,全部为黑色,轮廓为白色。

让我知道这是否有效,我没有机会测试这个解决方案!