python - 将 YUV 导入为字节数组

标签 python numpy yuv

我正在开展一个项目,我必须对 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 的比例进行二次采样:

enter image description here

所以,思路是读入整组 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.

关于python - 将 YUV 导入为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53467655/

相关文章:

java - Linux 错误代码 24 是什么意思?

python - Pandas - 如何对数据框的子列进行分组?

python - 从 statsmodels 调用 volution_filter 时出现类型错误

android - camera2 拍摄的图片 - 从 YUV_420_888 到 NV21 的转换

opencv - 在 OPENCV 中加载 RAW YUV 视频

python - 允许用户在 python 的 format() 中输入是否存在安全风险?

python - 将 ctypes int** 转换为 numpy 二维数组

python - 使用 np.zero 创建元组

python - numPy 在从文件中读取负数时给出 nan

c# - YUV色间距