![]() |
|
[Tut] Python Convert Image (JPG, PNG) to CSV - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Convert Image (JPG, PNG) to CSV (/thread-99929.html) |
[Tut] Python Convert Image (JPG, PNG) to CSV - xSicKxBot - 09-10-2022 Python Convert Image (JPG, PNG) to CSV 5/5 – (1 vote) Given an image as a Code: .pngCode: .jpegExample image: ![]() Convert the image to a CSV using the following steps:
Here’s the code that applies these four steps, assuming the image is stored in a file named Code: 'c++.jpg'Code: 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, Code: [255 255 255]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]
|