我有一个以字节为单位的图像:

print(image_bytes)

b'\xff\xd8\xff\xfe\x00\x10Lavc57.64.101\x00\xff\xdb\x00C\x00\x08\x04\x04\x04\x04\x04\x05\x05\x05\x05\x05\x05\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x07\x07\x07\x08\x08\x08\x07\x07\x07\x06\x06\x07\x07\x08\x08\x08\x08\t\t\t\x08\x08\x08\x08\t\t\n\n\n\x0c\x0c\x0b\x0b\x0e\x0e\x0e\x11\x11\x14\xff\xc4\x01\xa2\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x01\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\ ... some other stuff

我可以使用Pillow将其转换为NumPy数组:

image = numpy.array(Image.open(io.BytesIO(image_bytes))) 

但我真的不喜欢用枕头.有没有办法使用clear OpenCV,或者直接使用NumPy甚至更好,或者其他更快的库?

推荐答案

我创建了一个2x2 JPEG image来测试这个.图像有白色、红色、绿色和紫色像素.我用了cv2.imdecodenumpy.frombuffer

import cv2
import numpy as np

f = open('image.jpg', 'rb')
image_bytes = f.read()  # b'\xff\xd8\xff\xe0\x00\x10...'

decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)

print('OpenCV:\n', decoded)

# your Pillow code
import io
from PIL import Image
image = np.array(Image.open(io.BytesIO(image_bytes))) 
print('PIL:\n', image)

这似乎是可行的,尽管通道顺序是BGR,而不是PIL.Image中的RGB.您可能会使用一些标志来调整此设置.测试结果:

OpenCV:
 [[[255 254 255]
  [  0   0 254]]

 [[  1 255   0]
  [254   0 255]]]
PIL:
 [[[255 254 255]
  [254   0   0]]

 [[  0 255   1]
  [255   0 254]]]

Python-3.x相关问答推荐

"安装serial vs安装psyserial header,"""

像计数不显示在html和想知道如果我的模型设置正确

Django内置注销视图`不允许的方法(GET):/USERS/LOGOUT/`

使用 Fetch 提交表单到 Django 视图

比较和排序 DataFrame 两列中的值并在 python 中的同一行中排序

Pandas 窗口聚合两个排序表

如何对具有多个列值的 pandas 数据框进行数据透视/数据透视表

如何在 Telethon 中向机器人发送发送表情符号

python2和python3中的列表生成器

将元组列表转换为以整个元组为键的字典列表

SMTP 库 Python3:不太安全的应用程序访问

Python 3 `str.__getitem__` 的计算复杂度是多少?

删除括号和大括号中不必要的空格

具有 2 个输入的 python 3 map/lambda 方法

python 3.4版不支持'ur'前缀

在 Pandas 数据框中显示对图

如何调试垂死的 Jupyter Python3 内核?

当默认 pip 为 pip2 时,升级 pip3 的正确格式是什么?

清除 PyCharm 运行窗口

TypeError:无法实例化类型元组;使用 tuple() 代替