为什么我在使用 opencv python 进行移动物体检测时遇到错误?

Why I am facing an error in moving object detection using opencv python?

我正在使用 VS 代码作为 IDE 使用 Opencv 编写我的移动物体检测代码 python 但我有错误

Traceback (most recent call last):
  File "d:\Programming\Python programming\Moving_Object_detection.py", line 13, in 
    img = imutils.resize(img, width=500)
  File "D:\Python Vscode\lib\site-packages\imutils\convenience.py", line 69, in resize
    (h, w) = image.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'

所以你能给我解决方案吗?我正在为您提供我的代码

import cv2
import time
import imutils

cam = cv2.VideoCapture(2)
time.sleep(1)

firstFrame = None
area = 500
# count = 0

while True:
    _, img = cam.read()
    text = "Normal"
    img = imutils.resize(img, width=500, height=500)
    grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gaussianImg = cv2.GaussianBlur(grayImg, (21, 21), 0)
    if firstFrame is None:
        firstFrame = gaussianImg
        continue
    imgDiff = cv2.absdiff(firstFrame, gaussianImg)
    threshImg = cv2.threshold(imgDiff, 25, 255, cv2.THRESH_BINARY)[1]
    threshImg = cv2.dilate(threshImg, None, iterations=2)
    cnts = cv2.findContours(threshImg.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    for c in cnts:
        if cv2.contourArea(c) < area:
            continue
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # count = count +  1
        text = "Moving Object detected"
    print(text)
    cv2.putText(img, text, (10, 20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
    cv2.imshow("cameraFeed", img)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

cam.release()
cv2.destroyAllWindows()

您的问题很可能是 openCV 无法读取您的网络摄像头,或者您的网络摄像头的索引可能有误,或者它没有查看您的网络摄像头的权限。如果您仍需要更多帮助,请参阅 link 打开 CV 指南以解决 none 类型问题。

关于解决 none 类型错误的页面
https://www.pyimagesearch.com/2016/12/26/opencv-resolving-nonetype-errors/

首先,像您这样阅读帧是不好的做法。 cam.read() 中的另一个 return 值是有目的的。

success, cv_img = cam.read()
if success:
   # do whatever
else:
   print('capturing failed')

其次,如果如前所述,这是相机问题,请尝试禁用防病毒软件。看到好几次都打不开,因为被杀毒软件屏蔽了