How to Convert an Image to a NumPy Array and Save it to a CSV file using Python?

Python is a powerful programming language with a vast array of libraries and modules. One such library is NumPy, which is used for numerical computing and processing large multidimensional arrays and matrices. Another popular library used for image processing in Python is Pillow, which is a fork of the Python Imaging Library (PIL).

In this tutorial, we will show you how to convert an image to a NumPy array and save it to a CSV file using Python. We will be using the Pillow library to open the image and convert it to a NumPy array, and NumPy's built-in functions to save the array to a CSV file.

Required Libraries

Before we dive into the process of converting an image to a NumPy array and saving it to a CSV file, let's first understand the two libraries we'll be using in this tutorial:

Pillow is a Python Imaging Library (PIL) that adds support for opening, manipulating, and saving many different image file formats.

NumPy is a fundamental library for scientific computing in Python. It provides support for large multidimensional arrays and matrices, along with a range of mathematical functions to operate on them.

To install these libraries, use the following commands ?

pip install Pillow numpy

Converting Image to NumPy Array

Here's a complete example that converts an image to a NumPy array and saves it to a CSV file ?

from PIL import Image
import numpy as np

# Create a sample image (3x3 RGB for demonstration)
sample_array = np.array([
    [[255, 0, 0], [0, 255, 0], [0, 0, 255]],
    [[128, 128, 0], [255, 255, 255], [0, 0, 0]],
    [[64, 192, 128], [200, 100, 50], [75, 150, 225]]
], dtype=np.uint8)

# Create PIL Image from array
img = Image.fromarray(sample_array)

# Convert image to NumPy array
np_array = np.array(img)

# Print the shape of the NumPy array
print("Shape of NumPy array:", np_array.shape)
print("Data type:", np_array.dtype)
Shape of NumPy array: (3, 3, 3)
Data type: uint8

Saving NumPy Array to CSV File

For a color image with multiple channels, we need to reshape the array before saving to CSV ?

from PIL import Image
import numpy as np

# Create a sample grayscale image (easier for CSV demonstration)
gray_array = np.array([
    [255, 128, 64],
    [192, 96, 32],
    [224, 160, 80]
], dtype=np.uint8)

# Create PIL Image from array
img = Image.fromarray(gray_array, mode='L')  # 'L' for grayscale

# Convert back to NumPy array
np_array = np.array(img)

# Save NumPy array to CSV file
np.savetxt('image_output.csv', np_array, delimiter=',', fmt='%d')

print("Grayscale image shape:", np_array.shape)
print("CSV file 'image_output.csv' created successfully!")

# Display the array content
print("Array content:")
print(np_array)
Grayscale image shape: (3, 3)
CSV file 'image_output.csv' created successfully!
Array content:
[[255 128  64]
 [192  96  32]
 [224 160  80]]

Handling Color Images

For color images (RGB), you need to reshape the 3D array into 2D format before saving to CSV ?

from PIL import Image
import numpy as np

# Create a sample RGB image
rgb_array = np.array([
    [[255, 0, 0], [0, 255, 0]],
    [[0, 0, 255], [255, 255, 0]]
], dtype=np.uint8)

# Convert to PIL Image
img = Image.fromarray(rgb_array)
np_array = np.array(img)

print("Original RGB shape:", np_array.shape)

# Method 1: Flatten the entire array
flattened = np_array.flatten()
np.savetxt('rgb_flattened.csv', flattened.reshape(1, -1), delimiter=',', fmt='%d')

# Method 2: Reshape to 2D (height*width, channels)
reshaped = np_array.reshape(-1, np_array.shape[-1])
np.savetxt('rgb_reshaped.csv', reshaped, delimiter=',', fmt='%d')

print("Flattened shape:", flattened.shape)
print("Reshaped to 2D:", reshaped.shape)
print("Files saved successfully!")
Original RGB shape: (2, 2, 3)
Flattened shape: (12,)
Reshaped to 2D: (4, 3)
Files saved successfully!

Key Points

Image.open() loads an image file into a PIL Image object

np.array() converts PIL Image to NumPy array

Grayscale images have shape (height, width)

Color images have shape (height, width, channels)

Use np.savetxt() to save arrays to CSV format

Reshape 3D color arrays before saving to CSV

Comparison of Array Formats

Image Type Array Shape CSV Approach
Grayscale (height, width) Direct save
RGB Color (height, width, 3) Reshape or flatten
RGBA Color (height, width, 4) Reshape or flatten

Conclusion

Converting images to NumPy arrays enables powerful numerical operations and analysis. Use np.array(Image.open()) for conversion and np.savetxt() for CSV export. Remember to reshape multi-dimensional color arrays before saving to CSV format.

---
Updated on: 2026-03-27T09:16:08+05:30

979 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements