本文共 1209 字,大约阅读时间需要 4 分钟。
from io import BytesIOfrom PIL import Image# 读取文件内容with open("test_for_classification.png", "rb") as f: file = f.read()# 将 bytes 转换为 PIL.Imageimg = Image.open(BytesIO(file))img.show() # 查看图片 from PIL import Imagefrom io import BytesIO# 读取图片文件img = Image.open('test.jpg', mode='r')# 将图片保存为 bytes 格式img_bytes = BytesIO()img.save(img_bytes, format='JPEG')# 获取字节数据img_bytes = img_bytes.getvalue() import cv2# 假设 img_numpy 是一个 OpenCV 图像数组_, img_encode = cv2.imencode('.jpg', img_numpy)# 获取字节数据img_bytes = img_encode.tobytes() import numpy as npimport cv2# 将字节数据转换为 OpenCV 图像数组img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8)# 解码字节数据为 OpenCV 图像img_numpy = cv2.imdecode(img_buffer_numpy, 1)
from PIL import Imageimport cv2# 读取 PIL 图像img = Image.open("test.jpg")# 将 PIL 图像转换为 OpenCV 格式(BGR)img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) import cv2from PIL import Image# 读取 OpenCV 图像img = cv2.imread("test.jpg")# 将 OpenCV 图像转换为 PIL 格式(RGB)img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) 转载地址:http://oqtfk.baihongyu.com/