bhimrazy commited on
Commit
cc095d7
1 Parent(s): 8c581a0

Add script for cropping and resizing images

Browse files
Files changed (1) hide show
  1. scripts/crop_and_resize.py +48 -0
scripts/crop_and_resize.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ from src.concurrent_task_executor import concurrent_task_executor
4
+ from src.utils import crop_and_pad_image, track_files
5
+
6
+ from typing import NamedTuple, Tuple
7
+
8
+ parser = argparse.ArgumentParser(description="Crop and Resize Images in a folder")
9
+ parser.add_argument("--src", type=str, help="source folder", required=True)
10
+ parser.add_argument("--dest", type=str, help="destination folder", required=True)
11
+ parser.add_argument("--size", type=Tuple[int,int], help="Size of image in pixels, given as a (width, height) tuple", default=(512, 512))
12
+
13
+
14
+ class FileInfo(NamedTuple):
15
+ src: str
16
+ dest: str
17
+ size: Tuple[int, int] # (width, height) tuple.
18
+
19
+
20
+ def crop_and_save_image(file_info: FileInfo):
21
+ try:
22
+ cropped_image = crop_and_pad_image(file_info.src, target_size=file_info.size)
23
+ cropped_image.save(file_info.dest)
24
+ except Exception as e:
25
+ print(f"Error processing image: {str(e)}")
26
+
27
+
28
+ if __name__ == "__main__":
29
+ args = parser.parse_args()
30
+ src_folder = args.src
31
+ dst_folder = args.dest
32
+ size = args.size
33
+
34
+ # check if destination folder exists
35
+ if not os.path.exists(dst_folder):
36
+ print("Destination folder does not exist. Creating folder...")
37
+ os.makedirs(dst_folder, exist_ok=True)
38
+
39
+ files = [
40
+ FileInfo(
41
+ src_image_path,
42
+ os.path.join(dst_folder, os.path.basename(src_image_path)),
43
+ size
44
+ )
45
+ for src_image_path in track_files(src_folder)
46
+ ]
47
+ # cropping and resizing images and saving them to the destination folder
48
+ concurrent_task_executor(crop_and_save_image, files, description="Processing images")