【问题标题】:Extract external contour or silhouette of image in Python在Python中提取图像的外部轮廓或轮廓
【发布时间】:2012-11-15 05:15:06
【问题描述】:

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

这是我的原图:

这是我的结果:

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

我该怎么做?我阅读了contour 函数的文档,但我无法得到我想要的。

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

【问题讨论】:

    标签: python image-processing matplotlib


    【解决方案1】:

    如果您想坚持使用轮廓方法,您可以简单地在白色背景和叶子之间添加一个具有“阈值”值的级别参数。

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

    所以:

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

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

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

    【讨论】:

      【解决方案2】:

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

      您还必须对图像进行阈值处理。

      【讨论】:

      • 能否贴出使用OpenCV提取外轮廓的代码?
      • 我正要回答你。似乎为时已晚!
      【解决方案3】:

      对于那些想要 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()
      

      在这个例子中,我只画了最大的轮廓。请记住,“图像”必须是单通道数组。

      你应该改变阈值函数、findContours函数和drawContours函数的参数来得到你想要的。

      我在 drawContours 函数中转换为“int”,因为 Open CV 2.4.3 版本中存在错误,如果不进行此转换,程序会中断。 This is the bug.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-14
        • 2013-12-17
        • 2019-01-25
        • 2020-06-14
        • 2020-07-22
        • 2021-01-05
        • 2020-05-08
        • 2011-05-24
        相关资源
        最近更新 更多