pythonimage-processingarduinoheximage-conversion

Hexstring to img conversion


I'm using an arduino board to take a picture and it returns a HEX string. I've tried numpy, openCV, binascii and others but i'm not able to convert and save this image in RGB like a picture.

I get an "corrupted image" I can't open on my device but if a throw it in RAW Pixels I can see the image how it should be.

The original size of the picture (seted on arduino board is QVGA 320x240).

The HEX string is HERE. | EDIT: alternative HEX HERE.

And the result (by rawpixels) is this, revealing the data to represent a 320x240 image encoded using RGB565.

This is my actual code that saves a "corrupted file" but opens in rawpixels.net

with open('img.txt') as file:
    data = file.read()

data = bytes.fromhex(data[2:])

with open('image.png', 'wb') as file:
    file.write(data)

Solution

  • You can decode the image in only a few lines of code using opencv:

    import numpy as np
    import cv2
    
    with open("hex.txt") as file:
        data = file.read()
        buff = bytes.fromhex(data)
    
    # Convert to 3 channel uint8 numpy array representing the BGR image
    img = cv2.cvtColor(
        np.frombuffer(buff, dtype=np.uint8).reshape(240, 320, 2), cv2.COLOR_BGR5652BGR
    )
    # Save the image to a png file
    cv2.imwrite("image.png", img)