| | from PIL import Image |
| | import os |
| |
|
| | def crop(input_path, output_path, target_size=(308, 320)): |
| | """ |
| | Crop an image to a specified size, biased towards the top of the image. |
| | |
| | :param input_path: Path to the input image file. |
| | :param output_path: Path where the cropped image will be saved. |
| | :param target_size: The target size as a tuple (width, height). |
| | """ |
| | with Image.open(input_path) as img: |
| | width, height = img.size |
| | target_width, target_height = target_size |
| |
|
| | |
| | if target_width > width or target_height > height: |
| | print(f"Image {input_path} is too small to be cropped to {target_size}.") |
| | return |
| |
|
| | |
| | left = (width - target_width) / 2 |
| | right = (width + target_width) / 2 |
| | |
| | |
| | top = height * 0.18 |
| | bottom = top + target_height |
| |
|
| | |
| | if bottom > height: |
| | bottom = height |
| | top = height - target_height |
| |
|
| | |
| | img_cropped = img.crop((left, top, right, bottom)) |
| | img_cropped.save(output_path) |
| | print(f"Cropped (towards top) and saved: {output_path}") |
| |
|
| | def crop_images_in_folder(input_folder, output_folder=None, target_size=(308, 140)): |
| | """ |
| | Crop all images in the specified folder to a centered 308x320 size, biased towards the top. |
| | |
| | :param input_folder: Path to the folder containing images to be cropped. |
| | :param output_folder: Path to the folder where cropped images will be saved. If None, saves in the input folder. |
| | :param target_size: Target size to crop the images to. |
| | """ |
| | if output_folder is None: |
| | output_folder = input_folder |
| |
|
| | if not os.path.exists(output_folder): |
| | os.makedirs(output_folder) |
| |
|
| | for filename in os.listdir(input_folder): |
| | if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff')): |
| | input_path = os.path.join(input_folder, filename) |
| | output_path = os.path.join(output_folder, f"cropped_{filename}") |
| | |
| | crop(input_path, output_path, target_size) |
| |
|
| | |
| | input_folder = 'Cards File (Normal)/room' |
| | output_folder = 'Cards File (Normal) - Copie/room/' |
| | crop_images_in_folder(input_folder, output_folder) |
| |
|