yolo_detect / instances.py
Shreypai's picture
Upload folder using huggingface_hub (part 12)
bd933bd verified
Raw History Blame Contribute Delete
1.74 kB
import os
from collections import Counter
def count_instances(label_dir):
counts = Counter()
for fname in os.listdir(label_dir):
if fname.endswith(".txt"):
with open(os.path.join(label_dir, fname)) as f:
for line in f:
if line.strip():
cls_id = line.strip().split()[0]
counts[cls_id] += 1
return counts
# ------------------------- CONFIG (edit these) -------------------------
TRAIN_LABELS = r"C:\Users\shrey\Downloads\dataset\labels\train"
VAL_LABELS = r"C:\Users\shrey\Downloads\dataset\labels\val"
TEST_LABELS = r"C:\Users\shrey\Downloads\dataset\labels\test"
# Map class IDs to names for readable output -- confirm against your data.yaml
CLASS_NAMES = {
"0": "plastic_bottle",
"1": "drink_can",
"2": "paper",
}
# -------------------------------------------------------------------------
def print_counts(label, counts):
print(f"{label}:")
total = sum(counts.values())
for cls_id in sorted(counts.keys()):
name = CLASS_NAMES.get(cls_id, f"class_{cls_id}")
pct = (counts[cls_id] / total * 100) if total else 0
print(f" {name:15s} (id {cls_id}): {counts[cls_id]:5d} ({pct:.1f}%)")
print(f" {'TOTAL':15s} : {total:5d}\n")
if __name__ == "__main__":
for label_name, label_dir in [
("Train", TRAIN_LABELS),
("Val", VAL_LABELS),
("Test", TEST_LABELS),
]:
if os.path.isdir(label_dir):
counts = count_instances(label_dir)
print_counts(label_name, counts)
else:
print(f"Skipping {label_name} -- folder not found: {label_dir}\n")