african_512 / resize_ds_img.py
louiscklaw
update beach_512,
df7a2a7
raw
history blame
1.88 kB
# iterate files over subdirectories in `00_store`, store image files in hash table, delete files with same hash
import os
import hashlib
from PIL import Image
def resize_image(file_path, max_size=512, respect_ratio=False):
if os.path.getsize(file_path) == 0:
os.remove(file_path)
print(f"Deleted empty file: {file_path}")
return
with Image.open(file_path) as img:
# Resize the image if width or height larger than 1024
if img.width > max_size or img.height > max_size:
new_width = max_size
new_height = max_size
if respect_ratio:
# Calculate the new size maintaining the aspect ratio
aspect_ratio = img.width / img.height
if img.width > img.height:
new_width = min(img.width, max_size)
new_height = int(new_width / aspect_ratio)
else:
new_height = min(img.height, max_size)
new_width = int(new_height * aspect_ratio)
# Resize the image
resized_img = img.resize((new_width, new_height))
# Save the resized image
resized_img.save(file_path)
print("resize done " + file_path)
else:
# skipping
# print("skipped " + file_path)
return
def resize_image_worker(file_path):
try:
resize_image(file_path)
except Exception as e:
print(file_path)
print(e)
def action(in_path):
from multiprocessing import Pool
with Pool(processes=18) as pool:
for root, _, files in os.walk(in_path):
pool.map(resize_image_worker, [os.path.join(root, file) for file in files])
CURR_DIR = os.path.dirname(os.path.abspath(__file__))
action(CURR_DIR + "/data/train")
action(CURR_DIR + "/data/validate")