VideoWriter 没有正确保存视频

VideoWriter does not save the video correctly

我正在尝试使用 VideoWriter 将检索到的帧保存为视频文件,但它似乎不起作用。我检查了 while 循环并打印输出正在工作。不知道为什么视频输出只有O kb

 def detect_video(self, path, output_path):
    
    # Set output video writer with codec
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(output_path, fourcc, 25.0, (1920, 1080))
        # Read the video
        vidcap = cv2.VideoCapture(path)
        frame_read, image = vidcap.read()
        count = 0
        # Iterate over frames and pass each for prediction
        while frame_read:
            # Perform object detection and add to output file
            output_file = self.detect(image)
            #print(output_file)
            # Write frame with predictions to video
            out.write(output_file)
            # Read next frame
            frame_read, image = vidcap.read()
            count += 1
            #print(count)
        # Release video file when we're ready
        out.release()

看来你问的问题不对。它与 TensorFlow 或对象检测无关。不幸的是我是从评论中得到的,而不是从问题中得到的。

至于问题,一切都还好,就是分辨率不行。确保帧宽度为 1920,高度为 1080。否则,视频大小当然为 0 kb。如果您已将 1920x1080 作为输出分辨率传递给 cv2.VideoWriter,则您获得的帧大小也应该匹配。因此,您应该调整 检索到的帧:

 width = 1920
 height = 1080
 output_size = (width, height)
 out.write(cv2.resize(output_file, output_size ))

或使用这些获取框架的宽度和高度:

width = vidcap.get(cv2.CAP_PROP_FRAME_WIDTH )
height = vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT )
fps =  vidcap.get(cv2.CAP_PROP_FPS)
cv2.VideoWriter(output_path, fourcc, fps, (width, height))

P.S。写入视频时无法更改视频大小!