在Python中提取外部轮廓或图像轮廓

时间:2012-11-27 14:44:13

标签: python image-processing matplotlib

我想提取图像的轮廓,我正在尝试使用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 个答案:

答案 0 :(得分:14)

如果你想坚持你的轮廓方法,你可以简单地添加一个水平参数,其值为“阈值化”白色背景和叶子之间的图像。

您可以使用直方图找到合适的值。但在这种情况下,任何略低于255的值都可以。

所以:

contour(im, levels=[245], colors='black', origin='image')

enter image description here

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

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

答案 1 :(得分:5)

对于那些想要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版本中存在错误,如果您不进行此转换,程序会中断。 This is the bug

答案 2 :(得分:0)

我建议使用OpenCV来提高性能。 它有一个findContour函数,可以使用cv2绑定从python访问。 此功能可以设置为仅返回外部轮廓。

您还必须为图像设置阈值。

相关问题