Python - byte image to NumPy array using OpenCV

后端 未结 2 893
暖寄归人
暖寄归人 2021-02-08 08:27

I have an image in bytes:

print(image_bytes)

b\'\\xff\\xd8\\xff\\xfe\\x00\\x10Lavc57.64.101\\x00\\xff\\xdb\\x00C\\x00\\x08\\x04\\x04\\x04\\x04

2条回答
  •  抹茶落季
    2021-02-08 09:19

    I created a 2x2 JPEG image to test this. The image has white, red, green and purple pixels. I used cv2.imdecode and numpy.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)
    

    This seems to work, although the channel order is BGR and not RGB as in PIL.Image. There are probably some flags you might use to tune this. Test results:

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

提交回复
热议问题