Search code examples
pythonflaskobject-detectionnon-type

NoneType' object has no attribute 'shape


I am trying to do my detection but dont know why this error is comming up dont know whats the issue with this when i start the detection the cam stops and it gives the shape error of nonetype. It was running before but dont know what happen and its stop working and giving me this error.Can anyone can help me.

from flask import Flask,render_template,Response
import cv2
import numpy as np

app = Flask(__name__)

net = cv2.dnn.readNet('project-files/yolov4-custom.cfg', 'project-files/yolov4.weights')
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
scale_factor =1.3

with open("project-files/coco.names", "r") as f:
    classes = f.read().splitlines()
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/page1/')
def page1():
    return render_template('page1.html')
def obdetect():
    net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
    net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
    cap = cv2.VideoCapture(0)
    while True:

        _, img = cap.read()
        height, width, _ = img.shape
        blob = cv2.dnn.blobFromImage(img, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)
        net.setInput(blob)
        output_layers_names = net.getUnconnectedOutLayersNames()
        layeroutputs = net.forward(output_layers_names)
        boxes = []
        confidences = []
        class_ids = []
        for output in layeroutputs:
            for detection in output:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]
                if confidence > 0.5:
                    center_x = int(detection[0] * width)
                    center_y = int(detection[1] * height)
                    w = int(detection[2] * width)
                    h = int(detection[3] * height)
                    x = int(center_x - w / 2)
                    y = int(center_y - h / 2)

                    boxes.append([x, y, w, h])
                    confidences.append((float(confidence)))
                    class_ids.append(class_id)
            # it will remove the duplicate detections in our detection
        indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.2, 0.4)
        if len(indexes) > 0:
            for i in indexes.flatten():
                x, y, w, h = boxes[i]
                label = str(classes[class_ids[i]])
                confidence = str(round(confidences[i], 2))
                color = colors[i]
                cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
                cv2.putText(img, label + " " + confidence, (x, y + 20), font, 2, (255, 0, 0), 2)
        _, jpeg = cv2.imencode('.jpg', img)

        yield (b'--frame\r\n'
               b'Content-Type:image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n')

        cap.release()

@app.route('/video_feed')
def video_feed():
    return Response(obdetect(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
    app.run(threaded=True)

error

(base) C:\Users\sanja\OneDrive\Documents\flask>flask run
 * Serving Flask app "main"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [07/Jun/2021 18:43:41] "←[37mGET / HTTP/1.1←[0m" 200 -
127.0.0.1 - - [07/Jun/2021 18:43:41] "←[37mGET /static/logo-1-144x144.png HTTP/1.1←[0m" 200 -
127.0.0.1 - - [07/Jun/2021 18:43:43] "←[37mGET /page1/ HTTP/1.1←[0m" 200 -
127.0.0.1 - - [07/Jun/2021 18:43:55] "←[37mGET /video_feed HTTP/1.1←[0m" 200 -
[ WARN:1] global C:\project files\opencv-4.5.2\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Error on request:
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\serving.py", line 323, in run_wsgi
    execute(self.server.app)
  File "C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\serving.py", line 314, in execute
    for data in application_iter:
  File "C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\wsgi.py", line 506, in __next__
    return self._next()
  File "C:\ProgramData\Anaconda3\Lib\site-packages\werkzeug\wrappers\base_response.py", line 45, in _iter_encoded
    for item in iterable:
  File "C:\Users\sanja\OneDrive\Documents\flask\main.py", line 31, in obdetect
    height, width, _ = img.shape
AttributeError: 'NoneType' object has no attribute 'shape'

Solution

  • img = cv2.imread('../input/image-classification-2/train/{}'.format(f))
    

    in my case f had value with .jpg at last so the path name became ....jpg.jpg Try removing .jpg from imencode