python 图片base64 编解码,转换成Opencv,PIL.Image图片格式

752 阅读1分钟

Python PIL.Image和OpenCV图像格式相互转换

二进制打开图片文件,base64编解码转成Opencv格式:

# coding: utf-8
import base64
import numpy as np
import cv2
 
img_file = open('1.jpg','rb')   # 二进制打开图片文件
img_b64encode = base64.b64encode(img_file.read())  # base64编码
img_file.close()  # 文件关闭
img_b64decode = base64.b64decode(img_b64encode)  # base64解码
 
img_array = np.fromstring(img_b64decode,np.uint8) # 转换np序列
img=cv2.imdecode(img_array,cv2.COLOR_BGR2RGB)  # 转换Opencv格式
 
cv2.imshow("img",img)
cv2.waitKey()

二进制打开图片文件,base64编解码,转成PIL.Image格式:

# coding: utf-8
# python base64 编解码,转换成Opencv,PIL.Image图片格式
import base64
import io
from PIL import Image
 
img_file = open('1.jpg','rb')   # 二进制打开图片文件
img_b64encode = base64.b64encode(img_file.read())  # base64编码
img_file.close()  # 文件关闭
img_b64decode = base64.b64decode(img_b64encode)  # base64解码
 
image = io.BytesIO(img_b64decode)
img = Image.open(image)
img.show()

欢迎关注公众号:算法工程师的学习日志,获取算法工程师的学习资料。如果有技术咨询,提供有偿咨询,联系qq(1762016542)或者公众号留言