Created
July 14, 2020 20:41
-
-
Save HaxxonHax/79ffeb64abe72efb4f8397aebc1cf1e3 to your computer and use it in GitHub Desktop.
Converts pixels of an image to a csv of each pixel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" Converts an image to a csv of pixel values. """ | |
# be sure to "pip3 install pillow" before running | |
import sys | |
from PIL import Image, UnidentifiedImageError | |
E_FILENOTFOUND = 1 | |
E_PERMISSIONS = 2 | |
E_FILETYPE = 3 | |
def get_int_from_rgb(rgb): | |
""" Gets the integer from an RGB tuple. """ | |
red = rgb[0] | |
green = rgb[1] | |
blue = rgb[2] | |
rgb_int = (red<<16) + (green<<8) + blue | |
return rgb_int | |
def main(): | |
""" The main program where everything happens. """ | |
img_filepath = input('Enter the filename/path to the image: ') | |
try: | |
img_src = Image.open(img_filepath) #path to file | |
#load the pixel info | |
pix = img_src.load() | |
img_src.close() | |
except FileNotFoundError: | |
print('ERROR: invalid image file (not found).') | |
sys.exit(E_FILENOTFOUND) | |
except PermissionError: | |
print('ERROR: invalid image file (cannot open).') | |
sys.exit(E_PERMISSIONS) | |
except UnidentifiedImageError: | |
print(f'ERROR: {img_filepath} is not an image file (bad filetype).') | |
sys.exit(E_FILETYPE) | |
#get a tuple of the x and y dimensions of the image | |
width, height = img_src.size | |
print(f'Found file {img_filepath} with size {width} x {height}.') | |
#open a file to write the pixel data | |
csv_file = input('Enter the filename/path where you want the csv file: ') | |
try: | |
fileds = open(csv_file, 'w+') | |
except PermissionError: | |
print('ERROR: invalid csv file (no permission to write).') | |
sys.exit(E_PERMISSIONS) | |
#read the details of each pixel and write them to the file | |
for yval in range(height): | |
for xval in range(width): | |
rval = pix[xval, yval][0] | |
gval = pix[xval, yval][1] | |
bval = pix[xval, yval][2] | |
color_int = get_int_from_rgb((rval, gval, bval)) | |
#f.write('{0},{1},{2}\n'.format(r,g,b)) | |
fileds.write('{0},'.format(str(color_int))) | |
fileds.write('\n') | |
# Always close the file when done. | |
fileds.close() | |
print(f'Wrote output to file {csv_file} with {height} rows and {width} columns.') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment