drawContours OpenCV c++ 问题
Issue with drawContours OpenCV c++
我在 python 中有一个代码,我正在将它移植到 C++。我在 OpenCV c++ 中遇到 drawContours
函数的奇怪问题。
self.contours[i] = cv2.convexHull(self.contours[i])
cv2.drawContours(self.segments[object], [self.contours[i]], 0, 255, -1)
这是python中的函数调用,厚度参数的值-1用于填充轮廓,结果如下
我在 C++ 中做的完全一样,
cv::convexHull(cv::Mat(contour), hull);
cv::drawContours(this->objectSegments[currentObject], cv::Mat(hull), -1, 255, -1);
但这是生成的图像:
(请仔细看convexhull
点,这个不容易看出来)。我只得到点而不是填充的多边形。我也试过使用 fillPoly
比如
cv::fillPoly(this->objectSegments[currentObject],cv::Mat(hull),255);
但无济于事。
请帮我解决这个问题。我确定我遗漏了一些非常微不足道但无法发现的东西。
函数 drawContours()
需要接收一系列轮廓,每个轮廓都是 "vector of points"。
您用作参数的表达式 cv::Mat(hull)
returns 格式不正确的矩阵,每个点都被视为一个单独的轮廓 - 这就是为什么您只看到几个像素的原因。
根据 cv::Mat::Mat(const std::vector<_Tp>& vec)
的文档,传递给构造函数的向量按以下方式使用:
STL vector whose elements form the matrix. The matrix has a single column and the number of rows equal to the number of vector elements.
考虑到这一点,您有两个选择:
- 转置您创建的矩阵(使用
cv::Mat::t()
- 直接用点向量的向量就可以了
下面的示例展示了如何直接使用向量:
cv::Mat output_image; // Work image
typedef std::vector<cv::Point> point_vector;
typedef std::vector<point_vector> contour_vector;
// Create with 1 "contour" for our convex hull
contour_vector hulls(1);
// Initialize the contour with the convex hull points
cv::convexHull(cv::Mat(contour), hulls[0]);
// And draw that single contour, filled
cv::drawContours(output_image, hulls, 0, 255, -1);
我在 python 中有一个代码,我正在将它移植到 C++。我在 OpenCV c++ 中遇到 drawContours
函数的奇怪问题。
self.contours[i] = cv2.convexHull(self.contours[i])
cv2.drawContours(self.segments[object], [self.contours[i]], 0, 255, -1)
这是python中的函数调用,厚度参数的值-1用于填充轮廓,结果如下
我在 C++ 中做的完全一样,
cv::convexHull(cv::Mat(contour), hull);
cv::drawContours(this->objectSegments[currentObject], cv::Mat(hull), -1, 255, -1);
但这是生成的图像:
(请仔细看convexhull
点,这个不容易看出来)。我只得到点而不是填充的多边形。我也试过使用 fillPoly
比如
cv::fillPoly(this->objectSegments[currentObject],cv::Mat(hull),255);
但无济于事。 请帮我解决这个问题。我确定我遗漏了一些非常微不足道但无法发现的东西。
函数 drawContours()
需要接收一系列轮廓,每个轮廓都是 "vector of points"。
您用作参数的表达式 cv::Mat(hull)
returns 格式不正确的矩阵,每个点都被视为一个单独的轮廓 - 这就是为什么您只看到几个像素的原因。
根据 cv::Mat::Mat(const std::vector<_Tp>& vec)
的文档,传递给构造函数的向量按以下方式使用:
STL vector whose elements form the matrix. The matrix has a single column and the number of rows equal to the number of vector elements.
考虑到这一点,您有两个选择:
- 转置您创建的矩阵(使用
cv::Mat::t()
- 直接用点向量的向量就可以了
下面的示例展示了如何直接使用向量:
cv::Mat output_image; // Work image
typedef std::vector<cv::Point> point_vector;
typedef std::vector<point_vector> contour_vector;
// Create with 1 "contour" for our convex hull
contour_vector hulls(1);
// Initialize the contour with the convex hull points
cv::convexHull(cv::Mat(contour), hulls[0]);
// And draw that single contour, filled
cv::drawContours(output_image, hulls, 0, 255, -1);