【问题标题】:'NoneType' object has no attribute 'shape' in OpenCV recursion [duplicate]'NoneType'对象在OpenCV递归中没有属性'shape'[重复]
【发布时间】:2021-12-31 00:58:08
【问题描述】:

我遇到了一个问题:代码的工作原理是,当汽车经过摄像头时,会保存其经过的视频,然后函数通过递归再次启动,但恰好在第 4 个循环时,代码给出了错误

    (H, W) = image.shape[:2]

AttributeError: 'NoneType' 对象没有属性 'shape'

这是代码本身:

   import cv2 as cv
import numpy as np
import uuid
import os.path
import os
def camera():
    print("new cycle")
    confThreshold = 0.6
    nmsThreshold = 0.1
    inpWidth = 416
    inpHeight = 416
    classesFile = "car.names"
    classes = None
    with open(classesFile, 'rt') as f:
        classes = f.read().rstrip('\n').split('\n')
    modelConf = "car.cfg"
    modelWeights = "cars_last.weights"
    cap = cv.VideoCapture("rtsp://.../user=admin_password=tlJwpbo6_channel=1_stream=0.sdp?real_stream:")
    ret, image = cap.read()
    (H, W) = image.shape[:2]
    global empty
    global newname
    newname = str(uuid.uuid4())
    global output
    output = cv.VideoWriter(newname+'.avi', cv.VideoWriter_fourcc('M','J','P','G'), 10,
                            (W, H))
    print(newname)
    empty = []
    def postprocess(frame, outs):
        frameHeight = frame.shape[0]
        frameWidth = frame.shape[1]

        classIDs = []
        confidences = []
        boxes = []
        boxes1=[]
        cv.cvtColor(frame, cv.COLOR_RGB2BGR)

        for out in outs:
            for detection in out:

                scores = detection[5:]
                classID = np.argmax(scores)
                confidence = scores[classID]

                if confidence > confThreshold:
                    centerX = int(detection[0] * frameWidth)
                    centerY = int(detection[1] * frameHeight)

                    width = int(detection[2] * frameWidth)
                    height = int(detection[3] * frameHeight)

                    left = int(centerX - width / 2)
                    top = int(centerY - height / 2)
                    x = int(centerX - (width / 2))
                    y = int(centerY - (height / 2))
                    boxes1.append([x, y, int(width), int(height)])
                    classIDs.append(classID)
                    confidences.append(float(confidence))
                    boxes.append([left, top, width, height])
        idxs = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
        if len(idxs) > 0:
            empty.clear()
            empty.append(0)
        else:
            empty.append(1)
        if len(empty)>100:
            empty.clear()
            if (os.path.isfile(newname+".avi"))==True and os.path.getsize(newname+".avi")!=0:
                camera()


        indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
        for i in indices:
            i = i[0]
            box = boxes[i]
            left = box[0]
            top = box[1]
            width = box[2]
            height = box[3]

            drawPred(classIDs[i], confidences[i], left, top, left + width, top + height)
            output.write(frame)


    def drawPred(classId, conf, left, top, right, bottom):
        # Draw a bounding box.
        cv.rectangle(frame, (left, top), (right, bottom), (255, 178, 50), 3)

        label = '%.2f' % conf

        # Get the label for the class name and its confidence
        if classes:
            assert (classId < len(classes))
            label = '%s:%s' % (classes[classId], label)

        
        labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
        top = max(top, labelSize[1])
        cv.rectangle(frame, (left, top - round(1.5 * labelSize[1])), (left + round(1.5 * labelSize[0]), top + baseLine),
        (255, 255, 255), cv.FILLED)
        cv.rectangle(frame, (left,top),(right,bottom), (255,255,255), 1 )
        cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 0), 1)



    def getOutputsNames(net):
        layersNames = net.getLayerNames()

        return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]

    net = cv.dnn.readNetFromDarknet(modelConf, modelWeights)
    net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
    net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)

    winName = 'DL OD with OpenCV'
    cv.namedWindow(winName, cv.WINDOW_NORMAL)



    while cv.waitKey(1) < 0:

        hasFrame, frame = cap.read()

        blob = cv.dnn.blobFromImage(frame, 1 / 255, (inpWidth, inpHeight), [0, 0, 0], 1, crop=False)

        net.setInput(blob)
        outs = net.forward(getOutputsNames(net))

        postprocess(frame, outs)

        cv.imshow(winName, frame)
    cap.release()
    output.release()
camera()

【问题讨论】:

标签: python python-3.x opencv pycharm yolo


【解决方案1】:

正如文档中关于读取功能的发现:

参数 [出去] 图片 视频帧在这里返回。如果没有抓取任何帧,则图像将为空。

您应该检查退货状态以了解您是否有图像数据。

返回 如果没有抓取到任何帧,则返回 false

【讨论】:

  • 我应该让它的视频流不间断我正在使用 rtsp 播放器和另一个只显示检测结果的脚本检查它
  • 再加上 1 件事我现在发现周期数并不总是 4 现在它在第三个就坏了
  • waitkey(1) 将仅等待 1 毫秒。如果您的 im/s 小于 1000,则可能会很短。尝试增加延迟。
  • 解决了问题
【解决方案2】:

我所要做的就是将相机连接排除在递归之外,我已将它放在相机功能之外以寻求帮助)

    cap = cv.VideoCapture("rtsp:///user=admin_password=tlJwpbo6_channel=1_stream=0.sdp?real_stream:")
ret, image = cap.read()

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2021-01-10
    • 2016-09-20
    • 2019-05-21
    相关资源
    最近更新 更多