- import cv2 as cv
- import yuvio
- import os
- import cv2 as cv
- import numpy as np
-
- #参考:https://pypi.org/project/yuvio/
-
-
- yuv_frame = yuvio.imread("my.yuv", 720, 640, 'yuyv422')
-
- y = yuv_frame.y
- u = yuv_frame.u
- v = yuv_frame.v
-
- cv.imshow('y',y)
-
- reshaped_y = y.reshape(720,640)
- reshaped_u = u.reshape(720,320)
- reshaped_v = v.reshape(720,320)
-
- img = "my.jpg"
- outImg = "out.jpg"
-
- cv.imwrite(img, y)
- im = cv.imread(img)
- ##截取图像高从25到479,宽从0到720
- im = im[25:479,0:720]
- cv.imwrite(outImg, im)
- cv.waitkey(0)
参考:
https://github.com/labradon/yuvio/blob/main/README.md
另外下面代码yuv420p的转换,来自于网上。
- import os
- import cv2 as cv
- import numpy as np
-
-
- # 读取yuv420p的一帧文件,并转化为png图片
- if __name__ == '__main__':
- filepath = 'test.yuv'
- binfile = open(filepath, 'rb')
- size = os.path.getsize(filepath)
- image_width = 720
- image_hight = 640
- image_y = [[0] * image_width for i in range(image_hight)]
- image_u = [[0] * image_width for i in range(image_hight)]
- image_v = [[0] * image_width for i in range(image_hight)]
- for r in range(image_hight):
- for c in range(image_width):
- image_y[r][c] = binfile.read(1)[0]
- Image_Y = np.array(image_y)
-
- for r in range(int(image_hight / 2)):
- for c in range(int(image_width / 2)):
- pixel = binfile.read(1)[0]
- image_u[2 * r + 0][2 * c + 0] = pixel
- image_u[2 * r + 1][2 * c + 0] = pixel
- image_u[2 * r + 0][2 * c + 1] = pixel
- image_u[2 * r + 1][2 * c + 1] = pixel
- Image_U = np.array(image_u)
-
- for r in range(int(image_hight / 2)):
- for c in range(int(image_width / 2)):
- pixel = binfile.read(1)[0]
- image_v[2 * r + 0][2 * c + 0] = pixel
- image_v[2 * r + 0][2 * c + 1] = pixel
- image_v[2 * r + 1][2 * c + 0] = pixel
- image_v[2 * r + 1][2 * c + 1] = pixel
- Image_V = np.array(image_v)
- binfile.close()
- compose = np.array([Image_Y, Image_V, Image_U]).transpose([1, 2, 0]).astype(np.uint8)
- #compose = np.array([Image_Y, Image_U, Image_V]).transpose([1, 2, 0]).astype(np.uint8)
- Image = cv.cvtColor(compose, cv.COLOR_YUV2RGB)
- #Image = cv.cvtColor(compose, cv.COLOR_YUV2BGR)
- cv.imwrite("one_frame_of_highway.yuv.png", Image)