File size: 2,545 Bytes
9ec2c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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

        # Check if the target size is larger than the image
        if target_width > width or target_height > height:
            print(f"Image {input_path} is too small to be cropped to {target_size}.")
            return

        # Calculate the cropping box, biased towards the top
        left = (width - target_width) / 2
        right = (width + target_width) / 2
        
        # Adjust the top and bottom coordinates to crop towards the top
        top = height * 0.18  # Adjust this factor to move the crop area up or down
        bottom = top + target_height

        # Ensure bottom does not exceed image height
        if bottom > height:
            bottom = height
            top = height - target_height

        # Crop and save the image
        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)

# Usage example
input_folder = 'Cards File (Normal)/room'
output_folder = 'Cards File (Normal) - Copie/room/' # Optional, can be None
crop_images_in_folder(input_folder, output_folder)