PIL 和 pythonopencv 从内存字节码中读取图片并转为np.array格式

把某个RGB格式的图片以字节码的形式读入到内存中,然后使用PIL 和 CV2 来进行读写,并转成np.array 格式。

代码:

from PIL import Image
import cv2
import numpy as np

from io import BytesIO


f_path = '/home/devil/x.JPEG'

img = Image.open(f_path)
img_array = np.array(img.convert('RGB'))


f_bytes = open(f_path, 'rb').read()


img_array2 = Image.open(BytesIO(f_bytes))
img_array2 = np.asarray(img_array2, np.uint8)
# f_array_bytes = np.asarray(bytearray(f_bytes),np.uint8) f_array_bytes = np.frombuffer(f_bytes, np.uint8) img_array3 = cv2.cvtColor(cv2.imdecode(f_array_bytes, cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB) print(np.all(img_array==img_array2)) print(np.all(img_array==img_array3))

==============================================

本博客是博主个人学习时的一些记录,不保证是为原创,个别文章加入了转载的源地址还有个别文章是汇总网上多份资料所成,在这之中也必有疏漏未加标注者,如有侵权请与博主联系。
原文地址:https://www.cnblogs.com/devilmaycry812839668/p/15619333.html