-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataset_manager.py
More file actions
1990 lines (1660 loc) · 76.7 KB
/
Copy pathdataset_manager.py
File metadata and controls
1990 lines (1660 loc) · 76.7 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Dataset Manager for managing local annotated data for RT-DETR model training.
"""
import os
import json
from pathlib import Path
from typing import Optional, Dict, Any, List, Tuple
import random
import numpy as np
import cv2
class DatasetManager:
"""
Manager class for organizing and managing local datasets
for RT-DETR model training.
"""
def __init__(self, dataset_root: str = "./datasets"):
"""
Initialize the DatasetManager.
Args:
dataset_root: Root directory containing datasets
"""
self.dataset_root = Path(dataset_root)
self.dataset_root.mkdir(parents=True, exist_ok=True)
def load_dataset(self, dataset_path: str) -> Dict[str, Any]:
"""
Load and analyze a local dataset.
Args:
dataset_path: Path to the dataset directory
Returns:
Dictionary containing dataset information and paths
"""
dataset_path = Path(dataset_path)
if not dataset_path.exists():
raise ValueError(f"Dataset path does not exist: {dataset_path}")
print(f"Loading dataset from: {dataset_path}")
# Analyze dataset structure
dataset_info = {
"name": dataset_path.name,
"location": str(dataset_path.absolute()),
"splits": {}
}
# Check for common splits
for split in ["train", "valid", "val", "test"]:
split_path = dataset_path / split
if split_path.exists():
images = self._count_images(split_path)
annotations = self._find_annotations(split_path)
dataset_info["splits"][split] = {
"path": str(split_path.absolute()),
"image_count": images,
"annotations": annotations
}
# Calculate totals
total_images = sum(split["image_count"] for split in dataset_info["splits"].values())
dataset_info["total_images"] = total_images
self._print_dataset_summary(dataset_info)
# Save dataset info
info_path = dataset_path / "dataset_info.json"
with open(info_path, 'w') as f:
json.dump(dataset_info, f, indent=2)
return dataset_info
def _count_images(self, path: Path) -> int:
"""Count image files in a directory."""
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp'}
if not path.exists():
return 0
# Use a set to avoid counting duplicates (important on case-insensitive file systems)
image_files = set()
for file_path in path.rglob("*"):
if file_path.is_file() and file_path.suffix.lower() in image_extensions:
image_files.add(file_path)
return len(image_files)
def _find_annotations(self, path: Path) -> Dict[str, str]:
"""Find annotation files in a directory."""
annotations = {}
if path.exists():
# COCO format
coco_files = list(path.rglob("*annotations*.json")) + list(path.rglob("*.json"))
if coco_files:
annotations["coco"] = str(coco_files[0].absolute())
# YOLO format
if (path / "labels").exists() or list(path.rglob("*.txt")):
annotations["yolo"] = "txt labels found"
# Pascal VOC format
if list(path.rglob("*.xml")):
annotations["voc"] = "xml annotations found"
return annotations
def _print_dataset_summary(self, info: Dict[str, Any]):
"""Print a formatted summary of the dataset."""
print("\n" + "="*60)
print("Dataset Summary")
print("="*60)
print(f"Name: {info['name']}")
print(f"Location: {info['location']}")
print(f"\nSplits:")
for split_name, split_info in info['splits'].items():
print(f" {split_name.capitalize()}:")
print(f" Images: {split_info['image_count']}")
if split_info['annotations']:
print(f" Annotations: {', '.join(split_info['annotations'].keys())}")
print(f"\nTotal Images: {info['total_images']}")
print("="*60 + "\n")
def verify_coco_format(self, annotation_path: str) -> Dict[str, Any]:
"""
Verify and analyze a COCO format annotation file.
Args:
annotation_path: Path to COCO JSON annotation file
Returns:
Dictionary with COCO dataset statistics
"""
annotation_path = Path(annotation_path)
if not annotation_path.exists():
raise ValueError(f"Annotation file not found: {annotation_path}")
with open(annotation_path, 'r') as f:
coco_data = json.load(f)
stats = {
"images": len(coco_data.get("images", [])),
"annotations": len(coco_data.get("annotations", [])),
"categories": len(coco_data.get("categories", [])),
"category_names": [cat["name"] for cat in coco_data.get("categories", [])]
}
print(f"\nCOCO Annotation Statistics ({annotation_path.name}):")
print(f" Images: {stats['images']}")
print(f" Annotations: {stats['annotations']}")
print(f" Categories: {stats['categories']}")
print(f" Classes: {', '.join(stats['category_names'])}")
return stats
def get_annotation_statistics(self, annotation_path: str, verbose: bool = True) -> Dict[str, Any]:
"""
Get comprehensive statistics about annotations in a COCO format file.
Args:
annotation_path: Path to COCO JSON annotation file
verbose: Whether to print detailed statistics (default: True)
Returns:
Dictionary containing comprehensive annotation statistics including:
- Total counts (images, annotations, categories)
- Per-category statistics (count, percentage, area stats)
- Image statistics
- Area statistics
"""
annotation_path = Path(annotation_path)
if not annotation_path.exists():
raise ValueError(f"Annotation file not found: {annotation_path}")
with open(annotation_path, 'r') as f:
coco_data = json.load(f)
images = coco_data.get("images", [])
annotations = coco_data.get("annotations", [])
categories = coco_data.get("categories", [])
# Basic counts
num_images = len(images)
num_annotations = len(annotations)
num_categories = len(categories)
# Create category lookup
cat_id_to_name = {cat['id']: cat['name'] for cat in categories}
# Initialize per-category statistics
category_stats = {cat['id']: {
'name': cat['name'],
'count': 0,
'areas': [],
'bbox_widths': [],
'bbox_heights': []
} for cat in categories}
# Count annotations per image
annotations_per_image = {}
# Process each annotation
for ann in annotations:
cat_id = ann['category_id']
img_id = ann['image_id']
# Count by category
if cat_id in category_stats:
category_stats[cat_id]['count'] += 1
# Collect area statistics
if 'area' in ann:
category_stats[cat_id]['areas'].append(ann['area'])
# Collect bbox statistics
if 'bbox' in ann:
x, y, w, h = ann['bbox']
category_stats[cat_id]['bbox_widths'].append(w)
category_stats[cat_id]['bbox_heights'].append(h)
# Count by image
annotations_per_image[img_id] = annotations_per_image.get(img_id, 0) + 1
# Compute statistics for each category
category_summary = []
for cat_id, stats in category_stats.items():
summary = {
'category_id': cat_id,
'name': stats['name'],
'count': stats['count'],
'percentage': (stats['count'] / num_annotations * 100) if num_annotations > 0 else 0
}
# Area statistics
if stats['areas']:
summary['area_mean'] = np.mean(stats['areas'])
summary['area_std'] = np.std(stats['areas'])
summary['area_min'] = np.min(stats['areas'])
summary['area_max'] = np.max(stats['areas'])
summary['area_median'] = np.median(stats['areas'])
# Bbox statistics
if stats['bbox_widths']:
summary['bbox_width_mean'] = np.mean(stats['bbox_widths'])
summary['bbox_height_mean'] = np.mean(stats['bbox_heights'])
summary['bbox_width_min'] = np.min(stats['bbox_widths'])
summary['bbox_width_max'] = np.max(stats['bbox_widths'])
summary['bbox_height_min'] = np.min(stats['bbox_heights'])
summary['bbox_height_max'] = np.max(stats['bbox_heights'])
category_summary.append(summary)
# Sort by count descending
category_summary = sorted(category_summary, key=lambda x: x['count'], reverse=True)
# Image statistics
if annotations_per_image:
ann_per_img_values = list(annotations_per_image.values())
image_stats = {
'images_with_annotations': len(annotations_per_image),
'images_without_annotations': num_images - len(annotations_per_image),
'annotations_per_image_mean': np.mean(ann_per_img_values),
'annotations_per_image_std': np.std(ann_per_img_values),
'annotations_per_image_min': np.min(ann_per_img_values),
'annotations_per_image_max': np.max(ann_per_img_values),
'annotations_per_image_median': np.median(ann_per_img_values)
}
else:
image_stats = {
'images_with_annotations': 0,
'images_without_annotations': num_images,
'annotations_per_image_mean': 0,
'annotations_per_image_std': 0,
'annotations_per_image_min': 0,
'annotations_per_image_max': 0,
'annotations_per_image_median': 0
}
# Compile results
results = {
'file_name': annotation_path.name,
'file_path': str(annotation_path.absolute()),
'total_images': num_images,
'total_annotations': num_annotations,
'total_categories': num_categories,
'category_names': [cat['name'] for cat in categories],
'categories': category_summary,
'image_statistics': image_stats
}
# Print detailed statistics if verbose
if verbose:
self._print_annotation_statistics(results)
return results
def _print_annotation_statistics(self, stats: Dict[str, Any]):
"""
Print formatted annotation statistics.
Args:
stats: Statistics dictionary from get_annotation_statistics()
"""
print("\n" + "="*70)
print(f"ANNOTATION STATISTICS - {stats['file_name']}")
print("="*70)
# Overall statistics
print("\n📊 Overall Statistics:")
print(f" Total Images: {stats['total_images']}")
print(f" Total Annotations: {stats['total_annotations']}")
print(f" Total Categories: {stats['total_categories']}")
# Image statistics
img_stats = stats['image_statistics']
print(f"\n🖼️ Image Statistics:")
print(f" Images with annotations: {img_stats['images_with_annotations']}")
print(f" Images without annotations: {img_stats['images_without_annotations']}")
print(f" Annotations per image:")
print(f" Mean: {img_stats['annotations_per_image_mean']:.2f}")
print(f" Std: {img_stats['annotations_per_image_std']:.2f}")
print(f" Min: {img_stats['annotations_per_image_min']:.0f}")
print(f" Max: {img_stats['annotations_per_image_max']:.0f}")
print(f" Median: {img_stats['annotations_per_image_median']:.2f}")
# Per-category statistics
print(f"\n📁 Per-Category Statistics:")
print("\n" + "-"*70)
for cat_stat in stats['categories']:
print(f"\nCategory: {cat_stat['name']} (ID: {cat_stat['category_id']})")
print(f" Count: {cat_stat['count']} ({cat_stat['percentage']:.2f}%)")
if 'area_mean' in cat_stat:
print(f" Area:")
print(f" Mean: {cat_stat['area_mean']:.2f}")
print(f" Std: {cat_stat['area_std']:.2f}")
print(f" Min: {cat_stat['area_min']:.2f}")
print(f" Max: {cat_stat['area_max']:.2f}")
print(f" Median: {cat_stat['area_median']:.2f}")
if 'bbox_width_mean' in cat_stat:
print(f" Bounding Box:")
print(f" Width: {cat_stat['bbox_width_mean']:.2f} (min: {cat_stat['bbox_width_min']:.2f}, max: {cat_stat['bbox_width_max']:.2f})")
print(f" Height: {cat_stat['bbox_height_mean']:.2f} (min: {cat_stat['bbox_height_min']:.2f}, max: {cat_stat['bbox_height_max']:.2f})")
print("\n" + "="*70 + "\n")
def prepare_for_rtdetr(self, dataset_path: str, output_path: Optional[str] = None) -> str:
"""
Prepare a dataset for RT-DETR training.
Ensures the dataset is in the correct format and structure.
Args:
dataset_path: Path to the source dataset
output_path: Optional output path (if None, uses dataset_path)
Returns:
Path to the prepared dataset
"""
dataset_path = Path(dataset_path)
if output_path:
output_path = Path(output_path)
output_path.mkdir(parents=True, exist_ok=True)
else:
output_path = dataset_path
print(f"Preparing dataset for RT-DETR training...")
print(f"Source: {dataset_path}")
print(f"Output: {output_path}")
# Verify required structure
required_splits = ["train", "valid"]
missing_splits = []
for split in required_splits:
split_variants = [split, "val" if split == "valid" else None]
found = False
for variant in split_variants:
if variant and (dataset_path / variant).exists():
found = True
break
if not found:
missing_splits.append(split)
if missing_splits:
print(f"⚠ Warning: Missing required splits: {', '.join(missing_splits)}")
else:
print("✓ All required splits found (train, valid)")
print(f"✓ Dataset prepared at: {output_path}")
return str(output_path.absolute())
def list_datasets(self) -> List[str]:
"""
List all datasets in the dataset root directory.
Returns:
List of dataset names
"""
datasets = []
if self.dataset_root.exists():
for item in self.dataset_root.iterdir():
if item.is_dir():
datasets.append(item.name)
if datasets:
print(f"Available datasets in {self.dataset_root}:")
for ds in datasets:
print(f" - {ds}")
else:
print(f"No datasets found in {self.dataset_root}")
return datasets
def visualize_annotations(
self,
annotation_path: str,
image_dir: str,
num_images: int = 5,
image_ids: Optional[List[int]] = None,
show_boxes: bool = True,
show_masks: bool = True,
show_labels: bool = True,
save_dir: Optional[str] = None,
display: bool = True
):
"""
Visualize images with their COCO segmentation annotations.
Args:
annotation_path: Path to COCO JSON annotation file
image_dir: Directory containing the images
num_images: Number of random images to visualize (if image_ids not specified)
image_ids: Specific image IDs to visualize (optional)
show_boxes: Whether to show bounding boxes
show_masks: Whether to show segmentation masks
show_labels: Whether to show category labels
save_dir: Optional directory to save visualizations
display: Whether to display images (press any key to continue)
"""
# Load COCO annotations
with open(annotation_path, 'r') as f:
coco_data = json.load(f)
# Create lookup dictionaries
images_dict = {img['id']: img for img in coco_data['images']}
categories_dict = {cat['id']: cat['name'] for cat in coco_data['categories']}
# Group annotations by image_id
annotations_by_image = {}
for ann in coco_data['annotations']:
img_id = ann['image_id']
if img_id not in annotations_by_image:
annotations_by_image[img_id] = []
annotations_by_image[img_id].append(ann)
# Select images to visualize
if image_ids is None:
available_ids = list(annotations_by_image.keys())
image_ids = random.sample(available_ids, min(num_images, len(available_ids)))
# Create save directory if specified
if save_dir:
Path(save_dir).mkdir(parents=True, exist_ok=True)
# Visualize each image
for img_id in image_ids:
self._visualize_single_image(
img_id,
images_dict,
annotations_by_image,
categories_dict,
image_dir,
show_boxes,
show_masks,
show_labels,
save_dir,
display
)
if display:
cv2.destroyAllWindows()
print(f"\n✓ Visualized {len(image_ids)} images")
def _visualize_single_image(
self,
img_id: int,
images_dict: Dict,
annotations_by_image: Dict,
categories_dict: Dict,
image_dir: str,
show_boxes: bool,
show_masks: bool,
show_labels: bool,
save_dir: Optional[str],
display: bool
):
"""
Visualize a single image with its annotations.
"""
if img_id not in images_dict:
print(f"Warning: Image ID {img_id} not found")
return
img_info = images_dict[img_id]
img_filename = img_info['file_name']
# Find the image file
image_path = self._find_image_file(image_dir, img_filename)
if not image_path:
print(f"Warning: Image file not found: {img_filename}")
return
# Load image with OpenCV
img = cv2.imread(str(image_path))
if img is None:
print(f"Warning: Failed to load image: {img_filename}")
return
# Convert BGR to RGB for proper color display
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Create a copy for drawing
img_display = img_rgb.copy()
# Get annotations for this image
annotations = annotations_by_image.get(img_id, [])
# Generate colors for each annotation (BGR format for OpenCV)
colors = self._generate_colors(len(annotations))
# Draw each annotation
for ann, color in zip(annotations, colors):
category_name = categories_dict.get(ann['category_id'], 'Unknown')
# Draw segmentation mask
if show_masks and 'segmentation' in ann:
img_display = self._draw_segmentation(img_display, ann['segmentation'], color, img_info)
# Draw bounding box
if show_boxes and 'bbox' in ann:
img_display = self._draw_bbox(img_display, ann['bbox'], color, category_name if show_labels else None)
# Add title/info text at the top
title = f"ID: {img_id} | File: {img_filename} | Annotations: {len(annotations)}"
cv2.putText(img_display, title, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (255, 255, 255), 2, cv2.LINE_AA)
cv2.putText(img_display, title, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 0, 0), 1, cv2.LINE_AA)
# Convert back to BGR for OpenCV display/save
img_bgr = cv2.cvtColor(img_display, cv2.COLOR_RGB2BGR)
# Save or display
if save_dir:
save_path = Path(save_dir) / f"visualization_{img_id}_{Path(img_filename).stem}.png"
cv2.imwrite(str(save_path), img_bgr)
print(f"Saved: {save_path}")
if display:
# Resize if image is too large
h, w = img_bgr.shape[:2]
max_dim = 1200
if max(h, w) > max_dim:
scale = max_dim / max(h, w)
img_bgr = cv2.resize(img_bgr, None, fx=scale, fy=scale)
cv2.imshow(f'Image ID: {img_id}', img_bgr)
print(f"Displaying image {img_id}. Press any key to continue...")
cv2.waitKey(0)
def _find_image_file(self, image_dir: str, filename: str) -> Optional[Path]:
"""
Find an image file in the directory (handles nested structures).
"""
image_dir = Path(image_dir)
# Try direct path
direct_path = image_dir / filename
if direct_path.exists():
return direct_path
# Search recursively
for img_path in image_dir.rglob(filename):
return img_path
return None
def _generate_colors(self, n: int) -> List[Tuple[int, int, int]]:
"""
Generate n distinct colors in RGB format.
"""
colors = []
for i in range(n):
hue = int(180 * i / max(n, 1))
# Create color in HSV then convert to RGB (OpenCV uses BGR)
hsv = np.uint8([[[hue, 255, 255]]])
rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)[0][0]
colors.append(tuple(map(int, rgb)))
return colors
def _draw_segmentation(self, img, segmentation, color, img_info):
"""
Draw segmentation mask on the image.
Returns the modified image.
"""
overlay = img.copy()
if isinstance(segmentation, list):
# Polygon format
for seg in segmentation:
if len(seg) >= 6: # At least 3 points (x, y pairs)
poly = np.array(seg).reshape(-1, 2).astype(np.int32)
# Fill polygon with transparency
cv2.fillPoly(overlay, [poly], color)
# Draw polygon outline
cv2.polylines(img, [poly], True, color, 2)
# Blend overlay with original for transparency effect
cv2.addWeighted(overlay, 0.4, img, 0.6, 0, img)
elif isinstance(segmentation, dict):
# RLE format
if 'counts' in segmentation:
mask = self._decode_rle(segmentation, img_info['height'], img_info['width'])
# Apply colored mask
colored_mask = np.zeros_like(img)
colored_mask[mask > 0] = color
cv2.addWeighted(img, 1.0, colored_mask, 0.4, 0, img)
return img
def _decode_rle(self, rle, height, width):
"""
Decode RLE (Run-Length Encoding) to binary mask.
"""
if isinstance(rle['counts'], list):
# Uncompressed RLE
counts = rle['counts']
mask = np.zeros(height * width, dtype=np.uint8)
pos = 0
val = 0
for count in counts:
mask[pos:pos+count] = val
pos += count
val = 1 - val
return mask.reshape((height, width))
else:
# Compressed RLE - would need pycocotools
print("Warning: Compressed RLE format requires pycocotools")
return np.zeros((height, width), dtype=np.uint8)
def _draw_bbox(self, img, bbox, color, label=None):
"""
Draw bounding box on the image.
COCO bbox format: [x, y, width, height]
Returns the modified image.
"""
x, y, w, h = map(int, bbox)
# Draw rectangle
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
# Draw label if provided
if label:
# Get text size for background
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.6
thickness = 2
(text_w, text_h), baseline = cv2.getTextSize(label, font, font_scale, thickness)
# Draw background rectangle for text
cv2.rectangle(img, (x, y - text_h - baseline - 5),
(x + text_w, y), color, -1)
# Draw text
cv2.putText(img, label, (x, y - baseline - 2), font,
font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
return img
def augment_dataset(
self,
dataset_path: str,
split: str = 'train',
augmentation_factor: int = 2,
rotation_angles: Optional[List[float]] = None,
intensity_range: Tuple[float, float] = (0.8, 1.2),
noise_sigma: float = 0.02,
combinations: bool = True,
output_suffix: str = '_aug',
seed: int = 42
) -> Dict[str, Any]:
"""
Augment a dataset with various transformations.
Creates augmented images and updates COCO annotations accordingly.
Args:
dataset_path: Path to the dataset directory
split: Split name to augment (default: 'train')
augmentation_factor: Number of augmented versions per image (default: 2)
rotation_angles: List of rotation angles in degrees. If None, uses random rotations
intensity_range: Range for intensity adjustment (min, max) as multipliers
noise_sigma: Standard deviation for Gaussian noise (0-1 range)
combinations: Whether to combine multiple augmentations
output_suffix: Suffix to add to augmented image filenames
seed: Random seed for reproducibility
Returns:
Dictionary containing augmentation statistics
"""
dataset_path = Path(dataset_path)
split_path = dataset_path / split
if not split_path.exists():
raise ValueError(f"Split '{split}' not found: {split_path}")
# Find annotation file
annotation_files = list(split_path.glob('*annotations*.json')) + list(split_path.glob('*.json'))
if not annotation_files:
raise ValueError(f"No COCO annotation file found in {split_path}")
annotation_path = annotation_files[0]
print(f"Using annotation file: {annotation_path.name}")
# Load COCO annotations
with open(annotation_path, 'r') as f:
coco_data = json.load(f)
# Set random seed
random.seed(seed)
np.random.seed(seed)
print(f"\n{'='*60}")
print(f"Data Augmentation for '{split}' split")
print(f"{'='*60}")
print(f"Original images: {len(coco_data['images'])}")
print(f"Augmentation factor: {augmentation_factor}")
print(f"Augmentation settings:")
print(f" - Rotations: {rotation_angles if rotation_angles else 'Random'}")
print(f" - Intensity range: {intensity_range}")
print(f" - Noise sigma: {noise_sigma}")
print(f" - Combinations: {combinations}")
# Track new images and annotations
new_images = []
new_annotations = []
next_image_id = max(img['id'] for img in coco_data['images']) + 1
next_ann_id = max(ann['id'] for ann in coco_data['annotations']) + 1
# Group annotations by image_id
annotations_by_image = {}
for ann in coco_data['annotations']:
img_id = ann['image_id']
if img_id not in annotations_by_image:
annotations_by_image[img_id] = []
annotations_by_image[img_id].append(ann)
# Augment each image
total_created = 0
for img_info in coco_data['images']:
img_path = self._find_image_file(str(split_path), img_info['file_name'])
if not img_path:
print(f"Warning: Image not found: {img_info['file_name']}")
continue
# Load image
img = cv2.imread(str(img_path))
if img is None:
print(f"Warning: Failed to load image: {img_info['file_name']}")
continue
# Get annotations for this image
img_annotations = annotations_by_image.get(img_info['id'], [])
# Create augmented versions
for aug_idx in range(augmentation_factor):
# Determine augmentation parameters
aug_params = self._get_augmentation_params(
rotation_angles, intensity_range, noise_sigma, combinations, aug_idx
)
# Apply augmentations
aug_img, aug_annotations = self._apply_augmentations(
img.copy(), img_annotations, img_info, aug_params
)
# Save augmented image
aug_filename = self._generate_aug_filename(
img_info['file_name'], aug_idx, output_suffix
)
aug_img_path = split_path / aug_filename
cv2.imwrite(str(aug_img_path), aug_img)
# Create new image info
new_img_info = img_info.copy()
new_img_info['id'] = next_image_id
new_img_info['file_name'] = aug_filename
new_images.append(new_img_info)
# Update annotation IDs and image_id
for ann in aug_annotations:
ann['id'] = next_ann_id
ann['image_id'] = next_image_id
new_annotations.append(ann)
next_ann_id += 1
next_image_id += 1
total_created += 1
print(f"\nCreated {total_created} augmented images")
print(f"Created {len(new_annotations)} augmented annotations")
# Update COCO data
coco_data['images'].extend(new_images)
coco_data['annotations'].extend(new_annotations)
# Save updated annotation file
with open(annotation_path, 'w') as f:
json.dump(coco_data, f, indent=2)
print(f"\nUpdated annotation file: {annotation_path}")
print(f"Total images now: {len(coco_data['images'])}")
print(f"Total annotations now: {len(coco_data['annotations'])}")
print(f"{'='*60}\n")
# Show updated statistics for the augmented split
print(f"Getting updated annotation statistics for '{split}' split...")
updated_stats = self.get_annotation_statistics(str(annotation_path), verbose=True)
# Also show statistics for other splits (e.g., validation)
dataset_path_obj = Path(dataset_path)
other_splits_stats = {}
for other_split in ['valid', 'val', 'test']:
if other_split != split:
other_split_path = dataset_path_obj / other_split
if other_split_path.exists():
other_ann_files = list(other_split_path.glob('*annotations*.json')) + list(other_split_path.glob('*.json'))
if other_ann_files:
print(f"\nGetting annotation statistics for '{other_split}' split...")
other_stats = self.get_annotation_statistics(str(other_ann_files[0]), verbose=True)
other_splits_stats[other_split] = other_stats
return {
'original_images': len(coco_data['images']) - len(new_images),
'augmented_images': len(new_images),
'total_images': len(coco_data['images']),
'augmented_annotations': len(new_annotations),
'total_annotations': len(coco_data['annotations']),
'updated_statistics': updated_stats,
'other_splits_statistics': other_splits_stats
}
def _get_augmentation_params(
self,
rotation_angles: Optional[List[float]],
intensity_range: Tuple[float, float],
noise_sigma: float,
combinations: bool,
aug_idx: int
) -> Dict[str, Any]:
"""Generate augmentation parameters for a single augmentation."""
params = {}
if combinations:
# Apply multiple augmentations
if rotation_angles:
params['rotation'] = rotation_angles[aug_idx % len(rotation_angles)]
else:
params['rotation'] = random.uniform(1, 359)
params['intensity'] = random.uniform(intensity_range[0], intensity_range[1])
params['noise'] = random.uniform(0, noise_sigma)
else:
# Apply single augmentation type in rotation
aug_type = aug_idx % 3
if aug_type == 0: # Rotation
if rotation_angles:
params['rotation'] = rotation_angles[aug_idx % len(rotation_angles)]
else:
params['rotation'] = random.uniform(1, 359)
elif aug_type == 1: # Intensity
params['intensity'] = random.uniform(intensity_range[0], intensity_range[1])
else: # Noise
params['noise'] = random.uniform(0, noise_sigma)
return params
def _apply_augmentations(
self,
img: np.ndarray,
annotations: List[Dict],
img_info: Dict,
params: Dict[str, Any]
) -> Tuple[np.ndarray, List[Dict]]:
"""Apply augmentations to image and annotations."""
height, width = img.shape[:2]
aug_annotations = []
# Apply rotation
if 'rotation' in params:
img, rotation_matrix = self._rotate_image(img, params['rotation'])
# Transform annotations
for ann in annotations:
aug_ann = ann.copy()
aug_ann = self._transform_annotation(aug_ann, rotation_matrix, width, height)
aug_annotations.append(aug_ann)
else:
aug_annotations = [ann.copy() for ann in annotations]
# Apply intensity adjustment
if 'intensity' in params:
img = self._adjust_intensity(img, params['intensity'])
# Apply noise
if 'noise' in params:
img = self._add_noise(img, params['noise'])
return img, aug_annotations
def _rotate_image(self, img: np.ndarray, angle: float) -> Tuple[np.ndarray, np.ndarray]:
"""
Rotate image around center while keeping the same size.
Returns rotated image and rotation matrix.
"""
height, width = img.shape[:2]
center = (width // 2, height // 2)
# Get rotation matrix
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
# Rotate image
rotated = cv2.warpAffine(
img, rotation_matrix, (width, height),
flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT
)
return rotated, rotation_matrix
def _adjust_intensity(self, img: np.ndarray, factor: float) -> np.ndarray:
"""
Adjust overall intensity of the image.
Factor > 1 increases brightness, < 1 decreases brightness.
"""
# Convert to float for precision
img_float = img.astype(np.float32)
# Adjust intensity
adjusted = img_float * factor
# Clip values to valid range
adjusted = np.clip(adjusted, 0, 255)
return adjusted.astype(np.uint8)
def _add_noise(self, img: np.ndarray, sigma: float) -> np.ndarray:
"""
Add Gaussian noise to the image.
Sigma is in the range [0, 1] relative to image intensity range.
"""
# Generate Gaussian noise
noise = np.random.normal(0, sigma * 255, img.shape)
# Add noise to image
noisy = img.astype(np.float32) + noise
# Clip values to valid range
noisy = np.clip(noisy, 0, 255)
return noisy.astype(np.uint8)
def _transform_annotation(
self,
annotation: Dict,
rotation_matrix: np.ndarray,
orig_width: int,
orig_height: int
) -> Dict:
"""Transform annotation (segmentation and bbox) using rotation matrix."""
# Transform segmentation polygons
if 'segmentation' in annotation and isinstance(annotation['segmentation'], list):
transformed_segs = []
for seg in annotation['segmentation']:
if len(seg) >= 6: # At least 3 points
# Reshape to points
points = np.array(seg).reshape(-1, 2)
# Transform points