我想提取一张图像的轮廓,以点坐标的形式表示。
使用 Canny
函数,我能够产生一个仅包含图像边缘的二进制图像。然后,我尝试使用 findContours
函数来提取轮廓。但是结果不太好。
对于每个边缘,我经常得到两条线,就好像它被认为是非常细的区域。
我想简化我的轮廓,使它们可以绘制成单独的线段。或者使用另一个函数来提取它们,直接产生正确的结果可能更好。
我已经查看了 OpenCV 的文档,但没有找到有用的内容,但我想我不是第一个遇到这样问题的人。有没有我可以使用的函数或方法?
以下是我目前编写的 Python 代码:
def main():
img = cv2.imread("lena-mono.png", 0)
if img is None:
raise Exception("Error while loading the image")
canny_img = cv2.Canny(img, 80, 150)
contours, hierarchy = cv2.findContours(canny_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
scale = 10
contours_img = cv2.resize(contours_img, (0, 0), fx=scale, fy=scale)
for cnt in contours:
color = np.random.randint(0, 255, (3)).tolist()
cv2.drawContours(contours_img,[cnt*scale], 0, color, 1)
cv2.imwrite("canny.png", canny_img)
cv2.imwrite("contours.png", contours_img)
比例因子用于强调轮廓的双线。
以下是图像链接:
- Lena 灰度
- 使用
Canny
提取的边缘 - 实际轮廓:10倍缩放,您可以看到由
findContours
产生的错误结果
非常感谢任何建议。