Upload 2 files
Browse files- augment_fundus_images.py +136 -0
- crop_fundus_images.py +120 -0
augment_fundus_images.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
from PIL import Image
|
4 |
+
import random
|
5 |
+
|
6 |
+
from datasets.dataset_split import val_names # List of validation image filenames to exclude
|
7 |
+
|
8 |
+
|
9 |
+
def apply_zoom_in(img, factor):
|
10 |
+
"""Helper function: Apply center zoom-in effect."""
|
11 |
+
original_size = img.size
|
12 |
+
new_width = int(original_size[0] / factor)
|
13 |
+
new_height = int(original_size[1] / factor)
|
14 |
+
left = (original_size[0] - new_width) // 2
|
15 |
+
top = (original_size[1] - new_height) // 2
|
16 |
+
cropped_img = img.crop((left, top, left + new_width, top + new_height))
|
17 |
+
return cropped_img.resize(original_size, Image.Resampling.LANCZOS)
|
18 |
+
|
19 |
+
|
20 |
+
def apply_combo_transform(img, angle, zoom_factor):
|
21 |
+
"""
|
22 |
+
Helper function: Apply combined transform (rotate then zoom).
|
23 |
+
|
24 |
+
:param img: Input PIL Image object.
|
25 |
+
:param angle: Rotation angle in degrees.
|
26 |
+
:param zoom_factor: Zoom factor (e.g., 1.2 means 20% zoom-in).
|
27 |
+
:return: Transformed PIL Image object.
|
28 |
+
"""
|
29 |
+
original_size = img.size
|
30 |
+
|
31 |
+
# Step 1: Rotate the image
|
32 |
+
rotated_img = img.rotate(angle, resample=Image.BICUBIC, expand=False, fillcolor='black')
|
33 |
+
|
34 |
+
# Step 2: Center crop to achieve zoom effect
|
35 |
+
new_width = int(original_size[0] / zoom_factor)
|
36 |
+
new_height = int(original_size[1] / zoom_factor)
|
37 |
+
left = (original_size[0] - new_width) // 2
|
38 |
+
top = (original_size[1] - new_height) // 2
|
39 |
+
right = left + new_width
|
40 |
+
bottom = top + new_height
|
41 |
+
|
42 |
+
cropped_rotated_img = rotated_img.crop((left, top, right, bottom))
|
43 |
+
|
44 |
+
# Step 3: Resize back to original dimensions
|
45 |
+
final_img = cropped_rotated_img.resize(original_size, Image.Resampling.LANCZOS)
|
46 |
+
return final_img
|
47 |
+
|
48 |
+
|
49 |
+
def process_images_ultimate(source_folder, output_folder, rotation_angle_range=15, zoom_in_range=(1.05, 1.17)):
|
50 |
+
"""
|
51 |
+
Ultimate data augmentation script: all transforms use independent random parameters.
|
52 |
+
- 2x independent random rotations
|
53 |
+
- 2x independent random zooms
|
54 |
+
- 2x independent random rotation + zoom combinations
|
55 |
+
"""
|
56 |
+
if not os.path.exists(output_folder):
|
57 |
+
os.makedirs(output_folder)
|
58 |
+
print(f"Created output folder: {output_folder}")
|
59 |
+
|
60 |
+
supported_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff')
|
61 |
+
|
62 |
+
for filename in os.listdir(source_folder):
|
63 |
+
if filename in val_names: # Skip validation dataset
|
64 |
+
continue
|
65 |
+
|
66 |
+
if not filename.lower().endswith(supported_extensions):
|
67 |
+
continue
|
68 |
+
|
69 |
+
source_path = os.path.join(source_folder, filename)
|
70 |
+
|
71 |
+
try:
|
72 |
+
shutil.copy2(source_path, output_folder)
|
73 |
+
print(f"Copied original: {filename}")
|
74 |
+
except Exception as e:
|
75 |
+
print(f"Error copying file {filename}: {e}")
|
76 |
+
continue
|
77 |
+
|
78 |
+
try:
|
79 |
+
with Image.open(source_path) as img:
|
80 |
+
name, ext = os.path.splitext(filename)
|
81 |
+
|
82 |
+
# --- 1. Generate independent random parameters for all transforms ---
|
83 |
+
standalone_rot_angle1 = random.uniform(5, rotation_angle_range)
|
84 |
+
standalone_rot_angle2 = random.uniform(-rotation_angle_range, -5)
|
85 |
+
|
86 |
+
standalone_zoom_factor1 = random.uniform(zoom_in_range[0], zoom_in_range[1])
|
87 |
+
standalone_zoom_factor2 = random.uniform(zoom_in_range[0], zoom_in_range[1])
|
88 |
+
|
89 |
+
combo_rot_angle1 = random.uniform(5, rotation_angle_range)
|
90 |
+
combo_zoom_factor1 = random.uniform(zoom_in_range[0], zoom_in_range[1])
|
91 |
+
combo_rot_angle2 = random.uniform(-rotation_angle_range, -5)
|
92 |
+
combo_zoom_factor2 = random.uniform(zoom_in_range[0], zoom_in_range[1])
|
93 |
+
|
94 |
+
# --- 2. Apply independent rotations (2 images) ---
|
95 |
+
for i, angle in enumerate([standalone_rot_angle1, standalone_rot_angle2]):
|
96 |
+
rotated_img = img.rotate(angle, resample=Image.BICUBIC, expand=False, fillcolor='black')
|
97 |
+
rotated_filename = f"{name}_rot_{i + 1}_{int(angle)}deg{ext}"
|
98 |
+
rotated_img.save(os.path.join(output_folder, rotated_filename))
|
99 |
+
print(f" -> Created rotated image: {rotated_filename}")
|
100 |
+
|
101 |
+
# --- 3. Apply independent zooms (2 images) ---
|
102 |
+
for i, factor in enumerate([standalone_zoom_factor1, standalone_zoom_factor2]):
|
103 |
+
zoomed_img = apply_zoom_in(img, factor)
|
104 |
+
zoomed_filename = f"{name}_zoom_{i + 1}_{int(factor * 100)}pct{ext}"
|
105 |
+
zoomed_img.save(os.path.join(output_folder, zoomed_filename))
|
106 |
+
print(f" -> Created zoomed image: {zoomed_filename}")
|
107 |
+
|
108 |
+
# --- 4. Apply rotation+zoom combos (2 images) ---
|
109 |
+
combo_img1 = apply_combo_transform(img, combo_rot_angle1, combo_zoom_factor1)
|
110 |
+
combo_filename1 = f"{name}_combo_{int(combo_rot_angle1)}deg_{int(combo_zoom_factor1 * 100)}pct{ext}"
|
111 |
+
combo_img1.save(os.path.join(output_folder, combo_filename1))
|
112 |
+
print(f" -> Created combo image: {combo_filename1}")
|
113 |
+
|
114 |
+
combo_img2 = apply_combo_transform(img, combo_rot_angle2, combo_zoom_factor2)
|
115 |
+
combo_filename2 = f"{name}_combo_{int(combo_rot_angle2)}deg_{int(combo_zoom_factor2 * 100)}pct{ext}"
|
116 |
+
combo_img2.save(os.path.join(output_folder, combo_filename2))
|
117 |
+
print(f" -> Created combo image: {combo_filename2}")
|
118 |
+
|
119 |
+
except Exception as e:
|
120 |
+
print(f"Error processing image {filename}: {e}")
|
121 |
+
|
122 |
+
|
123 |
+
if __name__ == '__main__':
|
124 |
+
input_directory = 'csdi_datasets/croped_images'
|
125 |
+
output_directory = 'csdi_datasets/croped_augmented_images'
|
126 |
+
|
127 |
+
if not os.path.isdir(input_directory):
|
128 |
+
print(f"Error: input folder '{input_directory}' does not exist or is not a directory.")
|
129 |
+
else:
|
130 |
+
process_images_ultimate(
|
131 |
+
input_directory,
|
132 |
+
output_directory,
|
133 |
+
rotation_angle_range=15,
|
134 |
+
zoom_in_range=(1.05, 1.17)
|
135 |
+
)
|
136 |
+
print("\nProcessing complete!")
|
crop_fundus_images.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
import os
|
4 |
+
import argparse
|
5 |
+
from tqdm import tqdm
|
6 |
+
import csv
|
7 |
+
|
8 |
+
def crop_and_save_image(input_path, output_path, padding=10):
|
9 |
+
"""
|
10 |
+
Crop a single fundus image to remove black background and save to the specified path.
|
11 |
+
|
12 |
+
Returns:
|
13 |
+
dict: A dictionary containing cropping information, used for writing to CSV.
|
14 |
+
"""
|
15 |
+
try:
|
16 |
+
image = cv2.imread(input_path)
|
17 |
+
if image is None:
|
18 |
+
print(f"Warning: Unable to read image {input_path}, skipped.")
|
19 |
+
return None
|
20 |
+
|
21 |
+
original_h, original_w = image.shape[:2]
|
22 |
+
|
23 |
+
# Convert to grayscale for thresholding
|
24 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
25 |
+
_, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
|
26 |
+
|
27 |
+
# Find contours
|
28 |
+
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
29 |
+
if not contours:
|
30 |
+
print(f"Warning: No contours found in image {input_path}, skipped.")
|
31 |
+
return None
|
32 |
+
|
33 |
+
# Find the largest contour (main fundus region)
|
34 |
+
main_contour = max(contours, key=cv2.contourArea)
|
35 |
+
x, y, w, h = cv2.boundingRect(main_contour)
|
36 |
+
|
37 |
+
img_h, img_w = original_h, original_w
|
38 |
+
x1 = max(0, x - padding)
|
39 |
+
y1 = max(0, y - padding)
|
40 |
+
x2 = min(img_w, x + w + padding)
|
41 |
+
y2 = min(img_h, y + h + padding)
|
42 |
+
|
43 |
+
cropped_image = image[y1:y2, x1:x2]
|
44 |
+
|
45 |
+
# Replace white spots in black background with black
|
46 |
+
white_mask = np.all(cropped_image == [255, 255, 255], axis=-1)
|
47 |
+
cropped_image[white_mask] = [0, 0, 0]
|
48 |
+
|
49 |
+
cv2.imwrite(output_path, cropped_image)
|
50 |
+
|
51 |
+
# Calculate cropped pixels (left, top, right, bottom)
|
52 |
+
left_crop = x1
|
53 |
+
top_crop = y1
|
54 |
+
right_crop = img_w - x2
|
55 |
+
bottom_crop = img_h - y2
|
56 |
+
|
57 |
+
return {
|
58 |
+
"filename": os.path.basename(input_path),
|
59 |
+
"original_width": original_w,
|
60 |
+
"original_height": original_h,
|
61 |
+
"left_crop": left_crop,
|
62 |
+
"top_crop": top_crop,
|
63 |
+
"right_crop": right_crop,
|
64 |
+
"bottom_crop": bottom_crop
|
65 |
+
}
|
66 |
+
|
67 |
+
except Exception as e:
|
68 |
+
print(f"Error processing file {input_path}: {e}")
|
69 |
+
return None
|
70 |
+
|
71 |
+
def main():
|
72 |
+
parser = argparse.ArgumentParser(description="Automatically crop fundus images to remove black background.")
|
73 |
+
parser.add_argument('-i', '--input_dir', help="Input directory containing original images.", default="csdi_datasets/original_images")
|
74 |
+
parser.add_argument('-o', '--output_dir', help="Output directory for saving cropped images.", default="csdi_datasets/croped_images")
|
75 |
+
parser.add_argument('-p', '--padding', type=int, default=0, help="Extra pixel padding around the crop boundary, default 0.")
|
76 |
+
parser.add_argument('-c', '--csv_path', type=str, default="crop_info.csv", help="CSV file path to save cropping information, default 'crop_info.csv'.")
|
77 |
+
|
78 |
+
args = parser.parse_args()
|
79 |
+
input_dir = args.input_dir
|
80 |
+
output_dir = args.output_dir
|
81 |
+
padding = args.padding
|
82 |
+
csv_path = args.csv_path
|
83 |
+
|
84 |
+
if not os.path.isdir(input_dir):
|
85 |
+
print(f"Error: Input directory '{input_dir}' does not exist.")
|
86 |
+
return
|
87 |
+
|
88 |
+
os.makedirs(output_dir, exist_ok=True)
|
89 |
+
print(f"Cropped images will be saved to: '{output_dir}'")
|
90 |
+
|
91 |
+
supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff')
|
92 |
+
image_files = [f for f in os.listdir(input_dir) if f.lower().endswith(supported_formats)]
|
93 |
+
|
94 |
+
if not image_files:
|
95 |
+
print(f"No supported image files found in directory '{input_dir}'.")
|
96 |
+
return
|
97 |
+
|
98 |
+
crop_records = []
|
99 |
+
|
100 |
+
print(f"Found {len(image_files)} images, starting processing...")
|
101 |
+
for filename in tqdm(image_files, desc="Processing progress"):
|
102 |
+
input_image_path = os.path.join(input_dir, filename)
|
103 |
+
output_image_path = os.path.join(output_dir, filename)
|
104 |
+
|
105 |
+
record = crop_and_save_image(input_image_path, output_image_path, padding)
|
106 |
+
if record:
|
107 |
+
crop_records.append(record)
|
108 |
+
|
109 |
+
# Write CSV file
|
110 |
+
with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
|
111 |
+
fieldnames = ["filename", "original_width", "original_height", "left_crop", "top_crop", "right_crop", "bottom_crop"]
|
112 |
+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
113 |
+
writer.writeheader()
|
114 |
+
for rec in crop_records:
|
115 |
+
writer.writerow(rec)
|
116 |
+
|
117 |
+
print(f"All images processed! Cropping information saved to '{csv_path}'.")
|
118 |
+
|
119 |
+
if __name__ == '__main__':
|
120 |
+
main()
|