2014-11-05 119 views
0

我是OpenCV-Python的新手。
我想獲得convexityDefects,我有以下代碼,如下所示。OpenCV-Python中的凸性缺陷

import cv2 
import numpy as np 

img = cv2.imread('s4.png') 
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 
ret, thresh = cv2.threshold(img_gray, 127, 255,0) 
contours,hierarchy = cv2.findContours(thresh,2,1) 
cnt = contours[0] 

hull = cv2.convexHull(cnt,returnPoints = False) 
defects = cv2.convexityDefects(cnt,hull) 

# some codes here..... 

但是,當我跑我得到一個錯誤代碼..

Traceback (most recent call last): 
    File "C:/Users/jasonc/Desktop/Pyhton/convexityDefects", line 11, in <module> 
    defects = cv2.convexityDefects(cnt,hull) 
error: ..\..\..\OpenCV-2.4.4\modules\imgproc\src\contours.cpp:1969: error: (-215) ptnum > 3 

有什麼不對?我搜索了互聯網,大部分的例子看起來都一樣。

+0

因此,您需要超過3分的凸性缺陷。確保cnt包含3個以上的元素。 – berak 2014-11-05 06:32:40

+0

當我打印出cnt時,我得到了這個結果:[[[394 638]] [[395 638]]]。我現在應該怎麼做? – user3988645 2014-11-05 07:39:20

回答

0

所以問題是,cv2.findContours(thresh,2,1)給你一個單獨的輪廓,而不是一個輪廓的列表。在您從中獲得此代碼的教程中,星形圖像非常平滑,所以findContours命令在輪廓[0]處返回單個輪廓。什麼是s4.jpg都不能平滑連續,因此findContours正在返回輪廓列表。解決這個問題的辦法是減少所有輪廓。

numberofpoints = 0 
for contour in contours: 
    for point in contour: 
    numberofpoints = numberofpoints +1 

allcountours = np.zeros((numberofpoints,1,2), dtype=np.int32) 
count = 0 
for contour in contours: 
    for point in contour: 
     allcountours[count][0] = [point[0][0],point[0][1]] 
     count = count + 1 
cnt = allcountours 

這應該會給你一個大輪廓。因此cnt = allcountours應該給你正確的解決方案。

我在嘗試跟蹤時遇到了同樣的問題爲手的圖像創建凸包和缺陷。