AttributeError: 'tuple' object has no attribute 'write' , instance segmentation python

AttributeError: 'tuple' object has no attribute 'write' , instance segmentation python

我使用了这个博客的代码“https://learnopencv.com/deep-learning-based-object-detection-and-instance-segmentation-using-mask-r-cnn-in-opencv-python-c/” 在 python 的 OpenCV 中,标题为基于 Object 检测和实例分割使用 Mask R-CNN。我正在使用直播,想对其进行 object 检测和实例分割,并修改了下面的代码,其余部分与博客中解释的相同

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 information.
        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, 0, 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, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
     37 
---> 38         result.write(frame)
     39 
     40         cv.imshow("winName", frame)

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

如何更正此错误。

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

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

而是简单地做

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

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)