png转.bgr二进制图片

在板端推理时,经常会将png图片转成.bgr为后缀的二进制图片,偶尔也需要将.bgr转为png图片查看,这两者之间的互相转换,代码实现如下:

import cv2
import numpy as np

def png2bgr():
    img_path = r'C:\Code\test_qua_detect_img/res.png'.replace('\\', '/')  # 原图地址
    save_path = 'C:/imgs'+'/'+'res.bgr'  # 转成二进制的存储地址
    img = cv2.imread(img_path)  # cv2 读取的图片本来就是bgr格式的,因此通过opencv转换非常方便
    img = cv2.resize(img, (320, 320))
    shape = img.shape
    print(shape)  # shape 是 [w, h, 3]
    #  使用一个元组收取BGR3通道的
    (B, G, R) = cv2.split(img)
    with open(save_path, 'wb') as fp:
        for i in range(320):
            for j in range(320):
                fp.write(B[i, j])
                # print(B[i, j])
        for i in range(320):
            for j in range(320):
                fp.write(G[i, j])
                # print(G[i, j])
        for i in range(320):
            for j in range(320):
                fp.write(R[i, j])
                # print(G[i, j])
    print("write success!")

def bgr2png():
    bgr_path = r'C:\imgs/res.bgr'.replace('\\', '/')
    save_dir = r'C:/imgs/'
    f = open(bgr_path, "rb")
    d = f.read()
    tmp_a = []
    for i in d:
        tmp_a.append(i)
    tmp_a = np.array(tmp_a, dtype=np.uint8)
    print(tmp_a.shape)
    B = tmp_a[:102400].reshape(320, 320,1)
    G = tmp_a[102400:204800].reshape(320, 320,1)
    R = tmp_a[204800:].reshape(320, 320,1)
    image = np.concatenate((B,G,R),axis=2)
    print(image.shape)
    # data = np.fromfile(bgr_path, np.uint8).reshape(320, 320, 3)
    cv2.imshow("res.png", image)
    cv2.imwrite(save_dir+'/'+'res.png', image)
    cv2.waitKey(0)

    print("read success!")


if __name__ == '__main__':
    # png转二进制bgr图片
    png2bgr()

    # 二进制图片转png
    bgr2png()

猜你喜欢

转载自blog.csdn.net/qq_35037684/article/details/121339029