I had to write this recently and ended up with

indices = np.dstack(np.indices(im.shape[:2]))
data = np.concatenate((im, indices), axis=-1)

Where im is a numpy array. You are probably better off reading the images straight into numpy arrays with

from scipy.misc import imread
im = imread("farm.jpg")

Or, better still if you have Scikit Image installed

from skimage.io import imread
im = imread("farm.jpg")
Answer from YXD on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › converting between pil image and 2d pixel array?
r/learnpython on Reddit: Converting between PIL Image and 2d pixel array?
May 11, 2022 -

I need to do the following:

  1. Import an image.

  2. Convert image to a 2D array of pixel values (rgb tuples, bytes, whatever it doesn't matter).

  3. Manipulate that 2D array (needs to be 2D as I'm using a library that requires a 2D array of data).

  4. Convert the newly changed 2D array back into an image.

  5. Save the image.

Anyone know how I can accomplish this? PIL Image documentation has some functions to get data but it's all 1D arrays, and I'm not sure how to get them into 2D arrays and then re-convert it back into an image again.

Discussions

How can I convert an array of images to a 2D array in Python - Stack Overflow
I have a numpy array of images in that shape: (50000, 32, 32, 3) 50000 is the number of images 32, 32 are the height and width 3 are the RGB values with a range of 0-1 I would like to convert it t... More on stackoverflow.com
🌐 stackoverflow.com
Convert a binary image to 2D array or Matrix in Python? - Stack Overflow
I'm new to image processing and I'm really having a hard time understanding stuff...so the idea is that how do you create a matrix from a binary image in python? to something like this: It not the ... More on stackoverflow.com
🌐 stackoverflow.com
February 8, 2021
python - Converting a PNG image to 2D array - Stack Overflow
I have a PNG file which when I convert the image to a numpy array, it is of the format that is 184 x 184 x 4. The image is 184 by 184 and each pixel is in RGBA format and hence the 3D array. This ... More on stackoverflow.com
🌐 stackoverflow.com
September 13, 2016
python - Converting 2D Numpy array of grayscale values to a PIL image - Stack Overflow
Say I have a 2D Numpy array of values on the range 0 to 1, which represents a grayscale image. How do I then convert this into a PIL Image object? All attempts so far have yielded extremely strange More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › How-do-I-convert-an-image-into-2D-array-using-structures-in-Python
How to convert an image into 2D array using structures in Python - Quora
Answer (1 of 3): You need not to convert any image in 2-d array as most of the image processing libraries stores images as a 2-d array . If you read an image in color form , It will use 3 2-d arrays to store image ,1 array for each channel B,G,R seprately , but if you read image in greyScale it ...
🌐
scikit-image
scikit-image.org › skimage-tutorials › lectures › 00_images_are_arrays.html
Images are numpy arrays — Image analysis in Python
Images are represented in scikit-image using standard numpy arrays. This allows maximum inter-operability with other libraries in the scientific Python ecosystem, such as matplotlib and scipy. Let’s see how to build a grayscale image as a 2D array:
Top answer
1 of 2
2

Using cv2 -Read more here

import cv2
img = cv2.imread('path/to/img.jpg')
resized = cv2.resize(img, (128, 128), cv2.INTER_LINEAR)
print pic

Using skimage - Read more here

import skimage.io as skio
faces = skio.imread_collection('path/to/images/*.pgm',conserve_memory=True) # can load multiple images at once

Using Scipy - Read more here

from scipy import misc
pic = misc.imread('path/to/img.jpg')
print pic

Plotting Images

import matplotlib.pyplot as plt
plt.imshow(faces[0],cmap=plt.cm.gray_r,interpolation="nearest")
plt.show()
2 of 2
1

example I am currently working with.

"""
A set of utilities that are helpful for working with images. These are utilities
needed to actually apply the seam carving algorithm to images
"""


from PIL import Image


class Color:
    """
    A simple class representing an RGB value.
    """

    def __init__(self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

    def __repr__(self):
        return f'Color({self.r}, {self.g}, {self.b})'

    def __str__(self):
        return repr(self)


def read_image_into_array(filename):
    """
    Read the given image into a 2D array of pixels. The result is an array,
    where each element represents a row. Each row is an array, where each
    element is a color.

    See: Color
    """

    img = Image.open(filename, 'r')
    w, h = img.size

    pixels = list(Color(*pixel) for pixel in img.getdata())
    return [pixels[n:(n + w)] for n in range(0, w * h, w)]


def write_array_into_image(pixels, filename):
    """
    Write the given 2D array of pixels into an image with the given filename.
    The input pixels are represented as an array, where each element is a row.
    Each row is an array, where each element is a color.

    See: Color
    """

    h = len(pixels)
    w = len(pixels[0])

    img = Image.new('RGB', (w, h))

    output_pixels = img.load()
    for y, row in enumerate(pixels):
        for x, color in enumerate(row):
            output_pixels[x, y] = (color.r, color.g, color.b)

    img.save(filename)
🌐
YouTube
youtube.com › it guys
How to convert images to NumPy arrays - 20 - YouTube
Hello everyone! Today is the last video of the NumPy series! In this video we will learn how to convert images in NumPy arrays!This is really useful as you w...
Published: August 3, 2020
Views: 20K
Find elsewhere
🌐
Quora
quora.com › How-do-I-convert-image-data-from-1D-array-to-2D-in-Python
How to convert image data from 1D array to 2D in Python - Quora
Answer (1 of 2): This should give you the idea: [code]import matplotlib import numpy maxcolorrange = ? l=[] for row in array: rl=[] for i in range(1024): pixel = [row[i]/maxcolorrange, row[i+1024]/maxcolorrange, row[i+2048]/maxcolorrange] rl.append(pixel) l.appe...
🌐
Quora
quora.com › How-do-I-convert-image-data-from-2D-array-to-1D-using-python
How to convert image data from 2D array to 1D using python - Quora
Answer (1 of 5): Assuming your image is a numpy/cv2/PIL image. numpy.ndarray.flatten - NumPy v1.11 Manual Otherwise just cast it.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-images-to-numpy-array
How to Convert images to NumPy array? - GeeksforGeeks
September 30, 2022 - Python provides many modules and API's for converting an image into a NumPy array.
Top answer
1 of 2
1

If your objective is to save a numpy array as an image, your approach have a problem. The function plt.savefig saves an image of the plot, not the array. Also transforming an array into an image may carry some precision loss (when converting from float64 or float32 to uint16). That been said, I suggest you use skimage and imageio:

import imageio
import numpy as np

from skimage import img_as_uint

data = np.load('0058_00086_brown_2_recording1.wav.npy')
print("original", data.shape)

img = img_as_uint(data)
imageio.imwrite('image.png', img)
load = imageio.imread('image.png')

print("image", load.shape)

This script loads the data you provided and prints the shape for verification

data = np.load('0058_00086_brown_2_recording1.wav.npy')
print("original", data.shape)

then it transform the data to uint, saves the image as png and loads it:

img = img_as_uint(data)
imageio.imwrite('image.png', img)
load = imageio.imread('image.png')

the output of the script is:

original (64, 25)
image (64, 25)

i.e. the image is loaded with the same shape that data. Some notes:

  • image.png is saved as a grayscale image
  • To save to .jpg just change to imageio.imwrite('image.jpg', img)
  • In the case of .png the absolute average distance from the original image was 3.890e-06 (this can be verified using np.abs(img_as_float(load) - data).sum() / data.size)

Information about skimage and imageio can be found in the respectives websites. More on saving numpy arrays as images can be found in the following answers: [1], [2], [3] and [4].

2 of 2
1

link

 from scipy.misc import imread
 image_data = imread('test.jpg').astype(np.float32)

This should give you the numpy array (I would suggest using imread from scipy)

🌐
Pythoninformer
pythoninformer.com › python-libraries › numpy › numpy-and-images
PythonInformer - Image processing with pillow and NumPy
October 2, 2022 - import numpy as np from PIL import Image img = Image.open('testgrey.png') array = np.array(img) array = 255 - array invimg = Image.fromarray(array) invimg.save('testgrey-inverted.png') This is a very simple example of image processing. See the links at the start of this article for other image processing techniques using NumPy. ... Sign up using this form to receive an email when new content is added to the graphpicmaths or pythoninformer websites: 2d arrays abstract data type and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable o
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "python numpy howtos" › "how to convert 3d array to 2d array in python"
How to Convert 3D Array to 2D Array in Python | Delft Stack
March 11, 2025 - Converting a 3D array to a 2D array in Python is a common task that many data scientists and programmers encounter. Whether you’re working with image data, scientific simulations, or any multi-dimensional dataset, reshaping your data can be essential for analysis and visualization.
🌐
Quora
quora.com › How-can-an-image-be-converted-into-a-two-dimensional-array-of-numbers
How can an image be converted into a two dimensional array of numbers? - Quora
Answer (1 of 2): It is easy. The position of the number in the array is the physical position of every pixel in the image (typically, but not the only assignemet, the 0,0 position is for pixel in the upper-left corner). The value assigned to every position in the array will be the level of signa...
Top answer
1 of 3
54

You need to use np.transpose to rearrange dimensions. Now, n x m x 3 is to be converted to 3 x (n*m), so send the last axis to the front and shift right the order of the remaining axes (0,1). Finally , reshape to have 3 rows. Thus, the implementation would be -

img.transpose(2,0,1).reshape(3,-1)

Sample run -

In [16]: img
Out[16]: 
array([[[155,  33, 129],
        [161, 218,   6]],

       [[215, 142, 235],
        [143, 249, 164]],

       [[221,  71, 229],
        [ 56,  91, 120]],

       [[236,   4, 177],
        [171, 105,  40]]])

In [17]: img.transpose(2,0,1).reshape(3,-1)
Out[17]: 
array([[155, 161, 215, 143, 221,  56, 236, 171],
       [ 33, 218, 142, 249,  71,  91,   4, 105],
       [129,   6, 235, 164, 229, 120, 177,  40]])
2 of 3
5

[ORIGINAL ANSWER]

Let's say we have an array img of size m x n x 3 to transform into an array new_img of size 3 x (m*n)

Initial Solution:

new_img = img.reshape((img.shape[0]*img.shape[1]), img.shape[2])
new_img = new_img.transpose()

[EDITED ANSWER]

Flaw: The reshape starts from the first dimension and reshapes the remainder, this solution has the potential to mix the values from the third dimension. Which in the case of images could be semantically incorrect.

Adapted Solution:

# Dimensions: [m, n, 3]
new_img = new_img.transpose()
# Dimensions: [3, n, m]
new_img = img.reshape(img.shape[0], (img.shape[1]*img.shape[2]))

Strict Solution:

# Dimensions: [m, n, 3]
new_img = new_img.transpose((2, 0, 1))
# Dimensions: [3, m, n]
new_img = img.reshape(img.shape[0], (img.shape[1]*img.shape[2]))

The strict is a better way forward to account for the order of dimensions, while the results from the Adapted and Strict will be identical in terms of the values (set(new_img[0,...])), however with the order shuffled.