python图像数据互转(numpy,bytes,base64,file)import cv2
import numpy as np
import base64
from tkinter import *
from io import BytesIO
# 数组转base64
def numpy_to_base64(image_np):
data = cv2.imencode('.jpg', image_np)[1]
image_bytes = bytes()
image_base4 = base64.b64encode(image_bytes).decode('utf8')
return image_base4
# 数组转bytes
def numpy_to_bytes(image_np):
data = cv2.imencode('.jpg', image_np)[1]
image_bytes = bytes()
return image_bytes
# 数组保存
def numpy_to_file(image_np):
filename = '你的⽂件名_numpy.jpg'
cv2.imwrite(filename,image_np)
return filename
# bytes转数组
def bytes_to_numpy(image_bytes):
image_np = np.frombuffer(image_bytes, dtype=np.uint8)
image_np2 = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
return image_np2
# bytes 转 base64
def bytes_to_base64(image_bytes):
image_base4 = base64.b64encode(image_bytes).decode('utf8')
return image_base4
# bytes 保存
def bytes_to_file(image_bytes):
filename = '你的⽂件名_bytes.jpg'
with open(filename,'wb') as f:
f.write(image_bytes)
return filename
# ⽂件转数组
def file_to_numpy(path_file):
image_np = cv2.imread(path_file)
return image_np
# ⽂件转字节
def file_to_bytes(path_file):
with open(path_file,'rb') as f:
image_bytes = f.read()
return image_bytes
# ⽂件转base64
def file_to_base64(path_file):
with open(path_file,'rb') as f:
image_bytes = f.read()
image_base64 = base64.b64encode(image_bytes).decode('utf8')
return image_base64
# base64 转 bytes
def base64_to_bytes(image_base64):
numpy教程pdfimage_bytes = base64.b64decode(image_base64)
return image_bytes
# base64转数组
def base64_to_numpy(image_base64):
image_bytes = base64.b64decode(image_base64)
image_np = np.frombuffer(image_bytes, dtype=np.uint8)
image_np2 = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
return image_np2
# base64 保存
def base64_to_file(image_base64):
filename = '你的⽂件名_base64.jpg'
image_bytes = base64.b64decode(image_base64)
with open(filename, 'wb') as f:
f.write(image_bytes)
return filename
# base64图像转cv2的BGR图⽚(PIL为RGB图⽚)
def base64Toimg(self,imgstr):
# image = io.BytesIO(imgstr)
base64_data = re.sub('^data:image/.+;base64,', '', imgstr)    image = base64.b64decode(base64_data)
image_data = BytesIO(image)
img = Image.open(image_data)
img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB) return img

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。