Python 2.7 OpenCV Python中的凸性缺陷

Python 2.7 OpenCV Python中的凸性缺陷,python-2.7,opencv,Python 2.7,Opencv,我是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

我是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
回溯(最近一次呼叫最后一次):
文件“C:/Users/jasonc/Desktop/Pyhton/凸面缺陷”,第11行,在
缺陷=cv2.凸面缺陷(碳纳米管、外壳)
错误:..\..\..\OpenCV-2.4.4\modules\imgproc\src\contours.cpp:1969:错误:(-215)ptnum>3

怎么了?我在互联网上搜索过,大多数示例看起来都是一样的。

所以问题是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应该为您提供正确的解决方案


我在尝试为手的图像创建凸面外壳和缺陷时遇到了相同的问题。

因此,凸面缺陷需要3个以上的点。请确保cnt包含3个以上的元素。当我打印出cnt时,我得到以下结果:[[394 638]][[395 638]]。我现在该怎么办?