0
点赞
收藏
分享

微信扫一扫

vitepress一键push和发布到github部署网站脚本

夜空一星 2024-11-04 阅读 22

一 背景

	最近需要把图片nv12格式转换为rgb,因为NV12格式存储占空间比较小,采集时候存储NV12格式,现在需要把NV12格式转换为RGB格式。

二 代码

1 NV12 转 RGB

import os
import cv2
import numpy as np

def nv12_to_rgb(nv12_path, save_path, width, height):

    nv12_data = np.fromfile(nv12_path, dtype=np.uint8)
    nv12_data = nv12_data.reshape((height * 3 // 2 , width))
    rgb_data  = cv2.cvtColor(nv12_data, cv2.COLOR_YUV2BGR_NV12)
    
    cv2.imwrite(save_path, rgb_data)
    cv2.imshow('bgr', rgb_data)
    cv2.waitKey(-1)
    cv2.destroyAllWindows()
    

if __name__ == '__main__':
    nv12_path = '~/test.nv12'
    save_path = '~/2.bmp'
    width = 1280
    height = 720
    nv12_to_rgb(nv12_path, save_path, width, height)

在上述代码中,需要修改图片宽高,因为你存NV12格式时候,就知道图片的大小。注意修改。

2 RGB 转 NV12

import os
import cv2
import shutil

import numpy as np


def RGB_To_NV12(img_path, save_path):
    
    img = cv2.imread(img_path)
    b, g, r = cv2.split(img)
    Y = (0.299 * r + 0.587 * g + 0.114 * b).astype(np.uint8)
    U = (- 0.1687 * r - 0.3313 * g + 0.5 * b + 128).astype(np.uint8)
    V = (0.5 * r - 0.4187 * g - 0.0813 * b + 128).astype(np.uint8)
    U = U[::2,:]
    V = V[::2,:]
    U[:,1::2] = V[:,1::2]
    YUV = np.vstack((Y,U))
    
    YUV.tofile(save_path)


if __name__ == '__main__':
    img_path  = '~/test.bmp'
    save_path = '~/test.nv12'
    RGB_To_NV12(img_path, save_path)
举报

相关推荐

0 条评论