bigchaipat
bigchaipat

Reputation: 973

Retrieve RGB image from 1-dim array containing RGB image data

I pass a C array containing RGB image data to a function in Python to further process the image. How can I retrieve this image and plot it as well in Python?

the C array named c_data that contains RGB image data was created by

for(k = 0; k < c; ++k){
    for(j = 0; j < h; ++j){
        for(i = 0; i < w; ++i){
            int dst_index = i + w*j + w*h*k;
            int src_index = k + c*i + c*w*j;
            c_data[dst_index] = (float)stb_im[src_index]/255.;
        }
    }
}

the C array is converted into a numpy array and is passed to the Python function with the following header via the parameter named im_data

def read_img_from_c(im_data, im_h, im_w):

print(im_h) // 480
print(im_w) // 640
print(im_data.shape) // (921600,) --> (480*640*3)

I tried to simply reshape the numpy array using

data = im_data.reshape((im_h, im_w, 3)) 

and create a PIL image object using

img = PIL.Image.fromarray(data, 'RGB')

, but when I run the following command

img.show()

I got the following rather than the original image.

enter image description here

Update: I follow the suggestion by multiplying those normalized pixel values by 255.0, cast the numpy array to type int and plot:

im_data = (im_data*255.0).astype(np.uint8)
im_data = im_data.reshape((im_h, im_w, 3))
img = Image.fromarray(im_data, 'RGB')
img.show()

and I got the image with repeated patterns instead of a single big RGB image:

The original image was from the MOT16-02 sequence of the MOTChallenge Benchmark dataset

Upvotes: 1

Views: 704

Answers (2)

bigchaipat
bigchaipat

Reputation: 973

After spent a day for recovering this image, I have found a solution.

I believe that the flatten version of my normalized image pixels were stored in the one-dimensional array named im_data that looks like this

[ r1 g1 b1 r2 g2 b2 ... rN gN bN]

, where subscript N is the number of pixels.

So, the first step I multiply each pixel with 255.0 to get pixel values between 0-255:

import numpy as np
im_data = (im_data*255.0).astype(np.uint8)

and rather than reshaping the array using a shape of (im_h, im_w, 3), I reshape it using a shape of (3, im_h, im_w) so:

im_data = im.reshape((3, im_h, im_w))

Finally, I transpose the result numpy array to get a correct image shape, which is (im_h, im_w, 3), so:

im_data = np.transpose(im, (1, 2, 0))

Finally,

img = Image.fromarray(im_data, 'RGB')
img.show() 

and boom: enter image description here (the image is one of the MOTChallenge benchmark dataset https://motchallenge.net/)

To be honest, I am not totally sure about how all these works out. I just mess around with array operations.

Upvotes: 1

Artur Kasza
Artur Kasza

Reputation: 376

Try multiplying data by 255 again and rounding it to int. I guess the values in RGB tuple should be from range 0-255, not 0-1.

Upvotes: 1

Related Questions