Python 对图像进行base64编码及解码读取为numpy、opencv、matplot需要的格式
这篇博客将介绍Python如何对图像进行base64编解码及读取为numpy、opencv、matplot需要的格式。
1. 效果图
原始图如下:
base64转换为numpy数组效果图如下(一维):
base64转换为opencv BGR VS 灰度效果图如下:
base64转换为 matplot RGB VS 灰度效果图如下:
2. 源码
- base64编码图片为string
- base64解码string为图片
- base64解码string为numpy、opencv、matplot图片
import base64
import cv2
import numpy as np
from matplotlib import pyplot as plt
def write2txt(name, base64_data):
print(name)
print(name,len(base64_data))
basef = open(name + '_base64.txt', 'w')
data = 'data:image/jpg;base64,%s' % base64_data
basef.write(base64_data)
basef.close()
def encode_base64(file):
with open(file, 'rb') as f:
img_data = f.read()
base64_data = base64.b64encode(img_data)
print(type(base64_data))
base64_str = str(base64_data, 'utf-8')
print(len(base64_data))
write2txt(file.replace(".jpg", ""), base64_str)
return base64_data
def decode_base64(base64_data):
with open('./images/base64.jpg', 'wb') as file:
img = base64.b64decode(base64_data)
file.write(img)
def decode_base64_np_img(base64_data):
img = base64.b64decode(base64_data)
img_array = np.fromstring(img, np.uint8)
print('numpy: ', img_array.shape)
cv2.imshow("img", img_array)
cv2.waitKey(0)
def decode_base64_cv_img(base64_data):
img = base64.b64decode(base64_data)
img_array = np.fromstring(img, np.uint8)
img_raw = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
img_gray = cv2.imdecode(img_array, cv2.IMREAD_GRAYSCALE)
print('opencv bgr: ', img_raw.shape)
print('opencv gray: ', img_gray.shape)
cv2.imshow("img bgr", img_raw)
cv2.imshow("img gray", img_gray)
cv2.waitKey(0)
def decode_base64_matplot_img(base64_data):
img = base64.b64decode(base64_data)
img_array = np.fromstring(img, np.uint8)
img_raw = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
img_matplot = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
img_gray = cv2.imdecode(img_array, cv2.IMREAD_GRAYSCALE)
imggray_matplot = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)
plt.figure()
plt.title("Matplot RGB Origin Image")
plt.axis("off")
plt.imshow(img_matplot)
plt.figure()
plt.title("Matplot Gray Origin Image")
plt.axis("off")
plt.imshow(imggray_matplot)
plt.show()
if __name__ == '__main__':
img_path = './images/1622175322109_0.025711.jpg'
base64_data = encode_base64(img_path)
decode_base64(base64_data)
decode_base64_np_img(base64_data)
decode_base64_cv_img(base64_data)
decode_base64_matplot_img(base64_data)
参考
|