Python OpenCV仅在外轮廓绘制轮廓

2 投票
2 回答
10985 浏览
提问于 2025-05-10 15:09

在使用OpenCV的drawContours画轮廓时,边框是画在轮廓的中心位置的。我想要的是只在轮廓的外面画边框。

这张图片(来自SketchUp的文档)最能说明这个问题:

这里输入图片描述

drawContours画出的轮廓就像第一个圆圈那样(轮廓在画出的边框中间)。我需要的是边框只在轮廓的外面,就像最后一个圆圈那样。

有没有人知道我该怎么做到这一点呢?

谢谢。

相关文章:

  • 暂无相关问题
暂无标签

2 个回答

2

假设内部核心的颜色始终是均匀的,并且你事先知道核心颜色的值,我们可以简单地这样做:

#First you draw the contour on both the sides of the border.
contour_id = 0
border_thickness = 10
border_color = (185, 115, 72)
cv2.drawContours(img, contours, contour_id, border_color, border_thickness)

#Now you again draw contour but with thickness = -1 and color = Core color
border_thickness = -1
core_color = (225, 141, 98)
cv2.drawContours(img, contours, contour_id, core_color, border_thickness)
2

使用以下代码:

  _ret, contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
  cv2.drawContours(img,contours , -1, (255,0,0), 1)

这里的 cv2.RETR_EXTERNAL 只会返回外部检测到的轮廓。

撰写回答