首页 > 解决方案 > 为什么我会收到此错误?'NoneType'对象在opencv中没有属性'shape'

问题描述

我正在研究实时服装检测。所以我像这样从 GitHub 借用了代码:https ://github.com/rajkbharali/Real-time-clothes-detection 但是(H, W) = frame.shape[:2]:最后一行出现以下错误。我应该在哪里修复它?

from time import sleep
import cv2 as cv
import argparse
import sys
import numpy as np
import os.path
from glob import glob
import imutils
from imutils.video import WebcamVideoStream
from imutils.video import FPS

from google.colab import drive
drive.mount('/content/drive')

%cd /content/drive/My Drive/experiment/Yolo_mark-master/x64/Release/

Labels = []
classesFile1 = "data/obj.names";
with open(classesFile1, 'rt') as f:
    Labels = f.read().rstrip('\n').split('\n')

np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(Labels), 3), dtype="uint8")

weightsPath = "obj_4000.weights"
configPath = "obj.cfg"

net1 = cv.dnn.readNetFromDarknet(configPath, weightsPath)
net1.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net1.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)


image = WebcamVideoStream(src=0).start()
fps = FPS().start()
#'/home/raj/Documents/yolov3-Helmet-Detection-master/safety.mp4'

#while fps._numFrames<100:
while True:
#for fn in glob('images/*.jpg'):
    frame = image.read()
    #frame = imutils.resize(frame,width=500)
    (H, W) = frame.shape[:2]

标签: pythonnumpyopencvobject-detectionyolo

解决方案


您的错误背后的原因是框架是None(Null). 有时,从网络摄像头捕获的第一帧是 None 主要是因为 (1)网络摄像头尚未准备好(它需要一些额外的时间才能准备好)或(2)操作系统不允许您的代码访问网络摄像头。

在第一种情况下,在对框架执行任何操作之前,您需要检查框架是否有效:

while True:
 
    frame = image.read()
    if frame is not None:  # add this line
       
      (H, W) = frame.shape[:2]

在另一种情况下,您需要检查操作系统中的相机设置。

此外,为了捕获网络摄像头帧,还有另一种基于 Opencv 中的VideoCapure类的方法,它可能更容易调试。


推荐阅读