【问题标题】:Decoding a YUV image in Python OpenCV在 Python OpenCV 中解码 YUV 图像
【发布时间】:2014-05-20 06:53:36
【问题描述】:

我有一个表示为字节数组(无标题)的 YUV420_SP_NV21 图像,取自 Android 预览帧,我需要将其解码为 RGB 图像。 我之前在 Android 应用程序中使用 Java 和 OpenCV4Android 完成了此操作:

convert_mYuv = new Mat(height + height / 2, width, CvType.CV_8UC1);
convert_mYuv.put( 0, 0, data );
Imgproc.cvtColor( convert_mYuv, convert_mRgba, type, channels );

我已经尝试在 Python 中做同样的事情:

nmp = np.array(byteArray, dtype=np.ubyte) RGBMatrix = cv2.cvtColor(nmp, cv2.COLOR_YUV420P2RGB)

,但 RGBMatrix 仍然是 None

我知道自己可以这样做,我对公式很熟悉,但我很乐意以 OpenCV 的方式来做。 如何做到这一点?

我也试过cv2.imdecode(),但也失败了,可能是因为我没有使用它。

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    我解决这个问题已经有一段时间了,但我没有时间更新这个问题。

    我最终使用 numpy 将 YUV420_SP_NV21 字节数组提取为全尺寸 YUV 图像(在我的情况下为 1280x720),然后使用 OpenCV 将其转换为 RGB。

        import cv2 as cv2        # OpenCV import
        def YUVtoRGB(byteArray):
    
            e = 1280*720
            Y = byteArray[0:e]
            Y = np.reshape(Y, (720,1280))
    
            s = e
            V = byteArray[s::2]
            V = np.repeat(V, 2, 0)
            V = np.reshape(V, (360,1280))
            V = np.repeat(V, 2, 0)
    
            U = byteArray[s+1::2]
            U = np.repeat(U, 2, 0)
            U = np.reshape(U, (360,1280))
            U = np.repeat(U, 2, 0)
    
            RGBMatrix = (np.dstack([Y,U,V])).astype(np.uint8)
            RGBMatrix = cv2.cvtColor(RGBMatrix, cv2.COLOR_YUV2RGB, 3)
    

    我的原始数据是 YUV420_SP_NV21,解码如下:YY...YVUVUVU...VU, 但其他 YUV 格式需要对代码进行细微的更改。

    【讨论】:

    • 要实际读取文件,必须执行以下操作:with open(yuv_path, 'rb') as w: mat = YUVtoRGB(np.frombuffer(w.read(), dtype=np.uint8))
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多