簡體   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