make_calib_dataset.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. """从采集帧里生成 RKNN **INT8 量化校准集**(去重 + 抽样 + 归一尺寸 + ``dataset.txt``)。
  2. 为什么需要它:``scripts/onnx_to_rknn.py`` 的 ``--make-dataset`` 只是把目录里**每个文件**
  3. 列进 txt,不去重、不归一尺寸。现场采集(``--dump-frames``)一晚上会留下大量**同一帧的重复拷贝**
  4. (本轮实测 ``runs/`` 397 个文件去重后只有 165 张真实帧),直接拿去校准会让统计量偏向那些重复
  5. 场景,而且 640×480 的图与模型 640×640 输入也不一致。
  6. 用法::
  7. # 1) 台架/开发机:从 runs/ 造一个 200 张的校准集(默认写 PNG,纯标准库,不依赖 Pillow/cv2)
  8. python scripts/make_calib_dataset.py --src runs --limit 200 \
  9. --resize 640x640 --letterbox
  10. # 2) 打包上传(板端转换那台机器)
  11. tar czf calib.tgz -C runs calib_<时间戳>
  12. # 3) 板端转换(YOLOv8 必须钉 toolkit 2.3.2,见 requirements-rknn.txt)
  13. python scripts/onnx_to_rknn.py --onnx weights/yolov8n.onnx -o /tmp/yolov8n_int8.rknn \
  14. --target rk3588 --imgsz 640 --dataset /opt/portcv/runs/calib_<时间戳>/dataset.txt \
  15. --quantized-dtype w8a8
  16. # 4) 一定要验:cls cos / 框 IoU 不达标就别上板
  17. python scripts/verify_rknn.py --fp16 weights/yolov8n.rknn --int8 /tmp/yolov8n_int8.rknn
  18. 输出(都在 ``--out`` 下)::
  19. images/000001.png ... 归一后的校准图(默认 PNG,按需 ``--format jpg``)
  20. dataset.txt 每行一个**绝对路径**,直接喂 ``onnx_to_rknn.py --dataset``
  21. manifest.csv sha1, 源文件, 输出文件, 宽, 高, 字节数 —— 交付记录要能追溯
  22. summary.txt 本次造集的数字(扫描/去重/抽样),随验收记录归档
  23. 判据(本脚本只负责"造得对",精度由 ``verify_rknn.py`` 判):
  24. * 去重按**像素内容**算 sha1(同一帧存两个文件名只算一张);
  25. * 抽样按**来源目录轮转**(``runs/dump_a``、``runs/dump_b`` … 各取几张),避免某一批场景霸屏;
  26. * 200~500 张是经验区间:太少统计量不稳,太多只是拖长转换时间(13 min/次量级)。
  27. 只用标准库:PGM(P5/P6)自带解码,PNG 自带编码(zlib)。其它格式(JPG/PNG 输入)需要
  28. Pillow 或 OpenCV,装了就自动用,没装就跳过并计数,不会让整个流程失败。
  29. """
  30. from __future__ import annotations
  31. import argparse
  32. import csv
  33. import datetime as _dt
  34. import hashlib
  35. import os
  36. import struct
  37. import sys
  38. import zlib
  39. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  40. IMAGE_EXT = (".pgm", ".png", ".jpg", ".jpeg", ".bmp")
  41. PNG_SIG = b"\x89PNG\r\n\x1a\n"
  42. class ImageError(Exception):
  43. """读不出来 / 不支持的格式。"""
  44. def read_pgm(path: str):
  45. """读 PGM(P5 灰度 / P6 彩色),返回 ``(w, h, channels, pixels_bytes)``。"""
  46. with open(path, "rb") as fh:
  47. data = fh.read()
  48. if not data.startswith((b"P5", b"P6")):
  49. raise ImageError("不是 P5/P6 PGM:%s" % path)
  50. channels = 1 if data[1:2] == b"5" else 3
  51. pos = 2
  52. values = []
  53. while len(values) < 3:
  54. while pos < len(data) and data[pos:pos + 1].isspace():
  55. pos += 1
  56. if data[pos:pos + 1] == b"#": # 注释行
  57. while pos < len(data) and data[pos:pos + 1] not in (b"\n", b"\r"):
  58. pos += 1
  59. continue
  60. start = pos
  61. while pos < len(data) and not data[pos:pos + 1].isspace():
  62. pos += 1
  63. if start == pos:
  64. raise ImageError("PGM 头部损坏:%s" % path)
  65. values.append(int(data[start:pos]))
  66. pos += 1 # 头部与像素之间恰好一个空白
  67. width, height, maxval = values
  68. if maxval != 255:
  69. raise ImageError("只支持 8 位 PGM(maxval=255),得到 %d:%s" % (maxval, path))
  70. need = width * height * channels
  71. pixels = data[pos:pos + need]
  72. if len(pixels) != need:
  73. raise ImageError("PGM 像素不足:%s(%d/%d)" % (path, len(pixels), need))
  74. return width, height, channels, pixels
  75. def read_other(path: str):
  76. """非 PGM 输入:有 Pillow / OpenCV 就解码成 RGB,没有就抛 :class:`ImageError`。"""
  77. try: # Pillow
  78. from PIL import Image # type: ignore
  79. with Image.open(path) as img:
  80. img = img.convert("RGB")
  81. return img.size[0], img.size[1], 3, img.tobytes()
  82. except ImportError:
  83. pass
  84. try: # OpenCV(BGR → RGB)
  85. import cv2 # type: ignore
  86. img = cv2.imread(path, cv2.IMREAD_COLOR)
  87. if img is None:
  88. raise ImageError("OpenCV 读不出来:%s" % path)
  89. rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  90. return rgb.shape[1], rgb.shape[0], 3, rgb.tobytes()
  91. except ImportError:
  92. raise ImageError("读 %s 需要 Pillow 或 OpenCV(PGM 除外)" % path)
  93. def load_image(path: str):
  94. """统一入口:按魔数分派,返回 ``(w, h, channels, pixels)``。"""
  95. with open(path, "rb") as fh:
  96. magic = fh.read(2)
  97. if magic in (b"P5", b"P6"):
  98. return read_pgm(path)
  99. return read_other(path)
  100. def content_sha1(w: int, h: int, channels: int, pixels: bytes) -> str:
  101. """按**像素内容**算 sha1(同一帧存两个文件名 → 同一个哈希)。"""
  102. digest = hashlib.sha1()
  103. digest.update(("%dx%dx%d|" % (w, h, channels)).encode("ascii"))
  104. digest.update(pixels)
  105. return digest.hexdigest()
  106. def resize(w: int, h: int, channels: int, pixels: bytes, tw: int, th: int,
  107. letterbox: bool = False, pad: int = 114):
  108. """双线性缩放到 ``(tw, th)``;``letterbox`` 时保持长宽比并用 ``pad`` 填充。"""
  109. if (tw, th) == (w, h):
  110. return w, h, pixels
  111. if letterbox:
  112. scale = min(tw / float(w), th / float(h))
  113. nw = max(1, int(round(w * scale)))
  114. nh = max(1, int(round(h * scale)))
  115. else:
  116. nw, nh = tw, th
  117. scaled = _bilinear(w, h, channels, pixels, nw, nh)
  118. if (nw, nh) == (tw, th):
  119. return tw, th, scaled
  120. canvas = bytearray([pad]) * (tw * th * channels)
  121. x0 = (tw - nw) // 2
  122. y0 = (th - nh) // 2
  123. row_bytes = nw * channels
  124. for y in range(nh):
  125. src = y * row_bytes
  126. dst = ((y0 + y) * tw + x0) * channels
  127. canvas[dst:dst + row_bytes] = scaled[src:src + row_bytes]
  128. return tw, th, bytes(canvas)
  129. def _bilinear(w: int, h: int, channels: int, pixels: bytes, nw: int, nh: int) -> bytes:
  130. """双线性缩放。有 numpy 走向量化(960×540→640×360 约 3 ms),没有就纯 Python 兜底。"""
  131. x_ratio = (w - 1) / float(max(1, nw - 1)) if nw > 1 else 0.0
  132. y_ratio = (h - 1) / float(max(1, nh - 1)) if nh > 1 else 0.0
  133. try:
  134. import numpy as np # type: ignore
  135. except ImportError:
  136. np = None
  137. if np is not None:
  138. arr = np.frombuffer(pixels, dtype=np.uint8)
  139. arr = arr.reshape((h, w, channels) if channels > 1 else (h, w))
  140. ys = np.clip(np.arange(nh, dtype=np.float32) * y_ratio, 0, h - 1)
  141. xs = np.clip(np.arange(nw, dtype=np.float32) * x_ratio, 0, w - 1)
  142. y0 = ys.astype(np.intp)
  143. x0 = xs.astype(np.intp)
  144. y1 = np.minimum(y0 + 1, h - 1)
  145. x1 = np.minimum(x0 + 1, w - 1)
  146. fy = (ys - y0).astype(np.float32)
  147. fx = (xs - x0).astype(np.float32)
  148. if channels > 1:
  149. fy, fx = fy[:, None, None], fx[None, :, None]
  150. else:
  151. fy, fx = fy[:, None], fx[None, :]
  152. top = arr[y0][:, x0].astype(np.float32) * (1 - fx) + arr[y0][:, x1].astype(np.float32) * fx
  153. bot = arr[y1][:, x0].astype(np.float32) * (1 - fx) + arr[y1][:, x1].astype(np.float32) * fx
  154. return (top * (1 - fy) + bot * fy + 0.5).astype(np.uint8).tobytes()
  155. out = bytearray(nw * nh * channels)
  156. for y in range(nh):
  157. sy = y * y_ratio
  158. y0 = int(sy)
  159. y1 = min(h - 1, y0 + 1)
  160. fy = sy - y0
  161. row0 = y0 * w * channels
  162. row1 = y1 * w * channels
  163. dst = y * nw * channels
  164. for x in range(nw):
  165. sx = x * x_ratio
  166. x0 = int(sx)
  167. x1 = min(w - 1, x0 + 1)
  168. fx = sx - x0
  169. a = row0 + x0 * channels
  170. b = row0 + x1 * channels
  171. c = row1 + x0 * channels
  172. d = row1 + x1 * channels
  173. for ch in range(channels):
  174. top = pixels[a + ch] * (1 - fx) + pixels[b + ch] * fx
  175. bot = pixels[c + ch] * (1 - fx) + pixels[d + ch] * fx
  176. out[dst + x * channels + ch] = int(top * (1 - fy) + bot * fy + 0.5)
  177. return bytes(out)
  178. def write_png(path: str, w: int, h: int, channels: int, pixels: bytes) -> None:
  179. """写 8 位灰度/彩色 PNG(filter=0,纯 zlib;不依赖 Pillow)。"""
  180. color_type = 0 if channels == 1 else 2
  181. stride = w * channels
  182. raw = bytearray()
  183. for y in range(h):
  184. raw.append(0) # 每行 filter type = 0
  185. raw += pixels[y * stride:(y + 1) * stride]
  186. def chunk(tag: bytes, payload: bytes) -> bytes:
  187. return (struct.pack(">I", len(payload)) + tag + payload
  188. + struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF))
  189. ihdr = struct.pack(">IIBBBBB", w, h, 8, color_type, 0, 0, 0)
  190. with open(path, "wb") as fh:
  191. fh.write(PNG_SIG + chunk(b"IHDR", ihdr)
  192. + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b""))
  193. def write_jpg(path: str, w: int, h: int, channels: int, pixels: bytes, quality: int) -> None:
  194. """写 JPEG(需要 Pillow 或 OpenCV;都没有就抛 :class:`ImageError`)。"""
  195. try:
  196. from PIL import Image # type: ignore
  197. mode = "L" if channels == 1 else "RGB"
  198. Image.frombytes(mode, (w, h), pixels).save(path, quality=int(quality))
  199. return
  200. except ImportError:
  201. pass
  202. try:
  203. import cv2 # type: ignore
  204. import numpy as np # type: ignore
  205. flat = np.frombuffer(pixels, dtype=np.uint8)
  206. arr = flat.reshape((h, w)) if channels == 1 else flat.reshape((h, w, channels))
  207. img = arr if channels == 1 else cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
  208. if not cv2.imwrite(path, img, [int(cv2.IMWRITE_JPEG_QUALITY), int(quality)]):
  209. raise ImageError("cv2.imwrite 失败:%s" % path)
  210. return
  211. except ImportError:
  212. raise ImageError("--format jpg 需要 Pillow 或 OpenCV;本机都没有,请用 --format png")
  213. # --------------------------------------------------------------------------- 扫描 / 抽样
  214. def iter_images(src: str, exts=IMAGE_EXT):
  215. """递归列出 ``src`` 下的候选图片(排序,保证可复现)。"""
  216. found = []
  217. for root, _dirs, files in os.walk(src):
  218. for name in files:
  219. if name.lower().endswith(tuple(exts)):
  220. found.append(os.path.join(root, name))
  221. return sorted(found)
  222. def scan(src: str, dedupe: bool = True) -> dict:
  223. """解码 + 去重,返回 ``{"groups": {目录: [frame...]}, "stats": {...}}``。
  224. frame = ``{path, w, h, channels, pixels, sha1}``;去重后**保留首次出现的那张**
  225. (``iter_images`` 有序,所以结果可复现)。
  226. """
  227. stats = {"scanned": 0, "decoded": 0, "failed": 0, "dup": 0, "uniq": 0}
  228. groups: dict = {}
  229. seen: dict = {}
  230. for path in iter_images(src):
  231. stats["scanned"] += 1
  232. try:
  233. w, h, channels, pixels = load_image(path)
  234. except (ImageError, OSError, ValueError):
  235. stats["failed"] += 1
  236. continue
  237. stats["decoded"] += 1
  238. sha = content_sha1(w, h, channels, pixels)
  239. if dedupe and sha in seen:
  240. stats["dup"] += 1
  241. continue
  242. seen[sha] = path
  243. group = os.path.dirname(os.path.relpath(path, src)) or "."
  244. groups.setdefault(group, []).append(
  245. {"path": path, "w": w, "h": h, "channels": channels, "pixels": pixels, "sha1": sha})
  246. stats["uniq"] = sum(len(v) for v in groups.values())
  247. return {"groups": groups, "stats": stats}
  248. def pick(groups: dict, limit: int) -> list:
  249. """按来源目录**轮转**抽样:每个目录各取一张,循环直到够数(``limit<=0`` 表示全取)。"""
  250. if limit <= 0:
  251. return [f for key in sorted(groups) for f in groups[key]]
  252. order = sorted(groups)
  253. queues = [list(groups[key]) for key in order]
  254. out: list = []
  255. while len(out) < limit and any(queues):
  256. for queue in queues:
  257. if not queue:
  258. continue
  259. out.append(queue.pop(0))
  260. if len(out) >= limit:
  261. break
  262. return out
  263. def build(src: str, out: str, limit: int = 200, resize_to: str = "", letterbox: bool = False,
  264. pad: int = 114, fmt: str = "png", quality: int = 88, dedupe: bool = True,
  265. dataset_name: str = "dataset.txt", quiet: bool = False) -> int:
  266. """造集主流程;返回进程退出码(0 成功 / 2 没有可用图片 / 3 输出格式不可用)。"""
  267. target = None
  268. if resize_to:
  269. try:
  270. tw, th = [int(part) for part in resize_to.lower().split("x")]
  271. except ValueError:
  272. print("--resize 需要 WxH 形式(如 640x640),得到 %r" % resize_to, file=sys.stderr)
  273. return 2
  274. if tw <= 0 or th <= 0 or tw % 32 or th % 32:
  275. print("--resize 的宽高必须是 32 的正整数倍(RKNN 输入对齐),得到 %dx%d" % (tw, th),
  276. file=sys.stderr)
  277. return 2
  278. target = (tw, th)
  279. result = scan(src, dedupe=dedupe)
  280. stats = result["stats"]
  281. frames = pick(result["groups"], limit)
  282. if not frames:
  283. print("没有可用图片:扫描 %d,解码失败 %d(--src 指对了吗?)"
  284. % (stats["scanned"], stats["failed"]), file=sys.stderr)
  285. return 2
  286. img_dir = os.path.join(out, "images")
  287. os.makedirs(img_dir, exist_ok=True)
  288. rows = []
  289. for idx, frame in enumerate(frames, 1):
  290. w, h, ch, px = frame["w"], frame["h"], frame["channels"], frame["pixels"]
  291. if target is not None:
  292. w, h, px = resize(w, h, ch, px, target[0], target[1],
  293. letterbox=letterbox, pad=pad)
  294. dst = os.path.abspath(os.path.join(img_dir, "%06d.%s" % (idx, fmt)))
  295. try:
  296. if fmt == "jpg":
  297. write_jpg(dst, w, h, ch, px, quality)
  298. else:
  299. write_png(dst, w, h, ch, px)
  300. except ImageError as exc:
  301. print(str(exc), file=sys.stderr)
  302. return 3
  303. rows.append({"sha1": frame["sha1"], "src": frame["path"], "out": dst,
  304. "width": w, "height": h, "bytes": os.path.getsize(dst)})
  305. dataset = os.path.abspath(os.path.join(out, dataset_name))
  306. with open(dataset, "w", encoding="utf-8") as fh:
  307. for row in rows:
  308. fh.write(row["out"] + "\n")
  309. manifest = os.path.abspath(os.path.join(out, "manifest.csv"))
  310. with open(manifest, "w", newline="", encoding="utf-8") as fh:
  311. writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
  312. writer.writeheader()
  313. writer.writerows(rows)
  314. total_mb = sum(row["bytes"] for row in rows) / 1048576.0
  315. size_note = ("原尺寸 %dx%d" % (rows[0]["width"], rows[0]["height"])) if target is None \
  316. else ("%dx%d%s" % (target[0], target[1],
  317. " letterbox(pad=%d)" % pad if letterbox else " 拉伸"))
  318. summary = [
  319. "INT8 校准集构建摘要",
  320. " 来源: %s" % os.path.abspath(src),
  321. " 扫描: %d 个文件 → 解码成功 %d / 失败 %d" % (stats["scanned"], stats["decoded"],
  322. stats["failed"]),
  323. " 去重: %s(唯一 %d 张)" % ("丢重复 %d 个" % stats["dup"] if dedupe else "未去重",
  324. stats["uniq"]),
  325. " 抽样: %d 张(按来源目录轮转;目录 %d 个)" % (len(rows), len(result["groups"])),
  326. " 尺寸: %s;格式 %s" % (size_note, fmt),
  327. " 写盘: %s(%.1f MB,平均 %.0f KB/张)" % (img_dir, total_mb,
  328. total_mb * 1024.0 / max(1, len(rows))),
  329. " dataset.txt: %s(%d 行绝对路径)" % (dataset, len(rows)),
  330. " manifest.csv: %s" % manifest,
  331. "",
  332. "下一步(在装好 rknn-toolkit2 2.3.2 的机器上):",
  333. " python scripts/onnx_to_rknn.py --onnx weights/yolov8n.onnx -o /tmp/yolov8n_int8.rknn "
  334. "--target rk3588 --imgsz %d --dataset %s --quantized-dtype w8a8"
  335. % (target[0] if target else 640, dataset),
  336. " python scripts/verify_rknn.py --fp16 weights/demo/yolov8n.rknn --int8 /tmp/yolov8n_int8.rknn",
  337. ]
  338. text = "\n".join(summary) + "\n"
  339. with open(os.path.abspath(os.path.join(out, "summary.txt")), "w", encoding="utf-8") as fh:
  340. fh.write(text)
  341. if not quiet:
  342. print(text)
  343. return 0
  344. def main(argv=None) -> int:
  345. parser = argparse.ArgumentParser(
  346. description="从采集帧生成 RKNN INT8 校准集(去重 + 抽样 + 归一尺寸 + dataset.txt)")
  347. parser.add_argument("--src", default=os.path.join(REPO, "runs"),
  348. help="采集帧目录(递归;默认 runs)")
  349. parser.add_argument("--out", default=None, help="输出目录;默认 runs/calib_<时间戳>")
  350. parser.add_argument("--limit", type=int, default=200,
  351. help="最多取多少张(按目录轮转;0=全取;经验 200~500)")
  352. parser.add_argument("--resize", default="", help="归一尺寸 WxH(32 的倍数,如 640x640)")
  353. parser.add_argument("--letterbox", action="store_true",
  354. help="等比缩放 + 居中填充(与生产预处理一致,推荐)")
  355. parser.add_argument("--pad", type=int, default=114, help="letterbox 填充灰度(默认 114)")
  356. parser.add_argument("--format", dest="fmt", default="png", choices=("png", "jpg"),
  357. help="输出格式(png 纯标准库;jpg 需要 Pillow/OpenCV)")
  358. parser.add_argument("--quality", type=int, default=88, help="jpg 质量(默认 88)")
  359. parser.add_argument("--no-dedupe", dest="dedupe", action="store_false",
  360. help="不去重(默认按像素内容去重)")
  361. parser.add_argument("--dataset-name", default="dataset.txt", help="列表文件名")
  362. parser.add_argument("-q", "--quiet", action="store_true", help="不打印摘要")
  363. args = parser.parse_args(argv)
  364. if args.letterbox and not args.resize:
  365. parser.error("--letterbox 需要同时给 --resize WxH")
  366. out = args.out or os.path.join(REPO, "runs",
  367. "calib_" + _dt.datetime.now().strftime("%Y%m%d_%H%M%S"))
  368. return build(args.src, out, limit=args.limit, resize_to=args.resize,
  369. letterbox=args.letterbox, pad=args.pad, fmt=args.fmt, quality=args.quality,
  370. dedupe=args.dedupe, dataset_name=args.dataset_name, quiet=args.quiet)
  371. if __name__ == "__main__":
  372. raise SystemExit(main())