AttributeError: 'tuple' 对象没有属性 'write' ,实例分割 python

问题描述

我用过这个博客代码“https://learnopencv.com/deep-learning-based-object-detection-and-instance-segmentation-using-mask-r-cnn-in-opencv-python-c /" 题为在 Python 中使用 OpenCV 中的 Mask R-CNN 进行基于深度学习的对象检测和实例分割。我正在使用实时流并希望对其进行对象检测和实例分割,并修改了下面的代码,其余代码博客中的解释相同

input_path = 'rtsp://...'
cap = cv.VideoCapture(input_path)
print(cap.isOpened())

# We need to set resolutions. 
# so,convert them from float to integer. 
frame_width = int(cap.get(3)) 
frame_height = int(cap.get(4)) 
size = (frame_width,frame_height) 

#cv2.VideoWriter( filename,fourcc,fps,frameSize )
result = cv.VideoWriter('sample.avi',cv.VideoWriter_fourcc(*'MJPG'),22,size),round(cap.get(cv.CAP_PROP_FRAME_HEIGHT))


while True:
    ret,frame = cap.read()
    if ret:
        
        # You can do processing on this frame variable
        blob = cv.dnn.blobFromImage(frame,swapRB=True,crop=False)

        # Set the input to the network
        net.setInput(blob)

        # Run the forward pass to get output from the output layers
        Boxes,masks = net.forward(['detection_out_final','detection_masks'])

        # Extract the bounding Box and mask for each of the detected objects
        postprocess(Boxes,masks)

        # Put efficiency @R_57_4045@ion.
        t,_ = net.getPerfProfile()
        label = 'Mask-RCNN : Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
        cv.putText(frame,label,(0,15),cv.FONT_HERShey_SIMPLEX,0.5,0))

        result.write(frame.astype(np.uint8))

        cv.imshow("winName",frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

result.release()
cap.release()
cv.destroyAllWindows()

运行此程序时出现以下错误

AttributeError                            Traceback (most recent call last)
<ipython-input-10-9712242a2634> in <module>
     36         cv.putText(frame,0))
     37 
---> 38         result.write(frame)
     39 
     40         cv.imshow("winName",frame)

AttributeError: 'tuple' object has no attribute 'write'

如何纠正这个错误

解决方法

Result 是一个长度为 2 的元组,而它应该是一个简单的类型,您可以将第 38 行更改为:

result[0].write(frame.astype(np.uint8))

python round(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) 似乎没有做任何事情,因此您可以通过将第 12-14 行替换为:

result = cv.VideoWriter('sample.avi',cv.VideoWriter_fourcc(*'MJPG'),22,size)
,

在这一行中,您正在创建一个元组

result = cv.VideoWriter('sample.avi',size),round(cap.get(cv.CAP_PROP_FRAME_HEIGHT))

简单地做

result = cv.VideoWriter('sample.avi',size)
variableX = round(cap.get(cv.CAP_PROP_FRAME_HEIGHT))