python对yuv图像裁剪

17 篇文章 2 订阅
11 篇文章 1 订阅

首先读取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())


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值