ACCC1380 commited on
Commit
93221b3
1 Parent(s): 0cfe429

Upload lora-scripts/sd-scripts/tools/resize_images_to_resolution.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/tools/resize_images_to_resolution.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import cv2
4
+ import argparse
5
+ import shutil
6
+ import math
7
+ from PIL import Image
8
+ import numpy as np
9
+ from library.utils import setup_logging
10
+ setup_logging()
11
+ import logging
12
+ logger = logging.getLogger(__name__)
13
+
14
+ def resize_images(src_img_folder, dst_img_folder, max_resolution="512x512", divisible_by=2, interpolation=None, save_as_png=False, copy_associated_files=False):
15
+ # Split the max_resolution string by "," and strip any whitespaces
16
+ max_resolutions = [res.strip() for res in max_resolution.split(',')]
17
+
18
+ # # Calculate max_pixels from max_resolution string
19
+ # max_pixels = int(max_resolution.split("x")[0]) * int(max_resolution.split("x")[1])
20
+
21
+ # Create destination folder if it does not exist
22
+ if not os.path.exists(dst_img_folder):
23
+ os.makedirs(dst_img_folder)
24
+
25
+ # Select interpolation method
26
+ if interpolation == 'lanczos4':
27
+ cv2_interpolation = cv2.INTER_LANCZOS4
28
+ elif interpolation == 'cubic':
29
+ cv2_interpolation = cv2.INTER_CUBIC
30
+ else:
31
+ cv2_interpolation = cv2.INTER_AREA
32
+
33
+ # Iterate through all files in src_img_folder
34
+ img_exts = (".png", ".jpg", ".jpeg", ".webp", ".bmp") # copy from train_util.py
35
+ for filename in os.listdir(src_img_folder):
36
+ # Check if the image is png, jpg or webp etc...
37
+ if not filename.endswith(img_exts):
38
+ # Copy the file to the destination folder if not png, jpg or webp etc (.txt or .caption or etc.)
39
+ shutil.copy(os.path.join(src_img_folder, filename), os.path.join(dst_img_folder, filename))
40
+ continue
41
+
42
+ # Load image
43
+ # img = cv2.imread(os.path.join(src_img_folder, filename))
44
+ image = Image.open(os.path.join(src_img_folder, filename))
45
+ if not image.mode == "RGB":
46
+ image = image.convert("RGB")
47
+ img = np.array(image, np.uint8)
48
+
49
+ base, _ = os.path.splitext(filename)
50
+ for max_resolution in max_resolutions:
51
+ # Calculate max_pixels from max_resolution string
52
+ max_pixels = int(max_resolution.split("x")[0]) * int(max_resolution.split("x")[1])
53
+
54
+ # Calculate current number of pixels
55
+ current_pixels = img.shape[0] * img.shape[1]
56
+
57
+ # Check if the image needs resizing
58
+ if current_pixels > max_pixels:
59
+ # Calculate scaling factor
60
+ scale_factor = max_pixels / current_pixels
61
+
62
+ # Calculate new dimensions
63
+ new_height = int(img.shape[0] * math.sqrt(scale_factor))
64
+ new_width = int(img.shape[1] * math.sqrt(scale_factor))
65
+
66
+ # Resize image
67
+ img = cv2.resize(img, (new_width, new_height), interpolation=cv2_interpolation)
68
+ else:
69
+ new_height, new_width = img.shape[0:2]
70
+
71
+ # Calculate the new height and width that are divisible by divisible_by (with/without resizing)
72
+ new_height = new_height if new_height % divisible_by == 0 else new_height - new_height % divisible_by
73
+ new_width = new_width if new_width % divisible_by == 0 else new_width - new_width % divisible_by
74
+
75
+ # Center crop the image to the calculated dimensions
76
+ y = int((img.shape[0] - new_height) / 2)
77
+ x = int((img.shape[1] - new_width) / 2)
78
+ img = img[y:y + new_height, x:x + new_width]
79
+
80
+ # Split filename into base and extension
81
+ new_filename = base + '+' + max_resolution + ('.png' if save_as_png else '.jpg')
82
+
83
+ # Save resized image in dst_img_folder
84
+ # cv2.imwrite(os.path.join(dst_img_folder, new_filename), img, [cv2.IMWRITE_JPEG_QUALITY, 100])
85
+ image = Image.fromarray(img)
86
+ image.save(os.path.join(dst_img_folder, new_filename), quality=100)
87
+
88
+ proc = "Resized" if current_pixels > max_pixels else "Saved"
89
+ logger.info(f"{proc} image: {filename} with size {img.shape[0]}x{img.shape[1]} as {new_filename}")
90
+
91
+ # If other files with same basename, copy them with resolution suffix
92
+ if copy_associated_files:
93
+ asoc_files = glob.glob(os.path.join(src_img_folder, base + ".*"))
94
+ for asoc_file in asoc_files:
95
+ ext = os.path.splitext(asoc_file)[1]
96
+ if ext in img_exts:
97
+ continue
98
+ for max_resolution in max_resolutions:
99
+ new_asoc_file = base + '+' + max_resolution + ext
100
+ logger.info(f"Copy {asoc_file} as {new_asoc_file}")
101
+ shutil.copy(os.path.join(src_img_folder, asoc_file), os.path.join(dst_img_folder, new_asoc_file))
102
+
103
+
104
+ def setup_parser() -> argparse.ArgumentParser:
105
+ parser = argparse.ArgumentParser(
106
+ description='Resize images in a folder to a specified max resolution(s) / 指定されたフォルダ内の画像を指定した最大画像サイズ(面積)以下にアスペクト比を維持したままリサイズします')
107
+ parser.add_argument('src_img_folder', type=str, help='Source folder containing the images / 元画像のフォルダ')
108
+ parser.add_argument('dst_img_folder', type=str, help='Destination folder to save the resized images / リサイズ後の画像を保存するフォルダ')
109
+ parser.add_argument('--max_resolution', type=str,
110
+ help='Maximum resolution(s) in the format "512x512,384x384, etc, etc" / 最大画像サイズをカンマ区切りで指定 ("512x512,384x384, etc, etc" など)', default="512x512,384x384,256x256,128x128")
111
+ parser.add_argument('--divisible_by', type=int,
112
+ help='Ensure new dimensions are divisible by this value / リサイズ後の画像のサイズをこの値で割り切れるようにします', default=1)
113
+ parser.add_argument('--interpolation', type=str, choices=['area', 'cubic', 'lanczos4'],
114
+ default='area', help='Interpolation method for resizing / リサイズ時の補完方法')
115
+ parser.add_argument('--save_as_png', action='store_true', help='Save as png format / png形式で保存')
116
+ parser.add_argument('--copy_associated_files', action='store_true',
117
+ help='Copy files with same base name to images (captions etc) / 画像と同じファイル名(拡張子を除く)のファイルもコピーする')
118
+
119
+ return parser
120
+
121
+
122
+ def main():
123
+ parser = setup_parser()
124
+
125
+ args = parser.parse_args()
126
+ resize_images(args.src_img_folder, args.dst_img_folder, args.max_resolution,
127
+ args.divisible_by, args.interpolation, args.save_as_png, args.copy_associated_files)
128
+
129
+
130
+ if __name__ == '__main__':
131
+ main()