Given an image as a .png
or .jpeg
file. How to convert it to a CSV file in Python?
Example image:

Convert the image to a CSV using the following steps:
- Read the image into a
PIL.Image
object. - Convert the
PIL.Image
object to a 3D NumPy array with the dimensions rows, columns, and RGB values. - Convert the 3D NumPy array to a 2D list of lists by collapsing the RGB values into a single value (e.g., a string representation).
- Write the 2D list of lists to a CSV using normal file I/O in Python.
Here’s the code that applies these four steps, assuming the image is stored in a file named 'c++.jpg'
:
from PIL import Image import numpy as np # 1. Read image img = Image.open('c++.jpg') # 2. Convert image to NumPy array arr = np.asarray(img) print(arr.shape) # (771, 771, 3) # 3. Convert 3D array to 2D list of lists lst = [] for row in arr: tmp = [] for col in row: tmp.append(str(col)) lst.append(tmp) # 4. Save list of lists to CSV with open('my_file.csv', 'w') as f: for row in lst: f.write(','.join(row) + '\n')
Note that the resulting CSV file looks like this with super long rows.

Each CSV cell (column) value is a representation of the RGB value at that specific pixel. For example, [255 255 255]
represents the color white at that pixel.
For more information and some background on file I/O, check out our detailed tutorial on converting a list of lists to a CSV:
🌍 Related Tutorial: How to Convert a List to a CSV File in Python [5 Ways]

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.