Skip to content

Instantly share code, notes, and snippets.

@AnBucquet
Forked from jbdrvl/convert-save.py
Last active January 15, 2019 12:32
Show Gist options
  • Select an option

  • Save AnBucquet/dba9498d785928bab15c33fac249a0eb to your computer and use it in GitHub Desktop.

Select an option

Save AnBucquet/dba9498d785928bab15c33fac249a0eb to your computer and use it in GitHub Desktop.
For a project - takes pics in a folder, resizes them and saves them into another folder
#!/usr/bin/env python3
#!/usr/bin/env python
"""
A script designed to
1) resize all of the downloaded images to desired dimension (DEFAULT 64x64 pixels) and
2) rename images in folders from 1.png to n.png for ease of use in training
Modified version from https://github.com/rkjones4/GANGogh/blob/master/misc/picStuff.py
"""
import os, csv
import scipy.misc
if __name__=="__main__":
src_folder='./fullimages'
out_folder='./smallimages'
csv_file = open('index.csv', 'w')
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(['subdir', 'old-name', 'new-name'])
err_file = open('error-files.csv', 'w')
err_writer = csv.writer(err_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
err_writer.writerow(['subdir', 'name', 'error'])
# if "smallimages" is not here, create it
try:
os.stat(out_folder)
print("Folder %s already exists" % out_folder)
except:
print("Making new folder", out_folder)
os.mkdir(out_folder)
img_ok_nbr = 0
img_pb_nbr = 0
# go through subdirs and files
for subdir, dirs, files in os.walk(src_folder):
if subdir==src_folder:
# first iteration - just going thru the subdirs w/out entering them
for subdir_name in dirs:
new_subdir = out_folder+'/'+subdir_name
try:
os.stat(new_subdir)
print("[SUBDIR] Subdir %s already exists" % new_subdir)
except:
print("[SUBDIR] Making new directory:", new_subdir)
os.mkdir(new_subdir)
else:
# now going thru files of each subdir
subdir_name = subdir.split('/')[-1]
print("\n[SUBDIR PICTURES] Going through pictures in subdir", subdir_name)
i=0
for f in files:
#file_format = f.split('.')[-1]
try:
image = scipy.misc.imread(subdir+'/'+f)
image = scipy.misc.imresize(image,(64,64))
new_f = out_folder+'/'+subdir_name+'/'+str(i)+'.png' #+file_format
#print("[PICTURE] Saving %s as %s" % (f, new_f))
scipy.misc.imsave(new_f, image)
csv_writer.writerow([subdir_name, f, str(i)+'.png'])
i+=1
img_ok_nbr+=1
except Exception as err:
print("\n[ERROR] Couldn't convert and save %s" % subdir+'/'+f)
print("\n[ERROR] Here is the error:\n", err)
err_writer.writerow([subdir_name, f, err])
img_pb_nbr+=1
print("\rTotal nbr of images converted = %d -- Total nbr of images NOT converted = %d"%(img_ok_nbr, img_pb_nbr), end='')
csv_file.close()
err_file.close()
print('\nDONE')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment