You can use newer OpenCV python interface (if I'm not mistaken it is available since OpenCV 2.2). It natively uses numpy arrays:

import cv2
im = cv2.imread("abc.tiff")
print(type(im))

result:

<type 'numpy.ndarray'>
Answer from Andrey Kamaev on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-images-to-numpy-array
How to Convert images to NumPy array? - GeeksforGeeks
July 15, 2025 - from PIL import Image import numpy as np img = Image.open("Sample.png") # Load image a = np.array(img) print(a.shape) ... Explanation: It loads 'Sample.png' using Image.open() and converts it to a NumPy array using np.array(). The resulting array has a shape of (200, 400, 3), indicating a color image with height 200, width 400 and 3 color channels (RGB). Example 3: Here we display the actual pixel data from the image in NumPy array format. ... from PIL import Image from numpy import asarray img = Image.open('Sample.png') res = asarray(img) print(res)
🌐
AskPython
askpython.com › python › examples › convert-images-to-numpy-arrays
How to Convert Images to Numpy Arrays in Python - AskPython
April 21, 2026 - Pillow is the go-to library for basic image loading in Python. Pair it with numpy.asarray() and you get an array without installing anything heavy. from PIL import Image import numpy as np img = Image.open('sample.png') arr = np.asarray(img) print(type(arr)) print(arr.dtype) print(arr.shape)
Discussions

python - How do I convert a numpy array to (and display) an image? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Turn scattered docs and code into trusted AI context. Explore the new Stack Internal platform More on stackoverflow.com
🌐 stackoverflow.com
python - numpy.array vs img_to_array - Stack Overflow
Further, it would ensure that the ... input img is a 2D array which might represent a grayscale image, then it would add another axis with dimension 1 to make it a 3D array). Note that although in the docstring it has been mentioned that the input image is a PIL image instance, however it would also work with the numpy arrays or even Python lists (since the input is first converted to a numpy array: x = np.asarray(img, ... More on stackoverflow.com
🌐 stackoverflow.com
np.asarray for PIL.Image with dtype throw error in python 3.8.10
This works in python 3.8.5, but not works in python 3.8.10 Otherwise, np.asarray for np.array is works fine both 3.8.5 and 3.8.10 More on github.com
🌐 github.com
5
July 1, 2021
python - Create Numpy array of images - Stack Overflow
You could test with enforcing the ... 1).astype(np.uint8), however I don't quite believe in it 2016-06-10T12:15:35.577Z+00:00 ... You can add an assert statement in the loop that will raise AssertionError if any of the images have a different shape: assert image.shape == (150,150,3), "img %s has shape ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
Image processing with Python, NumPy | note.nkmk.me
October 20, 2020 - You can also get ndarray from PIL.Image with np.asarray().
🌐
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:
🌐
Matplotlib
matplotlib.org › stable › tutorials › images.html
Image tutorial — Matplotlib 3.11.2 documentation
img = np.asarray(Image.open('../../doc/_static/stinkbug.png')) print(repr(img))
Find elsewhere
🌐
Guiwitz
guiwitz.github.io › PyImageCourse_beginner › 02-Images_as_arrays.html
2. Images as arrays — Image processing with Python for beginners
There are many different types of arrays that we can create. For example we can create arrays that only contain 0s or 1s and have a certain shape, e.g. 5 rows and 3 columns, using the np.zeros() and np.ones() functions:
Top answer
1 of 2
7

Well, you can easily find out the answer by looking at the source code of img_to_array:

def img_to_array(img, data_format='channels_last', dtype='float32'):
    """Converts a PIL Image instance to a Numpy array.
    # Arguments
        img: PIL Image instance.
        data_format: Image data format,
            either "channels_first" or "channels_last".
        dtype: Dtype to use for the returned array.
    # Returns
        A 3D Numpy array.
    # Raises
        ValueError: if invalid `img` or `data_format` is passed.
    """
    if data_format not in {'channels_first', 'channels_last'}:
        raise ValueError('Unknown data_format: %s' % data_format)
    # Numpy array x has format (height, width, channel)
    # or (channel, height, width)
    # but original PIL image has format (width, height, channel)
    x = np.asarray(img, dtype=dtype)
    if len(x.shape) == 3:
        if data_format == 'channels_first':
            x = x.transpose(2, 0, 1)
    elif len(x.shape) == 2:
        if data_format == 'channels_first':
            x = x.reshape((1, x.shape[0], x.shape[1]))
        else:
            x = x.reshape((x.shape[0], x.shape[1], 1))
    else:
        raise ValueError('Unsupported image shape: %s' % (x.shape,))
    return x

So the main difference is that you can pass a data format argument to img_to_array to put the channels either at the first axis or the last axis. Further, it would ensure that the returned array is a 3D array (for example, if the given input img is a 2D array which might represent a grayscale image, then it would add another axis with dimension 1 to make it a 3D array).

Note that although in the docstring it has been mentioned that the input image is a PIL image instance, however it would also work with the numpy arrays or even Python lists (since the input is first converted to a numpy array: x = np.asarray(img, dtype=dtype)).

2 of 2
1

As far as I can see on some examples, img_to_array() is a method of an image Class. The Class does not represent an array, but something more abstract, but an image is inherently an array. That might be why you would have a similar result with numpy.array(image).

Note that as methods have more information (call it 'context'), they should be more efficient and reliable. For instance, opencv2 is manipulating BGR images when it comes to representation, and not RGB. It can be confusing at first, but using the proper cv2 library, you don't even have to really think about it (depending of what you intend to do).

🌐
DataCamp
datacamp.com › doc › numpy › converting-images-to-numpy
Converting Images to NumPy
from PIL import Image import numpy as np image = Image.open('example.jpg') image_array = np.array(image) print(image_array.shape)
🌐
Pluralsight
pluralsight.com › blog › tech guides & tutorials
Importing Image Data Into NumPy Arrays | Pluralsight
April 15, 2025 - Keras uses the img_to_array function to convert the PIL image into numpy.
🌐
Educative
educative.io › answers › convert-a-pil-image-to-numpy-array
Convert a PIL image to NumPy array
On the other hand, np.asarray() reflects all changes made to the original array in place. However, since the input is an image here and not an array, both methods will act the same way. from PIL import Image import numpy as np img = ...
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "python numpy howtos" › "how to save numpy array as image in python"
How to Save NumPy Array as Image in Python | Delft Stack
February 2, 2024 - import imageio import numpy as np image_data = np.array([ [0, 128, 255], [64, 192, 32], [100, 50, 150] ], dtype=np.uint8) imageio.imwrite("output.png", image_data)
🌐
Medium
medium.com › @whyamit101 › step-by-step-guide-to-convert-numpy-array-to-pil-image-f7f8492cd785
Step-by-Step Guide to Convert NumPy Array to PIL Image | by why amit | Medium
February 9, 2025 - numpy_array = np.array(img) print(numpy_array.shape) # Check the shape of the converted array · This ensures you can seamlessly switch between NumPy and PIL whenever needed. Pro tip: Always verify the array’s shape after conversion — it’s your safety net.
🌐
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 the PIL library from PIL import Image # Importing the NumPy library and aliasing it as 'np' import numpy as np # Defining image width and height img_w, img_h = 200, 200 # Creating a NumPy array 'data' filled with zeros of shape (img_h, img_w, 3) representing RGB channels data = np.zeros((img_h, img_w, 3), dtype=np.uint8) # Setting a specific pixel (100, 100) in the 'data' array to the color red [255, 0, 0] data[100, 100] = [255, 0, 0] # Creating 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 the image img.show()
🌐
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('testrgba.png') array = np.array(img) print(array.shape) # (100, 200, 4) img = Image.open('testrgb.png') array = np.array(img) print(array.shape) # (100, 200, 3) img = Image.open('testgrey.png') array = np.array(img) print(array.shape) # (100, 200)
🌐
GitHub
github.com › numpy › numpy › issues › 19386
np.asarray for PIL.Image with dtype throw error in python 3.8.10 · Issue #19386 · numpy/numpy
July 1, 2021 - np.asarray for PIL.Image with dtype throw error in python 3.8.10#19386 · Copy link · outtoin · opened · on Jul 1, 2021 · Issue body actions · import numpy as np from PIL import Image arr = np.random.randint(255, size=(100, 100, 3), dtype=np.uint8) img = Image.fromarray(arr) np.asarray(img, dtype=np.uint8) This works in python 3.8.5, but not works in python 3.8.10 Otherwise, np.asarray for np.array is works fine both 3.8.5 and 3.8.10 ·
Author: numpy
🌐
Java2Blog
java2blog.com › save-numpy-array-as-image-python
Save Numpy Array as Image in Python – Java2Blog
import numpy as np from PIL import Image a = np.arange(0, 414720, 1, np.uint8) a = np.reshape(a, (720, 576)) i = Image.fromarray(a) i.save("image.png")
Top answer
1 of 4
25

I tested your code. It works fine for me with output

('X_data shape:', (4, 617, 1021, 3))

however, all images were exactly the same dimension.

When I add another image with different extents I have this output:

('X_data shape:', (5,))

So I'd recommend checking the sizes and the same number of channels (as in are really all images coloured images)? Also you should check if either all images (or none) have alpha channels (see @Gughan Ravikumar's comment)

If only the number of channels vary (i.e. some images are grey), then force loading all into the color format with:

image = cv2.imread (myFile, cv2.IMREAD_COLOR)

EDIT: I used the very code from the question, only replaced with a directory of mine (and "*.PNG"):

import cv2
import glob
import numpy as np

X_data = []
files = glob.glob ("C:/Users/xxx/Desktop/asdf/*.PNG")
for myFile in files:
    print(myFile)
    image = cv2.imread (myFile)
    X_data.append (image)

print('X_data shape:', np.array(X_data).shape)
2 of 4
6

Appending images in a list and then converting it into a numpy array, is not working for me. I have a large dataset and RAM gets crashed every time I attempt it. Rather I append the numpy array, but this has its own cons. Appending into list and then converting into np array is space complex, but appending a numpy array is time complex. If you are patient enough, this will take care of RAM crasing problems.

def imagetensor(imagedir):
  for i, im in tqdm(enumerate(os.listdir(imagedir))):
    image= Image.open(im)
    image= image.convert('HSV')
    if i == 0:
      images= np.expand_dims(np.array(image, dtype= float)/255, axis= 0)
    else:
      image= np.expand_dims(np.array(image, dtype= float)/255, axis= 0)
      images= np.append(images, image, axis= 0)
  return images

I am looking for better implementations that can take care of both space and time. Please comment if someone has a better idea.

🌐
Reddit
reddit.com › r/learnpython › [np and pil] how do you load images as array and then reshape back to view the image
r/learnpython on Reddit: [np and PIL] how do you load images as array and then reshape back to view the image
September 11, 2022 -
arr = np.zeros((20,5000))
for idx,file in enumerate(images):
    file_to_open = folder / file
    print(file_to_open)
    img = Image.open(file_to_open)
    img = img.reduce(4)
    print(img.size)
    arr[idx]=np.asarray(img).reshape((1,5000))

I have 19 images of 80 W x 61 H ( grayscale)I just want to stack 20x 5000 for machine learning.

examplebut problem occurs when I wanted to display only 1 image after the combine and I wasn't able to re-construct the image array to display the it as gif using the code below

Image.fromarray(arr[0].reshape((50,100),'L')

I think it didn't reshape properly..
Apologies if it's not entirely Python.

anyone familiar with PIL and reshape? Thanks