我正在开发一个项目,必须对 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 根本不是数组!
谁能告诉我我做错了什么吗?
提前致谢!
您确实应该提供一个示例图像,以便人们可以更好地帮助您 - 否则他们会花费大量时间为他们猜测的图像格式开发代码,如果他们猜错了,那就是浪费精力。
假设您的数据如下所示维基百科 https://en.wikipedia.org/wiki/YUV,您可以看到所有 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))
我不知道你下一步打算做什么,所以我暂时就这样吧!
Keywords:NV21、YUV、YUV420、Android、YUV430P、Pillow、PIL、Python、图像、图像处理。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)