Rot*_*tem 8 python numpy image-processing video-processing nv12-nv21
NV12格式定义了具有 420 次采样的 YUV 颜色空间的特定颜色通道排序。
NV12格式主要用于视频编码/解码管道。
NV12 是一种双平面格式,具有全尺寸 Y 平面,后跟具有编织 U 和 V 值的单个色度平面。NV21 相同,但具有编织的 V 和 U 值。NV12中的12指的是每像素12位。NV12 具有半宽和半高色度通道,因此是 420 子采样。
在 NV12 上下文中,YUV 格式主要指YCbCr颜色空间。NV12 元素每个元素(类型)
有 8 位。
在帖子的上下文中,YUV 元素处于“有限范围”标准:Y 范围为 [16, 235],U,V 范围为 [16, 240]。 uint8
sRGB(标准红绿蓝)是 PC 系统使用的标准色彩空间。
在本文中,sRGB颜色分量范围为 [0, 255](uint8类型)。
RGB 元素排序与帖子无关(假设有 3 个颜色平面)。
目前至少有 2 种可能的 YCbCr 格式应用 NV12:
NV12 元件订购示例:
YYYYYY
YYYYYY
UVUVUV
RGB 到 NV12 的转换可以通过以下阶段来描述:
下图说明了应用 6x6 像素图像大小的转换阶段:
我们如何使用 NumPy 将 sRGB 转换为 NV12?
注意:
问题涉及演示转换过程的 Python 实现(帖子不适用于 OpenCV 实现等现有函数)。
这篇文章的目的是演示转换过程。
下面的Python实现使用NumPy,并刻意避免使用OpenCV。
RGB 到 NV12 转换阶段:
cv2.resize,而是使用每 2x2 像素的平均值(结果相当于双线性插值)。以下是将 RGB 转换为 NV12 标准的 Python 代码示例:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import subprocess as sp # The module is used for testing (using FFmpeg as reference).
do_use_bt709 = True # True for BT.709, False for BT.601
rgb = mpimg.imread('rgb_input.png')*255.0 # Read RGB input image, multiply by 255 (set RGB range to [0, 255]).
r, g, b = np.squeeze(np.split(rgb, 3, -1)) # Split RGB to R, G and B numpy arrays.
rows, cols = r.shape
# I. Convert RGB to YUV (convert sRGB to YUV444)
#################################################
if do_use_bt709:
# Convert sRGB to YUV, BT.709 standard
# Conversion formula used: 8 bit sRGB to "limited range" 8 bit YUV (BT.709).
y = 0.1826*r + 0.6142*g + 0.0620*b + 16
u = -0.1006*r - 0.3386*g + 0.4392*b + 128
v = 0.4392*r - 0.3989*g - 0.0403*b + 128
else:
# Convert sRGB to YUV, BT.601 standard.
# Conversion formula used: 8 bit sRGB to "limited range" 8 bit YUV (BT.601).
y = 0.2568*r + 0.5041*g + 0.0979*b + 16
u = -0.1482*r - 0.2910*g + 0.4392*b + 128
v = 0.4392*r - 0.3678*g - 0.0714*b + 128
# II. U,V Downscaling (convert YUV444 to YUV420)
##################################################
# Shrink U and V channels by a factor of x2 in each axis (use bi-linear interpolation).
#shrunk_u = cv2.resize(u, (cols//2, rows//2), interpolation=cv2.INTER_LINEAR)
#shrunk_v = cv2.resize(v, (cols//2, rows//2), interpolation=cv2.INTER_LINEAR)
# Each element of shrunkU is the mean of 2x2 elements of U
# Result is equivalent to resize by a factor of 0.5 with bi-linear interpolation.
shrunk_u = (u[0::2, 0::2] + u[1::2, 0::2] + u[0::2, 1::2] + u[1::2, 1::2]) * 0.25
shrunk_v = (v[0::2, 0::2] + v[1::2, 0::2] + v[0::2, 1::2] + v[1::2, 1::2]) * 0.25
# III. U,V Interleaving
########################
# Size of UV plane is half the number of rows, and same number of columns as Y plane.
uv = np.zeros((rows//2, cols)) # Use // for integer division.
# Interleave shrunkU and shrunkV and build UV plane (each row of UV plane is u,v,u,u,v...)
uv[:, 0::2] = shrunk_u
uv[:, 1::2] = shrunk_v
# Place Y plane at the top, and UV plane at the bottom (number of rows NV12 matrix is rows*1.5)
nv12 = np.vstack((y, uv))
# Round NV12, and cast to uint8.
nv12 = np.round(nv12).astype('uint8')
# Write NV12 array to binary file
nv12.tofile('nv12_output.raw')
# Display NV12 result (display as Grayscale image).
plt.figure()
plt.axis('off')
plt.imshow(nv12, cmap='gray', interpolation='nearest')
plt.show()
# Testing - compare the NV12 result to FFmpeg conversion result:
################################################################################
color_matrix = 'bt709' if do_use_bt709 else 'bt601'
sp.run(['ffmpeg', '-y', '-i', 'rgb_input.png', '-vf',
f'scale=flags=fast_bilinear:out_color_matrix={color_matrix}:out_range=tv:dst_format=nv12',
'-pix_fmt', 'nv12', '-f', 'rawvideo', 'nv12_ffmpeg.raw'])
nv12_ff = np.fromfile('nv12_ffmpeg.raw', np.uint8)
nv12_ff = nv12_ff.reshape(nv12.shape)
abs_diff = np.absolute(nv12.astype(np.int16) - nv12_ff.astype(np.int16)).astype(np.uint8)
max_abs_diff = abs_diff.max()
print(f'max_abs_diff = {max_abs_diff}')
plt.figure()
plt.axis('off')
plt.imshow(abs_diff, cmap='gray', interpolation='nearest')
plt.show()
################################################################################
Run Code Online (Sandbox Code Playgroud)
为了进行测试,我们使用FFmpeg (命令行工具)将相同的输入图像 ( rgb_input.png) 转换为 NV12 格式,并计算两次转换之间的最大绝对差。
测试假设 FFmpeg 位于执行路径中(在 Windows 中我们可以将 ffmpeg.exe 与 Python 脚本放在同一文件夹中)。
以下 shell 命令转换rgb_input.png为具有 BT.709 颜色标准的 NV12 格式:
ffmpeg -y -i rgb_input.png -vf "scale=flags=fast_bilinear:out_color_matrix=bt709:out_range=tv:dst_format=nv12" -pix_fmt nv12 -f rawvideo nv12_ffmpeg.raw
注意:
fast_bilinear插值可针对特定输入图像提供最佳结果 - 在缩小U和时应用双线性插值V。
以下 Python 代码nv12_ffmpeg.raw与进行比较nv12_ffmpeg.raw:
nv12_ff = np.fromfile('nv12_ffmpeg.raw', np.uint8).reshape(nv12.shape)
abs_diff = np.absolute(nv12.astype(np.int16) - nv12_ff.astype(np.int16)).astype(np.uint8)
print(f'max_abs_diff = {abs_diff.max()}')
Run Code Online (Sandbox Code Playgroud)
对于特定输入图像,最大差异为2或3(几乎相同)。
对于其他输入图像,差异更大(可能是由于错误的 FFmpeg 参数)。