Reputation: 428
I have an Excel file, with 100 rows and 100 columns. Each element is a pixel intensity value. How can I convert it into a 2D grayscale image using Python?
Upvotes: 2
Views: 1767
Reputation: 46779
If you have an Excel .xlsx
file you could use openpyxl to read in the values. The Pillow library can be used to build and save the image.
Assuming each value is an 8-bit value, the following approach could be used:
from itertools import chain
from PIL import Image
import openpyxl
wb = openpyxl.load_workbook("image.xlsx")
ws = wb.active
data = list(ws.iter_rows(values_only=True))
rows = len(data)
cols = max(len(row) for row in data)
img = Image.new('L', (cols, rows), color='black')
img.putdata(list(chain.from_iterable(data)))
img.save('output.png')
So for an Excel file containing these values:
You would get a PNG image looking like (enlarged):
If your file is actually in CSV format:
from itertools import chain
from PIL import Image
import csv
data = []
with open('image.csv', newline='') as f_input:
for row in csv.reader(f_input):
data.append(list(map(int, row)))
rows = len(data)
cols = max(len(row) for row in data)
img = Image.new('L', (cols, rows), color='black')
img.putdata(list(chain.from_iterable(data)))
img.save('output.png')
e.g. image.csv
contains:
24,1,4,255,43,2
2,4,6,0,3,2
1,1,255,3,32,5
Upvotes: 3