使用OpenCV从Python字节图像到NumPy数组

2024-05-18 15:47:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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,或者其他更快的库?


Tags: imagebytesx00x04x03x01xffx11
1条回答
网友
1楼 · 发布于 2024-05-18 15:47:54

我创建了一个2x2 JPEG image来测试这个。图像有白色、红色、绿色和紫色像素。我用了^{}^{}

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]]]

相关问题 更多 >

    热门问题