Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine 3 separate numpy arrays to an RGB image in Python

So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image.

I tried 'Image' to do the job but it requires 'mode' to be attributed.

I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' mode by default when Image.merge requires 'L' mode images to merge. If I would declare the attribute of array in fromarray() to 'L' at first place, all the R G B images become distorted.

But, if I save the images and then open them and then merge, it works fine. Image reads the image with 'L' mode.

Now I have two issues.

First, I dont think it is an elegant way of doing the work. So if anyone knows the better way of doing it, please tell

Secondly, Image.SAVE is not working properly. Following are the errors I face:

In [7]: Image.SAVE(imagefile, 'JPEG') ----------------------------------------------------------------------------------  TypeError                                 Traceback (most recent call last)  /media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>()  TypeError: 'dict' object is not callable 

Please suggest solutions.

And please mind that the image is around 4000x4000 size array.

like image 701
Ishan Tomar Avatar asked May 04 '12 05:05

Ishan Tomar


People also ask

How do I merge multiple arrays in NumPy?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.

Can you combine NumPy arrays?

We can perform the concatenation operation using the concatenate() function. With this function, arrays are concatenated either row-wise or column-wise, given that they have equal rows or columns respectively. Column-wise concatenation can be done by equating axis to 1 as an argument in the function.


2 Answers

rgb = np.dstack((r,g,b))  # stacks 3 h x w arrays -> h x w x 3 

To also convert floats 0 .. 1 to uint8 s,

rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8)  # right, Janna, not 256 
like image 50
denis Avatar answered Sep 23 '22 16:09

denis


I don't really understand your question but here is an example of something similar I've done recently that seems like it might help:

# r, g, and b are 512x512 float arrays with values >= 0 and < 1. from PIL import Image import numpy as np rgbArray = np.zeros((512,512,3), 'uint8') rgbArray[..., 0] = r*256 rgbArray[..., 1] = g*256 rgbArray[..., 2] = b*256 img = Image.fromarray(rgbArray) img.save('myimg.jpeg') 

I hope that helps

like image 28
Bi Rico Avatar answered Sep 23 '22 16:09

Bi Rico