Why do I get this error? 'NoneType' object has no attribute 'shape' in opencv

6.5k views Asked by At

I'm working on real-time clothing detection. so i borrowed the code from GitHub like this:https://github.com/rajkbharali/Real-time-clothes-detection but (H, W) = frame.shape[:2]:following error in last line. Where should I fix it?

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]
1

There are 1 answers

0
MohammadHosseinZiyaaddini On BEST ANSWER

The reason behind your error is that the frame is None(Null). Sometimes, the first frame that is captured from the webcam is None mainly because (1) the webcam is not ready yet ( and it takes some extra second for it to get ready) or (2) the operating system does not allow your code to access the webcam.

In the first case, before you do anything on the frame you need to check whether the frame is valid or not :

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

In the other case, you need to check the camera setting in your Operating system.

Also, for capturing the webcam frames there is another method based on the VideoCapure class in Opencv that might be easier to debug.