Last active
July 13, 2023 10:53
-
-
Save ekaitz-zarraga/a3d4383ed51dcc5b5d1f1764cc35f0ea to your computer and use it in GitHub Desktop.
Another shitty example :)
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
from PIL import Image | |
from os import path as p | |
import os | |
import argparse | |
def process_image(im): | |
size = im.size | |
menor = min(size) | |
return im.crop((0,0,menor,menor)) \ | |
.resize((256,256)) \ | |
.convert("L") | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser( | |
prog='Converter', | |
description='Converts images for Neural Network input', | |
epilog='') | |
parser.add_argument('src_dir', help="Source directory") | |
parser.add_argument('dest_dir', help="Destination directory") | |
parser.add_argument('-c', '--create-dest', action='store_true', | |
help="Create destination directory, default is False") | |
args = parser.parse_args() | |
src_dir = args.src_dir | |
dest_dir = args.dest_dir | |
if not p.isdir(src_dir): | |
print(f"Source directory \"{src_dir}\" does not exist") | |
exit(1) | |
if not p.isdir(dest_dir): | |
if args.create_dest: | |
os.mkdir(dest_dir) | |
else: | |
print(f"Destination directory \"{dest_dir}\" does not exist") | |
exit(1) | |
for root, dirs, files in os.walk(src_dir): | |
for filename in files: | |
f = p.join(root, filename) | |
im = Image.open(f) | |
im = process_image(im) | |
rel = p.relpath(f, start=src_dir) | |
dest = p.join(dest_dir, rel) | |
os.makedirs( p.dirname(dest), exist_ok=True ) | |
im.save( dest ) |
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
from PIL import Image | |
from os import path as p | |
import os | |
import sys | |
def process_image(im): | |
size = im.size | |
menor = min(size) | |
return im.crop((0,0,menor,menor)) \ | |
.resize((256,256)) \ | |
.convert("L") | |
if __name__ == "__main__": | |
if len(sys.argv) != 3: | |
# TODO: Handle this properly using argparse | |
print(f"USAGE:\n\t{sys.argv[0]} SOURCE_DIR DESTINATION_DIR") | |
exit(1) | |
src_dir = sys.argv[1] | |
dest_dir = sys.argv[2] | |
if not p.isdir(src_dir): | |
print(f"Source directory \"{src_dir}\" does not exist") | |
exit(1) | |
if not p.isdir(dest_dir): | |
print(f"Destination directory \"{dest_dir}\" does not exist") | |
exit(1) | |
infiles = [ p.join(src_dir, i) for i in os.listdir(src_dir) ] | |
print(infiles) | |
for f in infiles: | |
im = Image.open(f) | |
im = process_image(im) | |
filename = p.basename(f) | |
im.save( p.join(dest_dir, filename) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment