Python OpenCV 转换平面 YUV 4 :2:0 image to RGB -- YUV array format

标签 python numpy opencv image-processing

我正在尝试通过 python 使用 OpenCV 4.1.0 版将平面 YUV 4:2:0 图像转换为 RGB,并且正在努力了解如何格式化数组以传递给 cvtColor 功能。我将所有 3 个 channel 作为单独的数组,并尝试将它们合并以与 cv2.cvtColor 一起使用。我正在使用cv2.cvtColor(yuv_array, cv2.COLOR_YUV420p2RGB)。我知道 yuv_array 应该是原始图像高的 1.5 倍(这就是使用 cv2.COLOR_RGB2YUV_YV12 来自 cvtColor 的 yuv 数组的样子),我应该将 UV 分量放入 yuv_array 的下半部分,将 Y channel 放入数组的顶部。

我似乎无法弄清楚 U 和 V channel 应如何在该数组的底部格式化。我尝试过将它们交错放置,然后将它们背靠背放在那里。对于这两种方法,我都尝试过先将 U 再放在 V 上,或者反过来。所有方法都会导致生成的图像出现伪影。这是我的代码和示例图像:

import os
import errno
import numpy as np
import cv2

fifo_names = ["/tmp/fifos/y_fifo", "/tmp/fifos/u_fifo", "/tmp/fifos/v_fifo"]

#teardown; delete fifos
import signal, sys
def cleanup_exit(signal, frame):
    print ("cleaning up!")
    for fifo in fifo_names:
        os.remove(fifo)
    sys.exit(0)
signal.signal(signal.SIGINT, cleanup_exit)
signal.signal(signal.SIGTERM, cleanup_exit)

#make fifos
for fifo in fifo_names:
    try:
        os.mkfifo(fifo);
    except OSError as oe:
        if oe.errno == errno.EEXIST:
            os.remove(fifo)
            os.mkfifo(fifo)
        else:
            raise()

#make individual np arrays to store Y,U, and V channels
#we know the image size beforehand -- 640x360 pixels
yuv_data = []
frame_size = []
fullsize = (360, 640)
halfsize = (180, 320)
for i in range(len(fifo_names)):
    if (i == 0):
        size = fullsize
    else:
        size = halfsize
    yuv_data.append(np.empty(size, dtype=np.uint8));
    frame_size.append(size)

#make array that holds all yuv data for display with cv2
all_yuv_data = np.empty((fullsize[0] + halfsize[0], fullsize[1]), dtype=np.uint8) 

#continuously read yuv images from fifos
print("waiting for fifo to be written to...")
while True:
    for i in range(len(fifo_names)):
        fifo = fifo_names[i]
        with open(fifo, 'rb') as f:
            print("FIFO %s opened" % (fifo))
            all_data = b''
            while True:
                data = f.read()
                print("read from %s, len: %d" % (fifo,len(data)))
                if len(data) == 0: #then the fifo has been closed
                    break
                else:
                    all_data += data
            yuv_data[i] = np.frombuffer(all_data, dtype=np.uint8).reshape(frame_size[i])

    #stick all yuv data in one buffer, interleaving columns
    all_yuv_data[0:fullsize[0],0:fullsize[1]] = yuv_data[0]
    all_yuv_data[fullsize[0]:,0:fullsize[1]:2] = yuv_data[1]
    all_yuv_data[fullsize[0]:,1:fullsize[1]:2] = yuv_data[2]

    #show each yuv channel individually
    cv2.imshow('y', yuv_data[0])
    cv2.imshow('u', yuv_data[1])
    cv2.imshow('v', yuv_data[2])

    #convert yuv to rgb and display it
    rgb = cv2.cvtColor(all_yuv_data, cv2.COLOR_YUV420p2RGB);
    cv2.imshow('rgb', rgb)
    cv2.waitKey(1)

上面的代码尝试按列交错 U 和 V 信息。

我还尝试使用以下方法将 U 和 V channel 信息放入 all_yuv_data 数组中:

    #try back-to-back
    all_yuv_data[0:fullsize[0],0:fullsize[1]] = yuv_data[0]
    all_yuv_data[fullsize[0]:,0:halfsize[1]] = yuv_data[1]
    all_yuv_data[fullsize[0]:,halfsize[1]:] = yuv_data[2]

该图像是使用 libav 从另一个程序获取的视频帧。该帧的格式为AV_PIX_FMT_YUV420Pdescribed as “平面 YUV 4:2:0,12bpp,(每 2x2 Y 样本 1 个 Cr 和 Cb 样本)”。

以下是以灰度显示的示例图像的 yuv channel :

Y channel :

y channel

U channel :

u channel

V channel :

v channel

以及相应的 RGB 转换(这是使用上面的交错方法,使用“背对背”方法时会看到类似的伪影):

