Drona Nagarajan
Drona Nagarajan

Reputation: 99

From Raw binary image data to PNG in Python

After searching for a few hours, I ended up on this link. A little background information follows.

I'm capturing live frames of a running embedded device via a hardware debugger. The captured frames are stored as raw binary files, without headers or format. After looking at the above link and understanding, albeit perfunctorily, the NumPY and Matplotlib, I was able to convert the raw binary data to an image successfully. This is important because I'm not sure if the link to the raw binary file will help any one.

I use this code:

import matplotlib.pyplot as plt # study documentation
import numpy as np              #   "       " 

iFile = "FramebufferL0_0.bin" # Layer-A
shape = (430, 430) # length and width of the image
dtype = np.dtype('<u2') # unsigned 16 bit little-endian.
oFile = "FramebufferL0_0.png"

fid = open(iFile, 'rb')
data = np.fromfile(fid, dtype)
image = data.reshape(shape)

plt.imshow(image, cmap = "gray")
plt.savefig(oFile)
plt.show()

Now, the image I'm showing is black and white because the color map is gray-scale (right?). The actual captured frame is NOT black and white. That is, the image I see on my embedded device is "colorful".

My question is, how can I calculate actual color of each pixel from the raw binary file? Is there a way I can get the actual color map of the image from the raw binary? I looked into this example and I'm sure that, if I'm able to calculate the R, G and B channels (and Alpha too), I'll be able to recreate the exact image. An example code would be of much help.

Upvotes: 2

Views: 1880

Answers (1)

Paul Brodersen
Paul Brodersen

Reputation: 13031

An RGBA image has 4 channels, one for each color and one for the alpha value. The binary file seems to have a single channel, as you don't report an error when performing the data.reshape(shape) operation (the shape for the corresponding RGBA image would be (430, 430, 4)). I see two potential reasons:

  1. The image actual does have colour information but when you are grabbing the data you are only grabbing one of the four channels.

  2. The image is actually a gray-scale image, but the embedded device shows a pseudocolor image, creating the illusion of colour information. Without knowing what the colourmap is being used, it is hard to help you, other than point you towards matplotlib.pyplot.colormaps(), which lists all already available colour maps in matplotlib.

Could you

a) explain the exact source / type of imaging modality, and

b) show a photo of the output of the embedded device?

PS: Also, at least in my hands, the pasted binary file seems to have a size of 122629, which is incongruent with an image shape of (430,430).

Upvotes: 2

Related Questions