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

2024-04-29 04:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提取一个图像的轮廓,我试图用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等)


Tags: 函数from图像imageimportmatplotlibshoworigin
3条回答

如果你想坚持你的轮廓方法,你可以简单地添加一个级别参数,值'阈值'之间的白色背景和叶子的图像。

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

所以:

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

enter image description here

如果您想做一些严肃的图像处理,请确保签出Scikit图像。它包含了多种边缘检测算法等

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

对于那些想要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”必须是单通道数组。

您应该更改threshold函数、findContours函数和drawcours函数的参数以获得所需的结果。

我在drawContours函数中执行到“in t”的转换,因为Open CV 2.4.3版本中有一个bug,如果不执行此转换,程序将中断。 This is the bug

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

你也必须对你的形象设定门槛。

相关问题 更多 >