python对yuv图像裁剪
Posted 神遁克里苏
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python对yuv图像裁剪相关的知识,希望对你有一定的参考价值。
首先读取yuv图像,从图像的命名中读出图像的长和宽,可能要跟你的yuv文件命名方式来做修改。
这是我的yuv图像的命名方式。
达到长和宽之后就可以读取图像的像素值了,我这里设置的是裁剪成40的倍数,这两句是得到裁剪后的长和宽。
Height_Y = Height_Y // cropc * cropc
Width_Y = Width_Y // cropc * cropc
裁剪
current_Y = Y[0:Height_Y, 0: Width_Y ]
current_U = U[0:Height_Y // 2, 0:Width_Y // 2 ]
current_V = V[0:Height_Y // 2, 0:Width_Y // 2 ]
将 current_Y转换为list,方便存储
list_y = list(current_Y.reshape((Height_Y * Width_Y)))
list_u = list(current_U.reshape(((Height_Y // 2 )* (Width_Y // 2))))
list_v = list(current_V.reshape(((Height_Y // 2 ) * (Width_Y // 2))))
存储
outpath='D:/NN/265_cut/37_wo/'+str(num).rjust(4,'0')+'_'+str(Width_Y)+'x'+str(Height_Y)+'.yuv'
with open(outpath, 'wb+') as ff:
ff.write(np.array(list_y, dtype=np.uint8).tobytes())
ff.write(np.array(list_u, dtype=np.uint8).tobytes())
ff.write(np.array(list_v, dtype=np.uint8).tobytes())
完整代码如下:
import numpy as np
cropc=40
rootpath='C:/valid/valid_yuv'
for i in os.listdir(rootpath):
subfile = rootpath + '/' + i
size = i.split('.')[0]
num =size.split('_')[0]
size=size.split('_')[1]
width = size.split('x')[0]
Width_Y = int(width)
height = size.split('x')[1]
Height_Y = int(height)
fp1 = open(subfile, 'rb')
Y = np.frombuffer(fp1.read(Height_Y * Width_Y * 2 // 2), np.uint8).reshape((Height_Y , Width_Y))
U = np.frombuffer(fp1.read(Height_Y * Width_Y // 2 // 2), np.uint8).reshape((Height_Y // 2 , Width_Y // 2))
V = np.frombuffer(fp1.read(Height_Y * Width_Y // 2 // 2), np.uint8).reshape((Height_Y // 2 ,Width_Y // 2))
Height_Y = Height_Y // cropc * cropc
Width_Y = Width_Y // cropc * cropc
current_Y = Y[0:Height_Y, 0: Width_Y ]
current_U = U[0:Height_Y // 2, 0:Width_Y // 2 ]
current_V = V[0:Height_Y // 2, 0:Width_Y // 2 ]
list_y = list(current_Y.reshape((Height_Y * Width_Y)))
list_u = list(current_U.reshape(((Height_Y // 2 )* (Width_Y // 2))))
list_v = list(current_V.reshape(((Height_Y // 2 ) * (Width_Y // 2))))
outpath='D:/NN/265_cut/37_wo/'+str(num).rjust(4,'0')+'_'+str(Width_Y)+'x'+str(Height_Y)+'.yuv'
with open(outpath, 'wb+') as ff:
ff.write(np.array(list_y, dtype=np.uint8).tobytes())
ff.write(np.array(list_u, dtype=np.uint8).tobytes())
ff.write(np.array(list_v, dtype=np.uint8).tobytes())
以上是关于python对yuv图像裁剪的主要内容,如果未能解决你的问题,请参考以下文章