| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- """把 web_cc 按业务类别重组:敞车 / 平车 / 其他(棚车负样本)。
- 重命名规则:车型_001.jpg、车型_002.jpg ...
- 例:C70E_001.jpg、X70_001.jpg、P62_001.jpg
- - 敞车(状态1):C64, C64K, C70, C70E, C70H, C80
- - 平车(状态2):X70, NX70, X160
- - 其他(状态0负样本):P62, P64
- 同步更新 LICENSES.csv 与 analysis.csv 中的文件名/路径。
- 用法:python scripts/organize_web_cc.py
- """
- from __future__ import annotations
- import csv
- import os
- import shutil
- import sys
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- BASE = os.path.join(ROOT, "dataset", "web_cc")
- GROUPS = {
- "敞车": ["C70E", "C70H", "C70", "C64K", "C64", "C80"],
- "平车": ["NX70", "X70", "X160"],
- "其他": ["P62", "P64"],
- }
- TYPE2GROUP = {t: g for g, types in GROUPS.items() for t in types}
- EXTS = (".jpg", ".jpeg", ".png")
- def main() -> int:
- moved = {} # old basename -> new rel path
- for group, types in GROUPS.items():
- gdir = os.path.join(BASE, group)
- os.makedirs(gdir, exist_ok=True)
- for t in types:
- src_dir = os.path.join(BASE, t)
- if not os.path.isdir(src_dir):
- continue
- files = sorted(f for f in os.listdir(src_dir) if f.lower().endswith(EXTS))
- for i, f in enumerate(files, 1):
- ext = os.path.splitext(f)[1].lower()
- new_name = "%s_%03d%s" % (t, i, ext)
- src = os.path.join(src_dir, f)
- dst = os.path.join(gdir, new_name)
- if os.path.abspath(src) != os.path.abspath(dst):
- shutil.move(src, dst)
- moved[f] = os.path.join(group, new_name).replace("\\", "/")
- print("%-10s -> %s/%s" % (f[:10], group, new_name), file=sys.stderr)
- if not os.listdir(src_dir):
- os.rmdir(src_dir)
- # 同步 LICENSES.csv
- lic_path = os.path.join(BASE, "LICENSES.csv")
- if os.path.isfile(lic_path):
- with open(lic_path, encoding="utf-8-sig") as fh:
- rows = list(csv.DictReader(fh))
- for r in rows:
- old = os.path.basename(r["url"])
- # 从 title 提取原文件名更可靠
- title = r.get("title", "")
- old_name = title[5:] if title.lower().startswith("file:") else title
- r["organized_path"] = moved.get(old_name, "")
- with open(lic_path, "w", newline="", encoding="utf-8-sig") as fh:
- w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
- w.writeheader()
- w.writerows(rows)
- # 同步 analysis.csv
- ana_path = os.path.join(BASE, "analysis.csv")
- if os.path.isfile(ana_path):
- with open(ana_path, encoding="utf-8-sig") as fh:
- rows = list(csv.DictReader(fh))
- for r in rows:
- r["organized_path"] = moved.get(r["file"], "")
- with open(ana_path, "w", newline="", encoding="utf-8-sig") as fh:
- w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
- w.writeheader()
- w.writerows(rows)
- print("moved %d files" % len(moved))
- for g in GROUPS:
- n = len([f for f in os.listdir(os.path.join(BASE, g)) if f.lower().endswith(EXTS)])
- print(" %s: %d" % (g, n))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|