File size: 3,585 Bytes
93efe93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

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()