如何在 OpenCV 中获得扩展或收缩的轮廓?

How to get an expanded or contracted contour in OpenCV?

是否可以获得轮廓的扩展或收缩版本?

例如在下图中,我在二值图像上使用 cv::findContour() 和 cv::drawContour 来获取轮廓:

我想绘制另一个与原始轮廓具有自定义像素距离的轮廓,如下所示:

除了侵蚀,我认为这可能不是一个好主意,因为使用侵蚀似乎很难控制像素距离,我不知道如何解决这个问题。我可以知道正确的方向应该是什么吗?

使用具有小内核和多次迭代的 cv::erode 可能足以满足您的需求,即使它不准确。

C++代码:

cv::Mat img = ...;
int iterations = 10;
cv::erode(img, img,
   cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3,3)),
   cv::Point(-1,-1),
   iterations);

演示:

# img is the image containing the original black contour
for form in [cv.MORPH_RECT, cv.MORPH_CROSS]:
    eroded = cv.erode(img, cv.getStructuringElement(form, (3,3)), iterations=10)
    contours, hierarchy = cv.findContours(~eroded, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
    vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
    cv.drawContours(vis, contours, 0, (0,0,255))
    cv.drawContours(vis, contours, 1, (255,0,0))
    show_image(vis)

10 次迭代 cv.MORPH_RECT,内核为 3x3:

10 次迭代 cv.MORPH_CROSS,内核为 3x3:

您可以通过调整迭代次数来更改偏移量。

更准确的方法是使用 cv::distanceTransform 找到距离轮廓大约 10px 的所有像素:

dist = cv.distanceTransform(img, cv.DIST_L2, cv.DIST_MASK_PRECISE)
ring = cv.inRange(dist, 9.5, 10.5) # take all pixels at distance between 9.5px and 10.5px
show_image(ring)
contours, hierarchy = cv.findContours(ring, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
cv.drawContours(vis, contours, 0, (0,0,255))
cv.drawContours(vis, contours, 2, (255,0,0))
show_image(vis)

您将在原始轮廓的每一侧得到两个轮廓。使用带 RETR_EXTERNAL 的 findContours 仅恢复外部轮廓。要同时恢复内部轮廓,请使用 RETR_LIST

我认为解决方案可以更简单,无需扩张和新轮廓。

  1. 对于每个轮廓搜索质量中心:cv::moments(contours[i]) -> cv::Point2f mc(mu.m10 / mu.m00), mu.m01 / mu.m00));

  2. 轮廓的每个点:质心平移->乘以系数K->向后平移:pt_new = (k * (pt - mc) + mc) ;

但是每个点的系数k必须是单独的。待会儿再算算...