PIL、cv2、bytes三种图片格式相互转换
别人写的,这个看着最舒服就搬运一下,原文链接
1. PIL 与 cv2 相互转化
import cv2
from PIL import Image
import numpy as np
img= Image.open("test.jpg")
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
print(type(img))
img = cv2.imread("test.jpg")
img= Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
print(type(img))
2. PIL 与 bytes 相互转化
'''
bytes 转 PIL
'''
with open('test.jpg', 'rb') as f:
content = f.read()
local_img = Image.open(BytesIO(content))
print(type(local_img))
url = 'https://z3.ax1x.com/2021/07/13/WAuYJU.jpg'
content = requests.get(url, stream=True).content
net_img = Image.open(BytesIO(content))
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
img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8)
img_numpy = cv2.imdecode(img_buffer_numpy, 1)
_, img_encode = cv2.imencode('.jpg', img_numpy)
img_bytes = img_encode.tobytes()