使用Python提取图像的外部轮廓或轮廓线。

9

我想提取一张图像的轮廓,我试图使用MatplotLib的轮廓函数来实现这一目标。以下是我的代码:

from PIL import Image
from pylab import *

# read image to array
im = array(Image.open('HOJA.jpg').convert('L'))

# create a new figure
figure()

# show contours with origin upper left corner
contour(im, origin='image')
axis('equal')

show()

这是我的原始图片:

Original

而这是我的结果:

Contour

但我只想显示外部轮廓,也就是这个例子中的红色线条。

我查阅了contour函数的文档,但无法得到我想要的效果。

如果您知道在Python中更好的方法,请告诉我!(比如MatplotLib、OpenCV等)

3个回答

15
如果您想坚持使用轮廓法,可以简单地添加一个级别参数,并将图像的值设为“阈值”,使其在白色背景和叶子之间进行阈值处理。您可以使用直方图找到适当的阈值。但在这种情况下,任何低于255的值都可以使用。 因此:
contour(im, levels=[245], colors='black', origin='image')

enter image description here

如果您想进行一些严肃的图像处理,请确保您查看Scikit-Image。它包含多个边缘检测算法等。

http://scikit-image.org/docs/dev/auto_examples/


8

对于那些想要OpenCV解决方案的人,这是它:

ret,thresh = cv2.threshold(image,245,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

tam = 0

for contorno in contours:
    if len(contorno) > tam:
        contornoGrande = contorno
        tam = len(contorno)

cv2.drawContours(image,contornoGrande.astype('int'),-1,(0,255,0),2)

cv2.imshow('My image',image)

cv2.waitKey()
cv2.destroyAllWindows()

在这个例子中,我只绘制最大的轮廓。请记住,“image”必须是单通道数组。
您应该更改阈值函数、findContours函数和drawContours函数的参数以获得所需结果。 在drawContours函数中进行“int”转换,因为Open CV 2.4.3版本中存在一个错误,如果不进行此转换,程序将会崩溃。 这就是那个错误

0
我建议使用OpenCV来提高性能。 它有一个findContour函数,可以通过cv2绑定从Python访问。 该函数可以设置为仅返回外部轮廓。
您还需要对图像进行阈值处理。

1
你能贴出使用OpenCV提取外部轮廓的代码吗? - Xithias
我正准备回答你,看来太晚了! - Nicolas Barbey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接