在代码中获取以下错误
TypeError: 'NoneType' object is not subscriptable
line : crop_img = img[70:300, 70:300]
有人可以帮我吗?
非常感谢
img_dofh = cv2.imread("D.png",0)
ret, img = cap.read()
cv2.rectangle(img,(60,60),(300,300),(255,255,2),4) #outer most rectangle
crop_img = img[70:300, 70:300]
crop_img_2 = img[70:300, 70:300]
grey = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
答案 0 :(得分:0)
您不会显示img
变量的来源。但是不知何故,它是None
而不是包含图像数据。
通常在编写应该返回img
的有效对象的函数时发生这种情况,但是您忘记在函数中包含return
语句,因此它会自动返回{{1} }。
检查创建None
的代码。
更新
响应您的代码发布:
如果您可以提供minimal, reproducible example,将很有帮助。可能看起来像这样:
img
从documentation看,看来您的相机到代码中的这一点时可能尚未抓取任何帧。该文档说:“如果没有抓取任何帧(相机已断开连接,或者视频文件中没有其他帧),则这些方法将返回false,而这些函数将返回NULL指针。”我敢打赌import cv2
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, img = cap.read()
if img is None:
print("img was not returned.")
else:
crop_img = img[70:300, 70:300]
print(crop_img) # should show an array of image data
函数将返回一个NULL指针,当它返回给Python时,它将转换为.read()
。
不幸的是,由于没有其他人设置您的特定相机,因此其他人可能无法重现您的问题。
上面的代码在MacBook Pro上可以正常使用,但我必须在第一次尝试时授予终端使用相机的权限。您是否尝试过重启终端应用程序?您的程序可以访问相机吗?