带有伪影的 RGB 图像:

rgb image with artifacts

我应该如何将 u 和 v channel 信息放入 all_yuv_data 中?

此后由 Mark Setchell 编辑

我相信预期的结果是:

enter image description here

最佳答案

如果 YUV 标准与 OpenCV COLOR_YUV2BGR_I420 转换公式匹配,您可以将帧作为一个 block 读取,并将其 reshape 为高度*1.5 行应用转换。

以下代码示例:

  • 构建 YUV420 格式的输入,并将其写入内存流(而不是 fifo)。
  • 从流中读取帧并使用 COLOR_YUV2BGR_I420 将其转换为 BGR。
    颜色不正确...
  • 通过读取 Y、U 和 V、调整 U 和 V 的大小并使用 COLOR_YCrCb2BGR 转换来重复该过程。
    注意:OpenCV 以 BGR 颜色格式(而非 RGB)工作。

代码如下:

import cv2
import numpy as np
import io

# Building the input:
###############################################################################
img = cv2.imread('GrandKingdom.jpg')

#yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
#y, u, v = cv2.split(yuv)

# Convert BGR to YCrCb (YCrCb apply YCrCb JPEG (or YCC), "full range", 
# where Y range is [0, 255], and U, V range is [0, 255] (this is the default JPEG format color space format).
yvu = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
y, v, u = cv2.split(yvu)

# Downsample U and V (apply 420 format).
u = cv2.resize(u, (u.shape[1]//2, u.shape[0]//2))
v = cv2.resize(v, (v.shape[1]//2, v.shape[0]//2))

# Open In-memory bytes streams (instead of using fifo)
f = io.BytesIO()

# Write Y, U and V to the "streams".
f.write(y.tobytes())
f.write(u.tobytes())
f.write(v.tobytes())

f.seek(0)
###############################################################################

# Read YUV420 (I420 planar format) and convert to BGR
###############################################################################
data = f.read(y.size*3//2)  # Read one frame (number of bytes is width*height*1.5).

# Reshape data to numpy array with height*1.5 rows
yuv_data = np.frombuffer(data, np.uint8).reshape(y.shape[0]*3//2, y.shape[1])

# Convert YUV to BGR
bgr = cv2.cvtColor(yuv_data, cv2.COLOR_YUV2BGR_I420);


# How to How should I be placing the u and v channel information in all_yuv_data?
# -------------------------------------------------------------------------------
# Example: place the channels one after the other (for a single frame)
f.seek(0)
y0 = f.read(y.size)
u0 = f.read(y.size//4)
v0 = f.read(y.size//4)
yuv_data = y0 + u0 + v0
yuv_data = np.frombuffer(yuv_data, np.uint8).reshape(y.shape[0]*3//2, y.shape[1])
bgr = cv2.cvtColor(yuv_data, cv2.COLOR_YUV2BGR_I420);
###############################################################################

# Display result:
cv2.imshow("bgr incorrect colors", bgr)


###############################################################################
f.seek(0)
y = np.frombuffer(f.read(y.size), dtype=np.uint8).reshape((y.shape[0], y.shape[1]))  # Read Y color channel and reshape to height x width numpy array
u = np.frombuffer(f.read(y.size//4), dtype=np.uint8).reshape((y.shape[0]//2, y.shape[1]//2))  # Read U color channel and reshape to height x width numpy array
v = np.frombuffer(f.read(y.size//4), dtype=np.uint8).reshape((y.shape[0]//2, y.shape[1]//2))  # Read V color channel and reshape to height x width numpy array

# Resize u and v color channels to be the same size as y
u = cv2.resize(u, (y.shape[1], y.shape[0]))
v = cv2.resize(v, (y.shape[1], y.shape[0]))
yvu = cv2.merge((y, v, u)) # Stack planes to 3D matrix (use Y,V,U ordering)

bgr = cv2.cvtColor(yvu, cv2.COLOR_YCrCb2BGR)
###############################################################################


# Display result:
cv2.imshow("bgr", bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()
<小时/>

结果:
enter image description here

关于Python OpenCV 转换平面 YUV 4 :2:0 image to RGB -- YUV array format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60729170/

相关文章:

javascript - Django Inlineformset - 基于第二个下拉菜单的 JQuery 下拉菜单

python - ddof = 1 的 numpy 标准偏差估计器偏差

python - 将图像从 8 位转换为 10 位的问题

Java JNI “symbol lookup error” 当依赖共享库包含符号

python - 有django的类库图吗?

python - 无法让 Jython 在 Mac 上工作

python - 在 sleep 时杀死 python 进程

python - 从 Scipy 矩阵创建列表

python - 两个整数的二进制表示的统一重组

python - 使用 python 编写 mpeg-1 视频