PIL、cv2、bytes三种图片格式相互转换

PIL、cv2、bytes三种图片格式相互转换

别人写的,这个看着最舒服就搬运一下,原文链接

1. PIL 与 cv2 相互转化

import cv2
from PIL import Image
import numpy as np

# PIL 转 cv2
img= Image.open("test.jpg")
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
print(type(img))



# cv2 转 PIL
img = cv2.imread("test.jpg")
img= Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
print(type(img))

2. PIL 与 bytes 相互转化

'''
    bytes 转 PIL 
'''
# 第一类:转换 本地的bytes图片 为 PIL
with open('test.jpg', 'rb') as f:
    content = f.read()  
local_img = Image.open(BytesIO(content))   
print(type(local_img))  



# 第二类:转换 网络上的bytes图片 为 PIL
url = 'https://z3.ax1x.com/2021/07/13/WAuYJU.jpg'
content = requests.get(url, stream=True).content
net_img = Image.open(BytesIO(content))   # BytesIO实现了在内存中读写Bytes
print(type(net_img))    






'''
    PIL 转 bytes
'''
img_bytes  = BytesIO()
img = Image.open('test.jpg', mode='r')
img.save(img_bytes, format='JPEG')
img_bytes = img_bytes.getvalue()
print(type(img_bytes)) 

3. cv2 与bytes 相互转化

import numpy as np
import cv2


# bytes 转 numpy
img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8)  # 将 图片字节码bytes  转换成一维的numpy数组 到缓存中
img_numpy = cv2.imdecode(img_buffer_numpy, 1)   # 从指定的内存缓存中读取一维numpy数据,并把数据转换(解码)成图像矩阵格式



# numpy 转 bytes
 _, img_encode = cv2.imencode('.jpg', img_numpy)
img_bytes = img_encode.tobytes()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值