Lenylvt commited on
Commit
9ec2c1d
1 Parent(s): a62b394

Upload main2.py

Browse files
Files changed (1) hide show
  1. Cards File (Crop Image)/main2.py +63 -0
Cards File (Crop Image)/main2.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import os
3
+
4
+ def crop(input_path, output_path, target_size=(308, 320)):
5
+ """
6
+ Crop an image to a specified size, biased towards the top of the image.
7
+
8
+ :param input_path: Path to the input image file.
9
+ :param output_path: Path where the cropped image will be saved.
10
+ :param target_size: The target size as a tuple (width, height).
11
+ """
12
+ with Image.open(input_path) as img:
13
+ width, height = img.size
14
+ target_width, target_height = target_size
15
+
16
+ # Check if the target size is larger than the image
17
+ if target_width > width or target_height > height:
18
+ print(f"Image {input_path} is too small to be cropped to {target_size}.")
19
+ return
20
+
21
+ # Calculate the cropping box, biased towards the top
22
+ left = (width - target_width) / 2
23
+ right = (width + target_width) / 2
24
+
25
+ # Adjust the top and bottom coordinates to crop towards the top
26
+ top = height * 0.18 # Adjust this factor to move the crop area up or down
27
+ bottom = top + target_height
28
+
29
+ # Ensure bottom does not exceed image height
30
+ if bottom > height:
31
+ bottom = height
32
+ top = height - target_height
33
+
34
+ # Crop and save the image
35
+ img_cropped = img.crop((left, top, right, bottom))
36
+ img_cropped.save(output_path)
37
+ print(f"Cropped (towards top) and saved: {output_path}")
38
+
39
+ def crop_images_in_folder(input_folder, output_folder=None, target_size=(308, 140)):
40
+ """
41
+ Crop all images in the specified folder to a centered 308x320 size, biased towards the top.
42
+
43
+ :param input_folder: Path to the folder containing images to be cropped.
44
+ :param output_folder: Path to the folder where cropped images will be saved. If None, saves in the input folder.
45
+ :param target_size: Target size to crop the images to.
46
+ """
47
+ if output_folder is None:
48
+ output_folder = input_folder
49
+
50
+ if not os.path.exists(output_folder):
51
+ os.makedirs(output_folder)
52
+
53
+ for filename in os.listdir(input_folder):
54
+ if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff')):
55
+ input_path = os.path.join(input_folder, filename)
56
+ output_path = os.path.join(output_folder, f"cropped_{filename}")
57
+
58
+ crop(input_path, output_path, target_size)
59
+
60
+ # Usage example
61
+ input_folder = 'Cards File (Normal)/room'
62
+ output_folder = 'Cards File (Normal) - Copie/room/' # Optional, can be None
63
+ crop_images_in_folder(input_folder, output_folder)