图像类型转换代码
OpenCV(Numpy)与PIL互转
img_pil转img_np
from PIL import Image
import numpy as np
img_pil = Image.open("./test.png")
img_np = np.array(img_pil)
img_np转img_pil
from PIL import Image
import numpy as np
# 生成一个随机数组
# randint()生成一定范围的数组
# random()生成0-1之间的均匀分布
# randn() 生成高斯分布
img_np=np.random.randint(0,255,(48,48))
img_pil = Image.fromarray(img_np)
OpenCV(Numpy)与Base64互转
img_np转img_base64
def imgNP_to_imgBase64(img_np):
"""
convert img_np to img_base64
"""
img_bytes = cv2.imencode('.jpg', img_np)[1].tobytes() #将图片编码成流数据,放到内存缓存中,然后转化成byte格式
img_base64 = base64.b64encode(img_bytes) # 编码为base64
# 将byte格式的Base64编码转换成utf-8字符串
# img_base64_string = img_base64.decode('utf-8') # or img_base64_string = str(img_base64, encoding="utf8")
return img_base64
img_base64转img_np
def imgBase64_to_imgNP(img_base64):
"""
convert img_base64 to img_np
"""
img_bytes = base64.b64decode(img_base64) # 该输入同样适配Base64的utf-8字符串img_base64_string
nparr = np.frombuffer(img_bytes, dtype=np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img_np
直接读图转成Base64的utf-8字符串并重新存图
with open(img_path, 'rb') as jpg_file:
img_bytes = jpg_file.read()
img_base64 = base64.b64encode(img_bytes)
img_base64_string = img_base64.decode('utf-8')
# 将 base64 字符串解码成图片字节码
img_bytes = base64.b64decode(img_base64_string)
# 将字节码以二进制形式存入图片文件中,注意 'wb'
with open(img_path, 'wb') as jpg_file:
jpg_file.write(img_bytes)
PIL与Base64互转
img_pil转img_base64
from PIL import Image
import io
import base64
img_pil = Image.open('image.jpg')
# 创建一个BytesIO对象,用于临时存储图像数据
img_bytesIO = io.BytesIO()
# 将图像保存到BytesIO对象中,格式为JPEG
img_pil.save(img_bytesIO, format='JPEG')
# 将BytesIO对象的内容转换为字节串
img_bytes = img_bytesIO.getvalue()
# 将图像数据编码为Base64字符串
img_base64_string = base64.b64encode(img_bytes).decode('utf-8')
img_base64转img_pil
from io import BytesIO
import base64
from PIL import Image
def imgBase64_to_imgPil(img_base64_string: str) -> Image.Image:
img_bytes = base64.b64decode(img_base64_string)
img_bytesIO = BytesIO(img_bytes)
img_pil = Image.open(img_bytesIO)
return img_pil
# 或者一行代码表示
img_pil = Image.open(BytesIO(base64.b64decode(img_base64_string))).convert("RGB")