2014-11-05 94 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应该给你正确的解决方案。

我在尝试跟踪时遇到了同样的问题为手的图像创建凸包和缺陷。