【问题标题】:Storing RTSP stream as video file with OpenCV VideoWriter使用 OpenCV VideoWriter 将 RTSP 流存储为视频文件
【发布时间】:2019-08-04 02:18:34
【问题描述】:

我正在使用 OpenCV 开发一个 Python 模块,该模块连接到 RTSP 流以对视频执行一些预处理(主要是降低 fps 和分辨率),然后将其存储在文件系统中。

但是,即使在尝试了几个编解码器之后,寻找类似的发展......我总是以一个空的视频结束。我见过这个其他线程 (cv::VideoWriter yields unreadable video),它可能类似,但是是在 C++ 上开发的。

有人做过这方面的工作吗?我通常使用示例 RTSP 流作为参考,例如 rtsp://freja.hiof.no:1935/rtplive/definst/hessdalen03.stream,并且可以正确接收甚至观看来自 VLC 的流.

我看到很多讨论如何从 RTSP 流中捕获视频,或如何使用 VideoWriters 和 VideoReaders 类和视频文件的线程,但几乎没有将两者结合起来。

任何帮助将不胜感激 :) 谢谢!!


编辑 1:用于存储帧的示例代码。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import numpy

# Test frame.
width, height = 400, 300
width_2, height_2 = int(width / 2), int(height / 2)
frame = numpy.zeros((height, width, 3), numpy.uint8)
cv2.rectangle(frame, (0, 0), (width_2, height_2), (255, 0, 0), cv2.FILLED)
cv2.rectangle(frame, (width_2, height_2), (width, height), (0, 255, 0), cv2.FILLED)

frames = [frame for _ in range(100)]
fps = 25

# Define the codec.
#fourcc = cv2.VideoWriter_fourcc(*'X264')
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
fourcc = cv2.VideoWriter_fourcc(*'MJPG')

# Create VideoWriter object
out = cv2.VideoWriter(filename='video.avi',
                      fourcc=fourcc,
                      apiPreference=cv2.CAP_FFMPEG,
                      fps=float(fps),
                      frameSize=(width, height),
                      isColor=True)

result = 0
for frame in frames:
    result += 0 if out.write(frame) is None else 1
print(result)

out.release()

编辑 2:解决方案

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import numpy

# Test frame.
width, height = 400, 300
width_2, height_2 = int(width / 2), int(height / 2)

frame1 = numpy.zeros((height, width, 3), numpy.uint8)
cv2.rectangle(frame1, (0, 0), (width_2, height_2), (255, 0, 0), cv2.FILLED)
cv2.rectangle(frame1, (width_2, height_2), (width, height), (0, 255, 0), cv2.FILLED)
cv2.imwrite('frame1.jpg', frame1)

frame2 = numpy.zeros((height, width, 3), numpy.uint8)
cv2.rectangle(frame2, (width_2, 0), (width, height_2), (255, 0, 0), cv2.FILLED)
cv2.rectangle(frame2, (0, height_2), (width_2, height), (0, 255, 0), cv2.FILLED)
cv2.imwrite('frame2.jpg', frame2)

range1 = [frame1 for _ in range(10)]
range2 = [frame2 for _ in range(10)]
frames = range1 + range2 + range1 + range2 + range1
fps = 2

# Define the codec.
fourcc = cv2.VideoWriter_fourcc(*'MJPG')

# Create VideoWriter object
out = cv2.VideoWriter('video.avi', fourcc, float(fps), (width, height))

for frame in frames:
    out.write(frame)

out.release()

【问题讨论】:

  • 你能看到直播吗?我的意思是使用 imshow 而不是将其保存到磁盘?您是否可以使用虚拟图像创建视频,例如全红色的图像?您应该逐步进行,首先确保可以连接和检索图像,然后专注于保存....您提供的链接看起来rtmp 链接多于 rtsp,通常端口 554 用于 rtsp,1935 用于 rtmp...
  • 嗨@api55!是的,我可以看到从 RTSP 流中检索到的帧。事实上,现在我将它们存储为 jpeg 图像。但是将它们存储为视频应该更有效。但是,正如您所说,这很可能是为了解决问题。我用 numpy 准备了一个虚拟帧,视频仍然出错。请参阅随附的代码,导致 VLC 无法显示 240.924 字节的视频。
  • 太好了,现在您的问题有一个 MCVE。我知道获得fourcc +扩展在大多数情况下是一种可怕的体验......首先尝试查看您的机器中安装了哪些编解码器,而不是FOURCC pass -1,并且应该出现一个菜单,您可以选择一个编解码器
  • 它返回(在 Ubuntu 上)消息“OpenCV: FFMPEG: format avi / AVI (Audio Video Interleaved)”,以及一个包含 489 个标签的列表,例如“fourcc tag 0x34363248/'H264' codec_id 001B '。例如,它在尝试将其用作fourcc标签时回复“找不到编解码器ID 27的编码器:找不到编码器”,即使它在列表中。

标签: python opencv image-processing video rtsp


【解决方案1】:

这是一个 RTSP 流到视频小部件。我建议创建另一个线程来获取帧,因为cv2.VideoCapture.read() 正在阻塞。这可能会很昂贵并且会导致延迟,因为主线程必须等到它获得一个帧。通过将此操作放在一个单独的线程中,该线程只专注于抓取帧并在主线程中处理/保存帧,它可以显着提高性能。您也可以尝试使用其他编解码器,但使用 MJPG 应该是安全的,因为它内置在 OpenCV 中。我使用了我的 IP 摄像机流并将帧保存到 output.avi。请务必将 rtsp_stream_link 更改为您自己的 RTSP 流链接。 :)

from threading import Thread
import cv2

class RTSPVideoWriterObject(object):
    def __init__(self, src=0):
        # Create a VideoCapture object
        self.capture = cv2.VideoCapture(src)

        # Default resolutions of the frame are obtained (system dependent)
        self.frame_width = int(self.capture.get(3))
        self.frame_height = int(self.capture.get(4))

        # Set up codec and output video settings
        self.codec = cv2.VideoWriter_fourcc('M','J','P','G')
        self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height))

        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()

    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):
        # Display frames in main program
        if self.status:
            cv2.imshow('frame', self.frame)

        # Press Q on keyboard to stop recording
        key = cv2.waitKey(1)
        if key == ord('q'):
            self.capture.release()
            self.output_video.release()
            cv2.destroyAllWindows()
            exit(1)

    def save_frame(self):
        # Save obtained frame into video output file
        self.output_video.write(self.frame)

if __name__ == '__main__':
    rtsp_stream_link = 'your stream link!'
    video_stream_widget = RTSPVideoWriterObject(rtsp_stream_link)
    while True:
        try:
            video_stream_widget.show_frame()
            video_stream_widget.save_frame()
        except AttributeError:
            pass

【讨论】:

  • 谢谢@nathancy !!!我的 VLC 也显示了一些错误,即使视频已经正确存储,所以有点搞砸了。但是由于您的代码,我可以解决所有问题。我将在顶部添加固定代码。
  • 很高兴为您提供帮助!如果您收到不稳定的帧,请使用cv2.VideoWriter() FPS 参数或访问您的 IP 摄像头来调整摄像头的 FPS 设置。
  • 感谢您的帮助,有没有办法以其他格式录制音频,如 mp4 等。
  • 这超出了这个问题的范围,你应该为此另开一个问题
猜你喜欢
  • 2018-12-05
  • 2019-07-11
  • 2014-01-29
  • 1970-01-01
  • 2015-06-01
  • 2020-06-04
  • 1970-01-01
  • 2021-01-02
  • 1970-01-01
相关资源
最近更新 更多