Python - byte image to NumPy array using OpenCV

后端 未结 2 897
暖寄归人
暖寄归人 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:02

    I searched all over the internet finally I solved:

    NumPy array (cv2 image) - Convert

    NumPy to bytes

    and

    bytes to NumPy

    :.

    #data = cv2 image array
    def encodeImage(data):
        #resize inserted image
        data= cv2.resize(data, (480,270))
        # run a color convert:
        data= cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
        return bytes(data) #encode Numpay to Bytes string
    
    
    
    def decodeImage(data):
        #Gives us 1d array
        decoded = np.fromstring(data, dtype=np.uint8)
        #We have to convert it into (270, 480,3) in order to see as an image
        decoded = decoded.reshape((270, 480,3))
        return decoded;
    
    # Load an color image
    image= cv2.imread('messi5.jpg',1)
    
    img_code = encodeImage(image) #Output: b'\xff\xd8\xff\xe0\x00\x10...';
    img = decodeImage(img_code) #Output: normal array
    cv2.imshow('image_deirvlon',img);
    print(decoded.shape)
    

    You can get full code from here

提交回复
热议问题