File size: 1,877 Bytes
8c50231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df7a2a7
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 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")