代码如下:
import os
import cv2
from numpy import *
import numpy as np
Img_dir = "~/cityscape_2048" # 原图地址
Save_dir = "~/cityscape_images_2048" # 转成二进制的地址
def png2bgr(img_dir, save_dir):
img = cv2.imread(img_dir) # cv2 读取的图片本来就是bgr格式的,因此通过opencv转换非常方便
shape = img.shape
print(shape) # shape 是 [w, h, 3]
# 使用一个元组收取BGR3通道的
(B, G, R) = cv2.split(img)
with open (save_dir, 'wb') as fp:
for i in range(1024):
for j in range(2048):
fp.write(B[i, j])
# print(B[i, j])
for i in range(1024):
for j in range(2048):
fp.write(G[i, j])
# print(G[i, j])
for i in range(1024):
for j in range(2048):
fp.write(G[i, j])
# print(G[i, j])
print("write success!")
if __name__ == '__main__':
count = 1
for i in os.listdir(Img_dir):
imdir = Img_dir+'/'+i
save_dir = Save_dir+'/'+'{}.bgr'.format(count)
png2bgr(imdir, save_dir)
count+=1
if count == 21: # 这里我只需要20张即可
print('convert over')
break
转换之后就是.bgr文件