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()

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一位不愿暴露自己的小可爱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值