Spaces:
Build error
Build error
Commit ·
8d972cb
1
Parent(s): 8ee9a13
Add crop preprocessing script
Browse files- preprocess.py +37 -0
preprocess.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import random
|
| 4 |
+
|
| 5 |
+
# Define the source and destination directories
|
| 6 |
+
src_dir = Path('dataset4/bboxes')
|
| 7 |
+
dst_dir = Path('dataset4/crops3')
|
| 8 |
+
dst_dir.mkdir(parents=True, exist_ok=True)
|
| 9 |
+
|
| 10 |
+
# Define the scale
|
| 11 |
+
scale = (0.5, 0.8)
|
| 12 |
+
|
| 13 |
+
# Loop over all images in the source directory
|
| 14 |
+
for img_file in src_dir.glob('*.jpg'):
|
| 15 |
+
# Open the image
|
| 16 |
+
img = Image.open(img_file)
|
| 17 |
+
width, height = img.size
|
| 18 |
+
|
| 19 |
+
# Apply the transform 10 times to get 10 random crops
|
| 20 |
+
for i in range(3):
|
| 21 |
+
# Calculate random width and height
|
| 22 |
+
new_width = random.randint(int(width * scale[0]), int(width * scale[1]))
|
| 23 |
+
new_height = random.randint(int(height * scale[0]), int(height * scale[1]))
|
| 24 |
+
|
| 25 |
+
# Calculate random position for the crop
|
| 26 |
+
left = random.randint(0, width - new_width)
|
| 27 |
+
top = random.randint(0, height - new_height)
|
| 28 |
+
|
| 29 |
+
# Perform the crop
|
| 30 |
+
cropped_img = img.crop((left, top, left + new_width, top + new_height))
|
| 31 |
+
|
| 32 |
+
# Resize the cropped image to 224x224
|
| 33 |
+
resized_img = cropped_img.resize((224, 224))
|
| 34 |
+
|
| 35 |
+
# Save the resized image with coordinates in the filename
|
| 36 |
+
resized_img_file = dst_dir / f'{img_file.stem}_crop{i+1}_{left}_{top}_{left+new_width}_{top+new_height}.jpg'
|
| 37 |
+
resized_img.save(resized_img_file)
|