python - OpenCV 脚本:AttributeError:“NoneType”对象没有属性“shape”
问题描述
我正在尝试在 OpenCV 3.4.1、Python 3.6.5 上运行以下脚本,但我不断收到错误消息:line 41, in <module> for i in range(defects.shape[0]): AttributeError: 'NoneType' object has no attribute 'shape'
我尝试更改for i in range(defects.shape[0])
为,for i in len(defects)
但这会导致错误:TypeError: object of type 'NoneType' has no len()
我没有使用 Python 或 OpenCV 的经验,因此将不胜感激!
这是脚本:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while( cap.isOpened() ) :
ret,img = cap.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
ret,thresh1 = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
drawing = np.zeros(img.shape,np.uint8)
max_area=0
for i in range(defects.shape[0]):
cnt=contours[i]
area = cv2.contourArea(cnt)
if(area>max_area):
max_area=area
ci=i
cnt=contours[ci]
hull = cv2.convexHull(cnt)
moments = cv2.moments(cnt)
if moments['m00']!=0:
cx = int(moments['m10']/moments['m00']) # cx = M10/M00
cy = int(moments['m01']/moments['m00']) # cy = M01/M00
centr=(cx,cy)
cv2.circle(img,centr,5,[0,0,255],2)
cv2.drawContours(drawing,[cnt],0,(0,255,0),2)
cv2.drawContours(drawing,[hull],0,(0,0,255),2)
cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
hull = cv2.convexHull(cnt,returnPoints = False)
if(1):
defects = cv2.convexityDefects(cnt,hull)
mind=0
maxd=0
for i in range(defects.shape[0]):
s,e,f,d = defects[i,0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
dist = cv2.pointPolygonTest(cnt,centr,True)
cv2.line(img,start,end,[0,255,0],2)
cv2.circle(img,far,5,[0,0,255],-1)
print(i)
i=0
cv2.imshow('output',drawing)
cv2.imshow('input',img)
k = cv2.waitKey(10)
if k == 27:
break
解决方案
推荐阅读
- javascript - 如何计算带有对象的数组中的特定键?
- firebase - 无法使用云功能从 Firebase 获取数据
- ruby-on-rails - 嵌套资源和强参数应该使用“模型”还是“模型属性”,为什么?(不允许参数:型号)
- oracle - 单击按钮,将新行添加到表单
- flutter - 页面控制器轮播
- javascript - (Mithril) TypeError: m is not a function... 'm' is an instance of Object
- java - 在中央找不到工件 com.sun.xml.bind:jaxb-impl:jar:2.0EA3
- spring - 在哪里验证 Spring/Hibernate 中字段的唯一性
- android - Play 商店中的 Android 应用程序有 2 个版本,旧版本和新版本
- c# - 如何更改 C# AWS 客户端 Lambda 调用请求超时