繁体   English   中英

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

[英]Extract external contour or silhouette of image in 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()

这是我原来的形象:

原版的

这是我的结果:

轮廓

但我只想展示外部轮廓,轮廓。 只是这个例子中的读取行。

我该怎么做? 我阅读了轮廓功能的文档,但我无法得到我想要的东西。

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

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

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

所以:

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

在此输入图像描述

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

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'必须是单通道数组。

您应该更改阈值函数,findContours函数和drawContours函数的参数以获得所需的值。

我在drawContours函数中转换为'int',因为Open CV 2.4.3版本中存在错误,如果您不进行此转换,程序会中断。 这是错误

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM