参考资料:http://www.voidcn.com/article/p-sabqihis-bry.html
参考资料: https://blog.csdn.net/yang_bingo/article/details/84066217
1、使用cv2
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
img_url = r'C:\Users\xxc\Desktop\capture.png'
with open(img_url, 'rb') as f:
a = f.read()
# 二进制数据流转np.ndarray [np.uint8: 8位像素]
img = cv2.imdecode(np.frombuffer(a, np.uint8), cv2.IMREAD_COLOR)
# # 将bgr转为rbg
rgb_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
print(rgb_img)
# np.ndarray转IMAGE
a = Image.fromarray(rgb_img)
print(a)
# 显示图片
a.show()
2、使用io.BytesIO
import io
from PIL import Image
img_url = r'C:\Users\xxc\Desktop\capture.png'
with open(img_url, 'rb') as f:
a = f.read()
print(type(a))
# 将字节对象转为Byte字节流数据,供Image.open使用
byte_stream = io.BytesIO(a)
print(type(byte_stream))
roiImg = Image.open(byte_stream)
# 图片保存
roiImg.save(r'C:\Users\xxc\Desktop\save.png')
小结:cv2和io.BytesIO相比,多了一步bgr转rbg,可能使用io.BytesIO更加方便。