|
|
|
|
|
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: |
|
|
|
|
|
if img.width > max_size or img.height > max_size: |
|
new_width = max_size |
|
new_height = max_size |
|
|
|
if respect_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) |
|
|
|
|
|
resized_img = img.resize((new_width, new_height)) |
|
|
|
|
|
resized_img.save(file_path) |
|
print("resize done " + file_path) |
|
|
|
else: |
|
|
|
|
|
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") |
|
|