import os
import glob
from PIL import Image
import math
# Define the target pixel count (e.g., 1,048,576)
TARGET_PIXEL_COUNT = 1048576 # 1024 x 1024 pixels
# Define the input directory containing the original images
INPUT_DIR = 'input_images' # Directory containing the original images
# Define the base output directory where resized images will be saved
OUTPUT_DIR = 'resized_images' # Base directory to save resized images
# Create the output directory if it doesn't exist
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Initialize a set to collect unique resolutions of resized images
resolutions = set()
# Get list of image files in the input directory (supports various image formats)
image_files = glob.glob(os.path.join(INPUT_DIR, '*.*')) # Matches any file in the folder
# Process each image in the input directory
for image_path in image_files:
# Open the image file
img = Image.open(image_path)
# Get the original width and height of the image
original_width, original_height = img.size
# Calculate the total pixel count of the original image
total_pixels = original_width * original_height
# Calculate scaling factor to reach the target pixel count
scaling_factor = math.sqrt(TARGET_PIXEL_COUNT / total_pixels)
# Calculate new width and height based on the scaling factor
new_width = original_width * scaling_factor
new_height = original_height * scaling_factor
# Adjust the new dimensions to the nearest multiples of 64
adjusted_width = int(round(new_width / 64) * 64)
adjusted_height = int(round(new_height / 64) * 64)
# Resize the image to the adjusted dimensions using high-quality downsampling filter
img_resized = img.resize((adjusted_width, adjusted_height), Image.ANTIALIAS)
# Save the resized image in a folder named according to its new width and height (e.g., '1280_832')
folder_name = f"{adjusted_width}_{adjusted_height}"
save_dir = os.path.join(OUTPUT_DIR, folder_name)
os.makedirs(save_dir, exist_ok=True) # Create the directory if it doesn't exist
# Save the image using the same filename as the original
img_filename = os.path.basename(image_path)
save_path = os.path.join(save_dir, img_filename)
img_resized.save(save_path)
# Add the resolution to the set of resolutions
resolutions.add((adjusted_width, adjusted_height))
# Start building the dataset.toml content as a string
toml_content = "[general]\n\n"
# Iterate over sorted resolutions to build the datasets entries
for resolution in sorted(resolutions):
adjusted_width, adjusted_height = resolution
folder_name = f"{adjusted_width}_{adjusted_height}"
image_dir = os.path.join(OUTPUT_DIR, folder_name)
# Append the dataset entry to the toml content string
toml_content += "[[datasets]]\n"
toml_content += f"batch_size = 1\n"
toml_content += f"enable_bucket = true\n"
toml_content += f"resolution = [{adjusted_width}, {adjusted_height}]\n\n"
toml_content += " [[datasets.subsets]]\n"
toml_content += f' image_dir = "{image_dir}"\n'
toml_content += f" num_repeats = 1\n\n"
# Save the toml_content string to 'dataset.toml' file
with open('dataset.toml', 'w') as toml_file:
toml_file.write(toml_content)
Code Explanation:
-
Imports:
os, glob: For file and directory management.
PIL.Image from the Pillow library: For image processing tasks.
math: For mathematical operations like square roots and rounding.
-
Constants Definition:
TARGET_PIXEL_COUNT: The desired total pixel count for the resized images.
INPUT_DIR: Directory containing the original images to process.
OUTPUT_DIR: Base directory where resized images will be saved.
-
Preparation:
- Create the output directory if it doesn't exist to ensure there's a place to save resized images.
-
Process Each Image:
- Read Image and Calculate Pixel Count:
- Use
glob to list all images in the input directory.
- Open each image and retrieve its width and height to calculate the total pixel count.
- Calculate Scaling Factor:
- Compute the scaling factor needed to adjust the image to the target pixel count using the square root of the ratio between the target and original pixel counts.
- Compute New Dimensions:
- Multiply the original dimensions by the scaling factor to get new dimensions.
- Adjust Dimensions to Multiples of 64:
- Adjust the new dimensions to the nearest multiples of 64 without using loops, by dividing, rounding, and multiplying.
- Resize and Save Image:
- Resize the image to the adjusted dimensions.
- Save the resized image in a directory named after its new dimensions (e.g., "1280_832").
- Ensure the save directory exists, and save the image with its original filename.
- Record Resolutions:
- Add the adjusted dimensions to a set to keep track of all unique resolutions.
-
Generate dataset.toml File:
- Build the TOML Content:
- Start with the
[general] section.
- For each unique resolution, add a
[[datasets]] entry specifying batch size, enable_bucket, and resolution.
Note on Constraints:
- Avoiding Loops in Resizing and Adjusting Dimensions:
- The calculations for adjusting width and height to multiples of 64 are done using mathematical operations (
round, int) without loops.
- Clear Comments:
- The code contains comments explaining each major step for clarity.
This script, when run in a Jupyter Notebook, will read images from the specified INPUT_DIR, process them as per the requirements, save the resized images appropriately, and generate a dataset.toml file reflecting the datasets' configurations.