Skip to main content
 首页 » 编程设计

python之将 YUV 导入为字节数组

2025年05月04日14qq78292959

我正在开展一个项目,我必须对 YUV420_SP_NV21 图像(从 Android 相机拍摄)应用阈值以确定哪些像素是“黑色”,哪些像素是“白色”。

因此,我想将它作为字节数组导入 Python(使用 OpenCV、NumPy、PIL 等),这样我就可以对 Y 值进行一些快速的按位运算。



但是,当我尝试使用以下方法导入图像时,我得到无用的输出:

当我打字时

import cv2 
import numpy as np 
 
img = cv2.imread('test.yuv') 
imgArr = np.array(img) 
 
print(img) 
print(imgArr) 

我得到的输出是:

None 
None 



当我输入时

import numpy as np 
 
f = open('test.yuv', 'rb') 
img = f.read() 
imgArr = np.array(img) 

我得到了一些无用的字符序列。
当我现在输入时(例如)

print(imgArr[0]) 

我得到的输出是:

IndexError: too many indices for array 

这意味着 imgArr 根本不是数组!



谁能告诉我我做错了什么? 提前致谢!

请您参考如下方法:

您真的应该提供一个示例图像,以便人们可以更好地帮助您 - 否则他们会花费很长时间来开发代码,因为他们猜测的是您所指的图像格式,如果他们猜错了,那就是在浪费精力。

假设您的数据看起来像这样来自 Wikipedia ,您可以看到所有 Y 样本排在第一位,然后是所有 U 样本和所有 V 样本。然而,U/V 样本的数量仅为 Y 样本的 1/4,因为这两个分量在水平和垂直方向上以 2:1 的比例进行二次采样:

所以,思路是读入整组 YUV 样本,然后将第一个 w*h 个字节作为 Y 值,接下来的 w*h/4 采样为 U,下一个 w*h/4 采样为 V:

import numpy as np 
 
# Guess a width and height and derive number of pixels in image 
w,h = 2048,1536 
px = w*h 
 
# Read entire file into YUV 
YUV = np.fromfile('NV21_2048x1536.yuv',dtype='uint8') 
 
# Take first h x w samples and reshape as Y channel 
Y = YUV[0:w*h].reshape(h,w) 
 
# Take next px/4 samples as U 
U = YUV[px:(px*5)//4].reshape(h//2,w//2) 
 
# Take next px/4 samples as V 
V = YUV[(px*5)//4:(px*6)//4].reshape(h//2,w//2) 
 
# Undo subsampling of U and V by doubling height and width 
Ufull = U.copy().resize((w,h)) 
Vfull = V.copy().resize((w,h)) 

我不知道你接下来打算做什么,所以我暂时就这样吧!


关键词:NV21, YUV, YUV420, Android, YUV430P, Pillow, PIL, Python, image, image processing.