Skip to content

Instantly share code, notes, and snippets.

@4piu
Created March 6, 2024 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4piu/a75daf790acda983d6c42122d67aa4a4 to your computer and use it in GitHub Desktop.
Save 4piu/a75daf790acda983d6c42122d67aa4a4 to your computer and use it in GitHub Desktop.
Convert grayscale bitmap image to a csv where each cell is 0-255
#!/usr/bin/env python3
from PIL import Image
import csv
def convert_image_to_csv(image_path, csv_path):
# Open the image
with Image.open(image_path) as img:
# Convert image to grayscale (if it's not already)
img = img.convert('L')
width, height = img.size
# Load the image pixels
pixels = list(img.getdata())
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
# Write to CSV
with open(csv_path, mode='w', newline='') as file:
writer = csv.writer(file)
for row in pixels:
writer.writerow(row)
if __name__ == '__main__':
convert_image_to_csv(argv[1], argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment