Created
October 5, 2016 22:17
-
-
Save mathandy/ce511b40d2fb45e1e8469173343bc908 to your computer and use it in GitHub Desktop.
Converts a color image to a matrix and 3-tensor and stores them as CSV files (by default scales image to thumbnail-size).
This file contains 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
""" | |
Description: | |
Takes in a color image and creates a two CSV files storing downsized | |
matrix (grayscale) and 3-tensor representations of the image. | |
Instructions: | |
Put your image in the same folder as this file (tool4c.py), | |
then open a terminal in that folder and enter: | |
python tool4c <your_image> | |
Examples: | |
python tool4c.py test.jpg | |
# Use quotes if your image's filename contains spaces | |
python tool4c.py "my luxuriously named image.jpg" | |
# To change output image size, use the -d flag, | |
# e.g. for a max dimension of 32 | |
python tool4c.py test.jpg -d 32 | |
# If you want to see the array in the terminal, use the -o flag | |
python tool4c.py test.jpg -o | |
Troubleshooting Note: | |
If you get an error, it's probably cause you don't have Pillow | |
or numpy installed... this is easy to fix, in the terminal enter: | |
pip install numpy | |
pip install Pillow | |
""" | |
from PIL import Image | |
import numpy as np | |
import csvio | |
import os, argparse | |
def get_user_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'input_image', | |
default="test.jpg", | |
help='Example: python tool4c.py "test.jpg"', | |
) | |
parser.add_argument( | |
'-o','--console_output_on', | |
action='store_true', | |
default=False, | |
help='Use this flag to see arrays output in the terminal.', | |
) | |
parser.add_argument( | |
'-d','--max_dim', | |
default=16, | |
help='Use this to change the output array size (max dimension).', | |
) | |
return parser.parse_args() | |
def arr2csv(arr, filename, mode='w', delimiter=','): | |
"""Writes an array to a csv file. | |
Note: use mode='w' to overwrite file or mode='a' to append to file).""" | |
# Convert array to string | |
s = '' | |
for row in arr: | |
s += delimiter.join(str(x) for x in row) + '\n' | |
s = s[:-1] # Remove last line end | |
# Write string to csv. | |
with open(filename, mode) as f: | |
f.write(s) | |
if __name__ == '__main__': | |
user_args = get_user_args() | |
input_image = user_args.input_image | |
console_output_on = user_args.console_output_on | |
size = int(user_args.max_dim), int(user_args.max_dim) | |
simple_name = os.path.splitext(input_image)[0] | |
# Read in image (as a PIL Image object) | |
im = Image.open(input_image) | |
# create grayscale copy | |
im_gray = im.convert('L') | |
# create color and grayscale thumbnails | |
im_gray.thumbnail(size) | |
im.thumbnail(size) | |
# save thumbnails as jpg files | |
im_gray.save(simple_name + "_gray_thumb.jpg") | |
im.save(simple_name + "_thumb.jpg") | |
# convert Image objects into numpy arrays | |
gray_array = np.asarray(im_gray.getdata(), dtype=np.float64).reshape(im_gray.size) | |
color_array = np.asarray(im.getdata(), dtype=np.float64) | |
# print grayscale array on screen and save as CSV file | |
if console_output_on: | |
print("Grayscale Thumbnail:") | |
print("size = {} x {}".format(*im_gray.size)) | |
print(gray_array) | |
csvio.arr2csv(gray_array, simple_name + "_gray_thumb.csv", mode='w', delimiter=',') | |
color_array = color_array.reshape((im.size[0], im.size[1], 3)) | |
if console_output_on: | |
print("\nColor Array:") | |
print("size = {} x {} x {}".format(*color_array.shape)) | |
print(color_array) | |
csvio.arr2csv(color_array, simple_name + "_thumb.csv", mode='w', delimiter=',') | |
print("Done. Two thumbnail images and corresponding CSV files saved.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment