PIL.Image、cv2的img、bytes相互转换
发布日期:2025-05-05 08:13:27 浏览次数:2 分类:精选文章

本文共 1175 字,大约阅读时间需要 3 分钟。

PIL.Image 与 OpenCV 的图像与字节数据转换指南

1. bytes 转换为 PIL.Image

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()  # 查看图片

2. PIL.Image 转换为 bytes

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()

3. OpenCV 图像转换为 bytes

import cv2# 假设 img_numpy 是一个 OpenCV 图像数组_, img_encode = cv2.imencode('.jpg', img_numpy)# 获取字节数据img_bytes = img_encode.tobytes()

4. bytes 转换为 OpenCV 图像

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)

5. PIL 转 OpenCV 图像

from PIL import Imageimport cv2# 读取 PIL 图像img = Image.open("test.jpg")# 将 PIL 图像转换为 OpenCV 格式(BGR)img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

6. OpenCV 转换为 PIL 图像

import cv2from PIL import Image# 读取 OpenCV 图像img = cv2.imread("test.jpg")# 将 OpenCV 图像转换为 PIL 格式(RGB)img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
上一篇:PIL.Image进行图像融合显示(Image.blend)
下一篇:PIL&QOOT;IOERROR:带有大图像的图像文件被截断(&Q)

发表评论

最新留言

表示我来过!
[***.240.166.169]2026年06月05日 15时29分03秒