将yuv420p原始数据转换为图像opencv

2024-09-29 00:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有来自rtmp服务器的原始数据,像素格式为yuv420p

我使用管道读取数据。但我不知道如何将原始数据解码成图像

command = ['ffmpeg']
command.extend(["-loglevel", "fatal", "-i", 'rtmp://localhost/live/stream', "-f", "flv", "-pix_fmt" , 'yuv420p', '-vcodec', 'h264', "-"])
self.process = subprocess.Popen(command, stderr=subprocess.PIPE ,stdout = subprocess.PIPE)
self.output = self.process.stdout
self.fs = width*height*3 // 2
while True:
    data = self.output.read(self.fs)

我试过这样解码enter link description here

但结果是enter image description here

有人能帮我解决这个问题吗


Tags: selfoutput原始数据herestdoutdescription解码process
1条回答
网友
1楼 · 发布于 2024-09-29 00:22:32

我不是{}方面的专家,所以我会听从任何更了解我的人,如果我的答案被证明不正确,我会删除它

就我所见,您有一个RTMP流,您希望将其吸收到OpenCV中。OpenCV使用带有BGR排序的Numpy阵列来存储图像和视频帧,很明显,它们只是一个接一个地存储大量图像。因此,我建议您要求ffmpeg将Flash视频流转换为OpenCV想要的内容:

ffmpeg <RTMP INPUT STUFF> -pix_fmt bgr24 -f rawvideo -

然后更改它,因为它现在是BGR888:

self.fs = width * height * 3

由于我没有可用的RTMP源,因此生成了如下测试流:

# Generate raw video stream to read into OpenCV    
ffmpeg -f lavfi -i testsrc=duration=10:size=640x480:rate=30 -pixel_format rgb24 -f rawvideo -

然后我用以下方法将其导入Python:

ffmpeg -f lavfi -i testsrc=duration=10:size=640x480:rate=30 -pixel_format rgb24 -f rawvideo - | ./PlayRawVideo

Python程序PlayRawVideo如下所示:

#!/usr/bin/env python3

import numpy as np
import cv2
import sys

# Set width and height
w, h = 640, 480

while True:
    data = sys.stdin.buffer.read(w * h *3)
    if len(data) == 0:
        break
    frame = np.frombuffer(data, dtype=np.uint8).reshape((h, w, 3))
    cv2.imshow("Stream", frame)
    cv2.waitKey(1)
    

注意,我必须使用sys.stdin.buffer.read()来获取原始二进制数据

enter image description here

相关问题 更多 >