-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsd-rezize-1m.py
50 lines (39 loc) · 1.93 KB
/
sd-rezize-1m.py
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
from PIL import Image
import os
import math
def resize_and_pad(image_path, output_dir, target_area=1048576, divisor=32):
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# Load the image
img = Image.open(image_path)
original_width, original_height = img.size
original_area = original_width * original_height
# Calculate the resize ratio to reach the target area, while keeping aspect ratio
resize_ratio = math.sqrt(target_area / original_area)
new_width = round(original_width * resize_ratio)
new_height = round(original_height * resize_ratio)
# Adjust width and height to be divisible by the divisor (32 in this case)
new_width += (divisor - new_width % divisor) % divisor
new_height += (divisor - new_height % divisor) % divisor
# Ensure the final area does not exceed the target area significantly by reducing dimensions if necessary
while new_width * new_height > target_area:
new_width -= divisor
new_height -= divisor
# Resize the image
resized_image = img.resize((new_width, new_height), Image.LANCZOS)
# Finally, create an output image with the adjusted size and pad it if necessary
output_img = Image.new("RGB", (new_width, new_height), (0, 0, 0))
output_img.paste(resized_image, (0, 0))
# Save the processed image
filename = os.path.splitext(os.path.basename(image_path))[0] + '.jpeg'
output_path = os.path.join(output_dir, filename)
output_img.save(output_path, 'JPEG', optimize=True, quality=95)
# Example usage
# Assuming we have a directory 'input_images' with images to be processed
input_dir = 'input_images'
output_dir = 'output'
allowed_extensions = ('.png', '.jpg', '.jpeg')
for image_name in os.listdir(input_dir):
image_path = os.path.join(input_dir, image_name)
if os.path.isfile(image_path) and image_name.lower().endswith(allowed_extensions):
resize_and_pad(image_path, output_dir)