Crops images from the source folder and saves them to the output folder.
(source_folder, output_folder)
| 6 | from tqdm import tqdm |
| 7 | |
| 8 | def crop_images(source_folder, output_folder): |
| 9 | """ |
| 10 | Crops images from the source folder and saves them to the output folder. |
| 11 | """ |
| 12 | print(f"Starting to crop images from '{source_folder}'...") |
| 13 | os.makedirs(output_folder, exist_ok=True) |
| 14 | |
| 15 | filenames = [f for f in sorted(os.listdir(source_folder)) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp'))] |
| 16 | |
| 17 | for filename in tqdm(filenames, desc=f"Cropping {os.path.basename(source_folder)}"): |
| 18 | file_path = os.path.join(source_folder, filename) |
| 19 | img = cv2.imread(file_path) |
| 20 | |
| 21 | if img is None: |
| 22 | print(f"Warning: Unable to load image {filename}. Skipping.") |
| 23 | continue |
| 24 | |
| 25 | h, w = img.shape[:2] |
| 26 | |
| 27 | # Step 1: Scale while maintaining aspect ratio, making the smallest side 1024 |
| 28 | if w < h: |
| 29 | new_w = 1024 |
| 30 | new_h = int(h * (1024 / w)) |
| 31 | else: |
| 32 | new_h = 1024 |
| 33 | new_w = int(w * (1024 / h)) |
| 34 | |
| 35 | img_resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LANCZOS4) |
| 36 | |
| 37 | # Step 2: Crop a 1024x1024 area from the center |
| 38 | current_h, current_w = img_resized.shape[:2] |
| 39 | start_x = (current_w - 1024) // 2 |
| 40 | start_y = (current_h - 1024) // 2 |
| 41 | |
| 42 | img_cropped = img_resized[start_y:start_y + 1024, start_x:start_x + 1024] |
| 43 | |
| 44 | target_path = os.path.join(output_folder, filename) |
| 45 | cv2.imwrite(target_path, img_cropped) |
| 46 | |
| 47 | print(f"Finished cropping. Cropped images are in '{output_folder}'.") |
| 48 | |
| 49 | def create_videos_by_prefix(image_folder, output_folder, fps=25, max_frames=None): |
| 50 | """ |