yolo_detect / relabel.py
Shreypai's picture
Upload folder using huggingface_hub (part 17)
93efe93 verified
Raw History Blame Contribute Delete
3.59 kB
"""
Relabel all label files belonging to images whose filename starts with
"AluCan" so every bounding box in those files uses the correct class ID
(drink_can), regardless of what class ID they currently have.
Use case: filenames like AluCan67.jpg were found to have been mislabeled
as plastic_bottle in their .txt files. Since the filename itself reliably
tells you the true class, this script fixes all of them in one pass.
IMPORTANT:
- This assumes EVERY box in an AluCan*.txt file should be drink_can.
If any AluCan* image legitimately also contains a bottle or paper
in the same frame, this script will wrongly relabel those boxes too.
Spot-check a few multi-object AluCan images before trusting this blindly.
- Run this on train, val, and test label folders separately (or all at once
by listing multiple label dirs below).
- Always back up your labels folder before running, or run with DRY_RUN=True
first to preview changes without writing anything.
"""
import os
import shutil
# ------------------------- CONFIG (edit these) -------------------------
LABEL_DIRS = [
r"C:\Users\shrey\Downloads\dataset\labels\train"
]
FILENAME_PREFIX = "hardneg_can_PET" # match filenames starting with this (case-sensitive)
CORRECT_CLASS_ID = "0" # confirm this against your data.yaml -> drink_can's index
DRY_RUN = False # set to False once you've checked the preview and are confident
BACKUP_SUFFIX = ".bak" # backup extension, only used if DRY_RUN is False
# -------------------------------------------------------------------------
def relabel_file(path, correct_id, dry_run):
with open(path) as f:
lines = [line.strip() for line in f if line.strip()]
changed_lines = []
changed_count = 0
for line in lines:
parts = line.split()
if not parts:
continue
old_id = parts[0]
if old_id != correct_id:
changed_count += 1
parts[0] = correct_id
changed_lines.append(" ".join(parts))
if changed_count == 0:
return 0 # nothing to change in this file
if dry_run:
print(f"[DRY RUN] Would fix {changed_count} line(s) in: {path}")
else:
# backup original before overwriting
shutil.copy(path, path + BACKUP_SUFFIX)
with open(path, "w") as f:
f.write("\n".join(changed_lines) + "\n")
print(f"Fixed {changed_count} line(s) in: {path}")
return changed_count
def main():
total_files_touched = 0
total_lines_changed = 0
for label_dir in LABEL_DIRS:
if not os.path.isdir(label_dir):
print(f"Skipping (not found): {label_dir}")
continue
for fname in os.listdir(label_dir):
if fname.endswith(".txt") and fname.startswith(FILENAME_PREFIX):
path = os.path.join(label_dir, fname)
changed = relabel_file(path, CORRECT_CLASS_ID, DRY_RUN)
if changed:
total_files_touched += 1
total_lines_changed += changed
mode = "DRY RUN -- no files were modified" if DRY_RUN else "LIVE -- files were modified (backups saved as .bak)"
print(f"\nDone ({mode}).")
print(f"Files touched: {total_files_touched}")
print(f"Total lines relabeled: {total_lines_changed}")
if DRY_RUN:
print("\nReview the output above. If it looks correct, set DRY_RUN = False and rerun.")
if __name__ == "__main__":
main()