使用带有小内核和多次迭代的 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)
使用 cv.MORPH_RECT 和 3x3 内核进行 10 次迭代:
使用 cv.MORPH_CROSS 和 3x3 内核进行 10 次迭代:
您可以通过调整迭代次数来改变偏移量。
更准确的方法是使用 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