Just do

Image.fromarray(np.array(img).astype(np.uint8).transpose(1,2,0))
Answer from Maiia Bocharova on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how to convert rgb array to image?
r/learnpython on Reddit: How to convert RGB array to image?
May 6, 2023 -

So I tried to convert a raw RGB array to an image with this simple code:

import numpy as np

from PIL import Image

Canvas = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 0], [0, 0, 0]])

img = Image.fromarray(Canvas, 'RGB')

img = img.save("canvas.png")

I have no idea how to set the size of the image as a resolution of 2x2 because this code does not create the correct resolution

The first pixel in Canvas should be red, second pixel should be green, the third and fourth pixels should be black

All I want is a 2x2 resolution image where the top-left pixel is red and the top-right pixel is green, then both bottom pixels should be black, but my code is just producing the wrong image resolution with the wrong pixel locations. What is the issue?

Discussions

python - RGB matrix of an image - Stack Overflow
This gives you a 640x480 PixelAccess array of RGBA 4-tuples. ... Sign up to request clarification or add additional context in comments. ... An update: imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead. More on stackoverflow.com
🌐 stackoverflow.com
Combine 3 separate numpy arrays to an RGB image in Python - Stack Overflow
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 '... More on stackoverflow.com
🌐 stackoverflow.com
python - RGB array to PIL image - Stack Overflow
I am having an array of rgb tuples array = [(144, 144, 133), (85, 87, 75), (140, 87, 70), (129, 107, 105), (129, 107, 105), (194, 179, 171), (178, 164, 159), (100, 105, 122), (36, 38, 57), (59, 48,... More on stackoverflow.com
🌐 stackoverflow.com
May 8, 2022
python - Convert a raw RGB array into a png image. - Stack Overflow
I am trying to read a image file using PIL and then obtaining the raw pixel values in form of numpy array and then i am trying to put together the values to form a copy of original image. The code ... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 5
25

Note that this answer is outdated as of 2018; scipy has deprecated imread, and you should switch to imageio.imread. See this transition doc about differences between the two. The code below should work with no changes if you just import the new library in place of the old, but I haven’t tested it.


The simplest answer is to use the NumPy and SciPy wrappers around PIL. There's a great tutorial, but the basic idea is:

from scipy import misc
arr = misc.imread('lena.png') # 640x480x3 array
arr[20, 30] # 3-vector for a pixel
arr[20, 30, 1] # green value for a pixel

For a 640x480 RGB image, this will give you a 640x480x3 array of uint8.

Or you can just open the file with PIL (or, rather, Pillow; if you're still using PIL, this may not work, or may be very slow) and pass it straight to NumPy:

import numpy as np
from PIL import Image
img = Image.open('lena.png')
arr = np.array(img) # 640x480x4 array
arr[20, 30] # 4-vector, just like above

This will give you a 640x480x4 array of type uint8 (the 4th is alpha; PIL always loads PNG files as RGBA, even if they have no transparency; see img.getbands() if you're every unsure).

If you don't want to use NumPy at all, PIL's own PixelArray type is a more limited array:

arr = img.load()
arr[20, 30] # tuple of 4 ints

This gives you a 640x480 PixelAccess array of RGBA 4-tuples.

Or you can just call getpixel on the image:

img.getpixel(20, 30) # tuple of 4 ints
2 of 5
15

I have a feeling I'm not doing exactly what you wanted here, so please specify if this is totally off. You could open the image like this and get an array of pixels:

import Image
im = Image.open('Lenna.png')
pixels = list(im.getdata())

This will get you a flat list of RGB data that looks like

[(226, 137, 125), (226, 137, 125), (223, 137, 133), (223, 136, 128), 
 (226, 138, 120), (226, 129, 116), (228, 138, 123), (227, 134, 124), 
 (227, 140, 127), (225, 136, 119), (228, 135, 126), (225, 134, 121),...

Now this will be all pixels in a flat array, if you want a two dimensional array then some additional code would be needed for that. Not sure if there is a direct function for it in PIL.

🌐
Stack Overflow
stackoverflow.com › questions › 72161115 › rgb-array-to-pil-image
python - RGB array to PIL image - Stack Overflow
May 8, 2022 - You reshape your array into an 2d array with shape [sqrt(size),sqrt(size)]. What you need instead is a 3d array with shape [sqrt(size),sqrt(size),3] (x dimension, y dimension, 3 RGB values).
🌐
Stack Overflow
stackoverflow.com › questions › 48832292 › convert-a-raw-rgb-array-into-a-png-image
python - Convert a raw RGB array into a png image. - Stack Overflow
I am trying to read a image file using PIL and then obtaining the raw pixel values in form of numpy array and then i am trying to put together the values to form a copy of original image. The code does not produce any runtime error but the image formed ("my.png") is unreadable. from PIL import Image import numpy as np img_filename = "image.png" img = Image.open(img_filename) img = img.convert("RGB") img.show() aa = np.array(img.getdata()) alpha = Image.fromarray(aa,"RGB") alpha.save('my.png') alpha.show() python ·
🌐
Astropy
docs.astropy.org › en › stable › visualization › rgb.html
Creating color RGB images — Astropy v8.0.1
RGB images can be produced using matplotlib’s ability to make three-color images. In general, an RGB image is an MxNx3 array, where M is the y-dimension, N is the x-dimension, and the length-3 layer represents red, green, and blue, respectively.
Find elsewhere
🌐
Pythoninformer
pythoninformer.com › python-libraries › numpy › numpy-and-images
PythonInformer - Image processing with pillow and NumPy
October 2, 2022 - Now let's fill the array with orange pixels (red=255, green=128, blue=0). We use slices to do this, the three values are broadcast across all the rows and columns of the array: ... The PIL function Image.fromarray function creates a PIL image from a NumPy array.
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-109.php
Python NumPy: Convert a numpy array to an image - w3resource
August 29, 2025 - # Importing the Image module from ... an image object 'img' from the NumPy array 'data', specifying the color mode as 'RGB' img = Image.fromarray(data, 'RGB') # Saving the image as 'test.png' img.save('test.png') # Displaying ...
Top answer
1 of 2
4

In your comment you specify that the red_arr, etc. are arrays of the range -4000 to 4000.

But if we take a look at the specifications of the Image.from_array modes, then we see that it expects a matrix of three bytes (values from zero to 255).

This is however not per se a problem: we can perform:

def rescale(arr):
    arr_min = arr.min()
    arr_max = arr.max()
    return (arr - arr_min) / (arr_max - arr_min)

red_arr_b = 255.0 * rescale(red_arr)
green_arr_b = 255.0 * rescale(green_arr)
blue_arr_b = 255.0 * rescale(blue_arr)

arr[:,:,0] = red_arr_b
arr[:,:,1] = green_arr_b
arr[:,:,2] = blue_arr_b

img = Image.fromarray(arr.astype(int), 'RGB')

So first we rescale to a range 0 to 255, and then we feed that array to the PIL.

It is also possible that we want to scale red, green and blue the same way. In that case we can use:

def rescale(arr):
    arr_min = arr.min()
    arr_max = arr.max()
    return (arr - arr_min) / (arr_max - arr_min)

arr[:,:,0] = red_arr
arr[:,:,1] = green_arr
arr[:,:,2] = blue_arr

arr = 255.0 * rescale(arr)

img = Image.fromarray(arr.astype(int), 'RGB')
2 of 2
4

Your np array should have data type as uint8:

arr = np.zeros((len(x), len(z), 3),dtype='uint8')

Essentially, PIL calls tobytes function on each strides of your arr and if they are of type int, extra bytes will be generated.

Here are the result of following piece of code with different data type.

import numpy as np
from PIL import Image

size=241

arr = np.zeros((size,size,3))

arr[:,:,0] = [[255]*size]*size
arr[:,:,1] = [[255]*size]*size
arr[:,:,2] = [[0]*size]*size

img = Image.fromarray(arr.astype(int), 'RGB')

import numpy as np
from PIL import Image

size=241

arr = np.zeros((size,size,3))

arr[:,:,0] = [[255]*size]*size
arr[:,:,1] = [[255]*size]*size
arr[:,:,2] = [[0]*size]*size

img = Image.fromarray(arr.astype('uint8'), 'RGB')

As suggested by others, if your original input are not in range (0,255), you will need to rescale them as well.

🌐
YouTube
youtube.com › watch
Create a RGB 565 image from python array - YouTube
Download this code from https://codegive.com Creating an RGB 565 image from a Python array involves converting the RGB values of each pixel in the array into...
Published: November 29, 2023
🌐
Medium
celik-muhammed.medium.com › how-to-create-rgb-image-in-python-programing-language-from-jupyter-notebook-4a78db8205d7
How to Generate RGB Image in Python Programing Language from Jupyter Notebook | by Muhammed ÇELİK | Medium
October 19, 2022 - 5. step-5: We show RGB Image from array with Matplotlib. 1–Defining RGB Color Model[¹] 2–Defining Image[²] 3–Defining ‘uint8’[³] 4–Defining Python Programing Language[⁴] 5–Defining Jupyter Notebook[⁵]
🌐
CodeSpeedy
codespeedy.com › home › how to convert an rgb image to a numpy array
How to convert an RGB image to a NumPy array - CodeSpeedy
August 5, 2022 - In image processing, all colored images use the RGB model. RGB(Red, Green, Blue) model is additive of all three colors to produce an extensive spectrum of colors. The value of each color component ranges from 0-255 pixels (a total of 256 shades of colors). We will be using NumPy and Pillow library in Python for this tutorial. NumPy is a library for Python language used to work with 2D and 3D arrays ...
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert a python numpy array to an rgb image
5 Best Ways to Convert a Python NumPy Array to an RGB Image - Be on the Right Side of Change
February 20, 2024 - This snippet first generates a random RGB image as a NumPy array and then uses Matplotlib’s capabilities to display the image on the screen. Finally, it saves the generated image as a PNG file. This method is great for quick visualization and saving, but it requires having the Matplotlib library installed and doesn’t support more advanced image manipulation tasks. The Python Imaging Library (Pillow) is a versatile library designed specifically for opening, manipulating, and saving many different image file formats.
Top answer
1 of 2
1

I think this is solved here, remember if you want a RGB image you need 3 channels and that means a matrix with shape (NxMx3).

Convert 2d array to collored image in python

Cheers!

Edit:

This is an example of how you can stack your 2D arrays into a 3D one with the shape you need.

import numpy as np
#some random arrays i just created for test
r = np.array([3,3,3])
g = np.array([6,6,6])
b = np.array([9,9,9])
bl = np.array([12,12,12])

#create the stacked arrays
stacked = np.dstack((r,g,b,bl))

#check the shape
print(np.shape(stacked))
2 of 2
0

To make RGB images from ndarrays you have to: 1) separate each RGB channel as a different array by methods such as splitting maximum and minimum intensities into group of 3, normalize them (turning them into a range between 0-1) based on original or RGB minimums/maximums to represent pixel color intensity, then display/save them using plt.imshow/plt.imsave:

from  matplotlib.colors import Normalize
from PIL import Image
import numpy as np

# example data
arr = np.array([4,3,2,1,-1,-2,-3,-4])

# producing RGB variants by slicing intensity of the data into 3 equal sections
R = np.percentile(arr,100 - 100/3)
B = np.percentile(arr,100/3)
arr_R = np.where(arr >= R, arr, 0)
arr_B = np.where(arr <= B, arr, 0)
arr_G = np.where((arr > B) & (arr < R), arr, 0)

# normalizing arr_RGB to have values between 0-255
def normRGB(a):
    mynorm = Normalize(vmin=np.min(a), vmax=np.max(a))
    return mynorm(a)

# #Run below if you prefer original array's minimum and maximum
# arr = normRGB(abs(arr))  # absolute values help acknowledging negative values' intensity, exclude them if you mean otherwise
# # otherwise run below if you prefer RGB channels' minimums and maximums
arr_R = normRGB(abs(arr_R)) # absolute values help acknowledging negative values' intensity, exclude them if you mean otherwise
arr_G = normRGB(abs(arr_G))
arr_B = normRGB(abs(arr_B))

# stacking RGB into one ndarray
arr_RGB = np.dstack((arr_R,arr_G,arr_B))
plt.imshow(arr_RGB)
plt.show()
print(arr_RGB)

Stacking resulted images into a higher dimension array (like an album book) is also possible by adding arr_RGB's together using the same np.dstack() function. for example:

N = 22 # if there are 22 images
album = np.zeros((N))
for n in range(N):
    
    ### Here should be written all above operation with an i index that updates new arr_RGB from dataset[i] during each iteration ###
    
    if n == 0: # if it is the first iteration
        album = np.copy(arr_RGB)
    elif n > 0: # now that album has been created, it can be stacked on its previous records
    album = np.dstack(album, arr_RGB)
print(np.shape(album))

Thanks to @jairoar answer upon explaining np.dstack