-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrop.py
More file actions
55 lines (43 loc) · 1.59 KB
/
crop.py
File metadata and controls
55 lines (43 loc) · 1.59 KB
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
import os
from PIL import Image
from pathlib import Path
# Define your paths
images_folder = Path("CUB_200_2011/images")
bounding_boxes_file = Path("CUB_200_2011/bounding_boxes.txt")
images_txt_file = Path("CUB_200_2011/images.txt")
output_folder = Path("images_cropped")
# Load bounding box data
# Format: {image_id: (x, y, width, height)}
bounding_boxes = {}
with open(bounding_boxes_file, "r") as f:
for line in f:
parts = line.strip().split()
image_id = int(parts[0])
x, y, width, height = map(float, parts[1:])
bounding_boxes[image_id] = (x, y, width, height)
# Now process each image
with open(images_txt_file, "r") as f:
for line in f:
parts = line.strip().split()
image_id = int(parts[0])
image_rel_path = parts[1]
# Full path to the image
image_path = images_folder / image_rel_path
# Load image
if not image_path.exists():
print(f"Warning: Image {image_path} not found.")
continue
img = Image.open(image_path)
# Get bounding box
if image_id not in bounding_boxes:
print(f"Warning: No bounding box for image ID {image_id}.")
continue
x, y, width, height = bounding_boxes[image_id]
# Crop the image
cropped_img = img.crop((x, y, x + width, y + height))
# Prepare output path
output_path = output_folder / image_rel_path
output_path.parent.mkdir(parents=True, exist_ok=True)
# Save cropped image
cropped_img.save(output_path)
print(f"Saved cropped image to {output_path}")