使用opencv捕获视频,保存到ffmpeg管道和直播

时间:2018-01-20 16:48:08

标签: python-3.x opencv video ffmpeg live-streaming

目标是通过RTSP将分析的实时视频流式传输到某个媒体服务器。要进行编辑/分析,我使用opencv,将编辑过的帧保存为FF在FFMPEG图像管道中,并使用相同的FFMPEG创建RTSP流。对不起,如果术语不准确,我发现它仍然很混乱。

经过一番努力后,我有以下代码:

import cv2
from subprocess import Popen, PIPE
from PIL import Image

# open pipe
p = Popen('ffmpeg -y -f image2pipe -vcodec mjpeg -r 24 -i - -vcodec h264 -f rtsp -rtsp_transport tcp rtsp://localhost:8081/test.sdp', stdin=PIPE)

video = cv2.VideoCapture(0)
i = 0
while video.isOpened():
    i=i+1
    ret, frame = video.read()
    if ret:
        #[...do some analysis stuff]
        im = Image.fromarray(frame)
        im.save(p.stdin, 'JPEG')

        """
        alternatively
        img_str = cv2.imencode('.jpg', frame)[1].tostring()
        p.stdin.write(img_str)
        """

    else:
        break

    print (i)
    if(i==1000):
        break


p.stdin.close()
p.wait()
video.release()
cv2.destroyAllWindows()
print("done streaming video")

运行124帧(i = 124)然后循环挂起,我从ffmpeg收到一些消息,我不知道它是什么,但它看起来不像是错误:

push frame
122
push frame
123
push frame
124
Input #0, image2pipe, from 'pipe:':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: mjpeg, yuvj420p(pc, bt470bg/unknown/unknown), 640x480 [SAR 1:1 DAR 4:3], 24 fps, 24 tbr, 24 tbn, 24 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg (native) -> h264 (libx264))
[libx264 @ 000002076650d980] using SAR=1/1
[libx264 @ 000002076650d980] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 000002076650d980] profile High, level 3.0
[libx264 @ 000002076650d980] 264 - core 155 r2893 b00bcaf - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=24 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
push frame

网络摄像头似乎继续运行,但没有更多的框架被推入管道。看起来有些缓冲区已经填满了。如果我直接写入视频文件而不是rtsp,它可以工作。如果我同时使用ffplay打开rtsp流,它也可以工作(虽然滞后5秒)。 任何人都知道这是来自哪里以及如何解决它?

0 个答案:

没有答案
相关问题