"""从采集帧里生成 RKNN **INT8 量化校准集**(去重 + 抽样 + 归一尺寸 + ``dataset.txt``)。 为什么需要它:``scripts/onnx_to_rknn.py`` 的 ``--make-dataset`` 只是把目录里**每个文件** 列进 txt,不去重、不归一尺寸。现场采集(``--dump-frames``)一晚上会留下大量**同一帧的重复拷贝** (本轮实测 ``runs/`` 397 个文件去重后只有 165 张真实帧),直接拿去校准会让统计量偏向那些重复 场景,而且 640×480 的图与模型 640×640 输入也不一致。 用法:: # 1) 台架/开发机:从 runs/ 造一个 200 张的校准集(默认写 PNG,纯标准库,不依赖 Pillow/cv2) python scripts/make_calib_dataset.py --src runs --limit 200 \ --resize 640x640 --letterbox # 2) 打包上传(板端转换那台机器) tar czf calib.tgz -C runs calib_<时间戳> # 3) 板端转换(YOLOv8 必须钉 toolkit 2.3.2,见 requirements-rknn.txt) python scripts/onnx_to_rknn.py --onnx weights/yolov8n.onnx -o /tmp/yolov8n_int8.rknn \ --target rk3588 --imgsz 640 --dataset /opt/portcv/runs/calib_<时间戳>/dataset.txt \ --quantized-dtype w8a8 # 4) 一定要验:cls cos / 框 IoU 不达标就别上板 python scripts/verify_rknn.py --fp16 weights/yolov8n.rknn --int8 /tmp/yolov8n_int8.rknn 输出(都在 ``--out`` 下):: images/000001.png ... 归一后的校准图(默认 PNG,按需 ``--format jpg``) dataset.txt 每行一个**绝对路径**,直接喂 ``onnx_to_rknn.py --dataset`` manifest.csv sha1, 源文件, 输出文件, 宽, 高, 字节数 —— 交付记录要能追溯 summary.txt 本次造集的数字(扫描/去重/抽样),随验收记录归档 判据(本脚本只负责"造得对",精度由 ``verify_rknn.py`` 判): * 去重按**像素内容**算 sha1(同一帧存两个文件名只算一张); * 抽样按**来源目录轮转**(``runs/dump_a``、``runs/dump_b`` … 各取几张),避免某一批场景霸屏; * 200~500 张是经验区间:太少统计量不稳,太多只是拖长转换时间(13 min/次量级)。 只用标准库:PGM(P5/P6)自带解码,PNG 自带编码(zlib)。其它格式(JPG/PNG 输入)需要 Pillow 或 OpenCV,装了就自动用,没装就跳过并计数,不会让整个流程失败。 """ from __future__ import annotations import argparse import csv import datetime as _dt import hashlib import os import struct import sys import zlib REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) IMAGE_EXT = (".pgm", ".png", ".jpg", ".jpeg", ".bmp") PNG_SIG = b"\x89PNG\r\n\x1a\n" class ImageError(Exception): """读不出来 / 不支持的格式。""" def read_pgm(path: str): """读 PGM(P5 灰度 / P6 彩色),返回 ``(w, h, channels, pixels_bytes)``。""" with open(path, "rb") as fh: data = fh.read() if not data.startswith((b"P5", b"P6")): raise ImageError("不是 P5/P6 PGM:%s" % path) channels = 1 if data[1:2] == b"5" else 3 pos = 2 values = [] while len(values) < 3: while pos < len(data) and data[pos:pos + 1].isspace(): pos += 1 if data[pos:pos + 1] == b"#": # 注释行 while pos < len(data) and data[pos:pos + 1] not in (b"\n", b"\r"): pos += 1 continue start = pos while pos < len(data) and not data[pos:pos + 1].isspace(): pos += 1 if start == pos: raise ImageError("PGM 头部损坏:%s" % path) values.append(int(data[start:pos])) pos += 1 # 头部与像素之间恰好一个空白 width, height, maxval = values if maxval != 255: raise ImageError("只支持 8 位 PGM(maxval=255),得到 %d:%s" % (maxval, path)) need = width * height * channels pixels = data[pos:pos + need] if len(pixels) != need: raise ImageError("PGM 像素不足:%s(%d/%d)" % (path, len(pixels), need)) return width, height, channels, pixels def read_other(path: str): """非 PGM 输入:有 Pillow / OpenCV 就解码成 RGB,没有就抛 :class:`ImageError`。""" try: # Pillow from PIL import Image # type: ignore with Image.open(path) as img: img = img.convert("RGB") return img.size[0], img.size[1], 3, img.tobytes() except ImportError: pass try: # OpenCV(BGR → RGB) import cv2 # type: ignore img = cv2.imread(path, cv2.IMREAD_COLOR) if img is None: raise ImageError("OpenCV 读不出来:%s" % path) rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return rgb.shape[1], rgb.shape[0], 3, rgb.tobytes() except ImportError: raise ImageError("读 %s 需要 Pillow 或 OpenCV(PGM 除外)" % path) def load_image(path: str): """统一入口:按魔数分派,返回 ``(w, h, channels, pixels)``。""" with open(path, "rb") as fh: magic = fh.read(2) if magic in (b"P5", b"P6"): return read_pgm(path) return read_other(path) def content_sha1(w: int, h: int, channels: int, pixels: bytes) -> str: """按**像素内容**算 sha1(同一帧存两个文件名 → 同一个哈希)。""" digest = hashlib.sha1() digest.update(("%dx%dx%d|" % (w, h, channels)).encode("ascii")) digest.update(pixels) return digest.hexdigest() def resize(w: int, h: int, channels: int, pixels: bytes, tw: int, th: int, letterbox: bool = False, pad: int = 114): """双线性缩放到 ``(tw, th)``;``letterbox`` 时保持长宽比并用 ``pad`` 填充。""" if (tw, th) == (w, h): return w, h, pixels if letterbox: scale = min(tw / float(w), th / float(h)) nw = max(1, int(round(w * scale))) nh = max(1, int(round(h * scale))) else: nw, nh = tw, th scaled = _bilinear(w, h, channels, pixels, nw, nh) if (nw, nh) == (tw, th): return tw, th, scaled canvas = bytearray([pad]) * (tw * th * channels) x0 = (tw - nw) // 2 y0 = (th - nh) // 2 row_bytes = nw * channels for y in range(nh): src = y * row_bytes dst = ((y0 + y) * tw + x0) * channels canvas[dst:dst + row_bytes] = scaled[src:src + row_bytes] return tw, th, bytes(canvas) def _bilinear(w: int, h: int, channels: int, pixels: bytes, nw: int, nh: int) -> bytes: """双线性缩放。有 numpy 走向量化(960×540→640×360 约 3 ms),没有就纯 Python 兜底。""" x_ratio = (w - 1) / float(max(1, nw - 1)) if nw > 1 else 0.0 y_ratio = (h - 1) / float(max(1, nh - 1)) if nh > 1 else 0.0 try: import numpy as np # type: ignore except ImportError: np = None if np is not None: arr = np.frombuffer(pixels, dtype=np.uint8) arr = arr.reshape((h, w, channels) if channels > 1 else (h, w)) ys = np.clip(np.arange(nh, dtype=np.float32) * y_ratio, 0, h - 1) xs = np.clip(np.arange(nw, dtype=np.float32) * x_ratio, 0, w - 1) y0 = ys.astype(np.intp) x0 = xs.astype(np.intp) y1 = np.minimum(y0 + 1, h - 1) x1 = np.minimum(x0 + 1, w - 1) fy = (ys - y0).astype(np.float32) fx = (xs - x0).astype(np.float32) if channels > 1: fy, fx = fy[:, None, None], fx[None, :, None] else: fy, fx = fy[:, None], fx[None, :] top = arr[y0][:, x0].astype(np.float32) * (1 - fx) + arr[y0][:, x1].astype(np.float32) * fx bot = arr[y1][:, x0].astype(np.float32) * (1 - fx) + arr[y1][:, x1].astype(np.float32) * fx return (top * (1 - fy) + bot * fy + 0.5).astype(np.uint8).tobytes() out = bytearray(nw * nh * channels) for y in range(nh): sy = y * y_ratio y0 = int(sy) y1 = min(h - 1, y0 + 1) fy = sy - y0 row0 = y0 * w * channels row1 = y1 * w * channels dst = y * nw * channels for x in range(nw): sx = x * x_ratio x0 = int(sx) x1 = min(w - 1, x0 + 1) fx = sx - x0 a = row0 + x0 * channels b = row0 + x1 * channels c = row1 + x0 * channels d = row1 + x1 * channels for ch in range(channels): top = pixels[a + ch] * (1 - fx) + pixels[b + ch] * fx bot = pixels[c + ch] * (1 - fx) + pixels[d + ch] * fx out[dst + x * channels + ch] = int(top * (1 - fy) + bot * fy + 0.5) return bytes(out) def write_png(path: str, w: int, h: int, channels: int, pixels: bytes) -> None: """写 8 位灰度/彩色 PNG(filter=0,纯 zlib;不依赖 Pillow)。""" color_type = 0 if channels == 1 else 2 stride = w * channels raw = bytearray() for y in range(h): raw.append(0) # 每行 filter type = 0 raw += pixels[y * stride:(y + 1) * stride] def chunk(tag: bytes, payload: bytes) -> bytes: return (struct.pack(">I", len(payload)) + tag + payload + struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF)) ihdr = struct.pack(">IIBBBBB", w, h, 8, color_type, 0, 0, 0) with open(path, "wb") as fh: fh.write(PNG_SIG + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b"")) def write_jpg(path: str, w: int, h: int, channels: int, pixels: bytes, quality: int) -> None: """写 JPEG(需要 Pillow 或 OpenCV;都没有就抛 :class:`ImageError`)。""" try: from PIL import Image # type: ignore mode = "L" if channels == 1 else "RGB" Image.frombytes(mode, (w, h), pixels).save(path, quality=int(quality)) return except ImportError: pass try: import cv2 # type: ignore import numpy as np # type: ignore flat = np.frombuffer(pixels, dtype=np.uint8) arr = flat.reshape((h, w)) if channels == 1 else flat.reshape((h, w, channels)) img = arr if channels == 1 else cv2.cvtColor(arr, cv2.COLOR_RGB2BGR) if not cv2.imwrite(path, img, [int(cv2.IMWRITE_JPEG_QUALITY), int(quality)]): raise ImageError("cv2.imwrite 失败:%s" % path) return except ImportError: raise ImageError("--format jpg 需要 Pillow 或 OpenCV;本机都没有,请用 --format png") # --------------------------------------------------------------------------- 扫描 / 抽样 def iter_images(src: str, exts=IMAGE_EXT): """递归列出 ``src`` 下的候选图片(排序,保证可复现)。""" found = [] for root, _dirs, files in os.walk(src): for name in files: if name.lower().endswith(tuple(exts)): found.append(os.path.join(root, name)) return sorted(found) def scan(src: str, dedupe: bool = True) -> dict: """解码 + 去重,返回 ``{"groups": {目录: [frame...]}, "stats": {...}}``。 frame = ``{path, w, h, channels, pixels, sha1}``;去重后**保留首次出现的那张** (``iter_images`` 有序,所以结果可复现)。 """ stats = {"scanned": 0, "decoded": 0, "failed": 0, "dup": 0, "uniq": 0} groups: dict = {} seen: dict = {} for path in iter_images(src): stats["scanned"] += 1 try: w, h, channels, pixels = load_image(path) except (ImageError, OSError, ValueError): stats["failed"] += 1 continue stats["decoded"] += 1 sha = content_sha1(w, h, channels, pixels) if dedupe and sha in seen: stats["dup"] += 1 continue seen[sha] = path group = os.path.dirname(os.path.relpath(path, src)) or "." groups.setdefault(group, []).append( {"path": path, "w": w, "h": h, "channels": channels, "pixels": pixels, "sha1": sha}) stats["uniq"] = sum(len(v) for v in groups.values()) return {"groups": groups, "stats": stats} def pick(groups: dict, limit: int) -> list: """按来源目录**轮转**抽样:每个目录各取一张,循环直到够数(``limit<=0`` 表示全取)。""" if limit <= 0: return [f for key in sorted(groups) for f in groups[key]] order = sorted(groups) queues = [list(groups[key]) for key in order] out: list = [] while len(out) < limit and any(queues): for queue in queues: if not queue: continue out.append(queue.pop(0)) if len(out) >= limit: break return out def build(src: str, out: str, limit: int = 200, resize_to: str = "", letterbox: bool = False, pad: int = 114, fmt: str = "png", quality: int = 88, dedupe: bool = True, dataset_name: str = "dataset.txt", quiet: bool = False) -> int: """造集主流程;返回进程退出码(0 成功 / 2 没有可用图片 / 3 输出格式不可用)。""" target = None if resize_to: try: tw, th = [int(part) for part in resize_to.lower().split("x")] except ValueError: print("--resize 需要 WxH 形式(如 640x640),得到 %r" % resize_to, file=sys.stderr) return 2 if tw <= 0 or th <= 0 or tw % 32 or th % 32: print("--resize 的宽高必须是 32 的正整数倍(RKNN 输入对齐),得到 %dx%d" % (tw, th), file=sys.stderr) return 2 target = (tw, th) result = scan(src, dedupe=dedupe) stats = result["stats"] frames = pick(result["groups"], limit) if not frames: print("没有可用图片:扫描 %d,解码失败 %d(--src 指对了吗?)" % (stats["scanned"], stats["failed"]), file=sys.stderr) return 2 img_dir = os.path.join(out, "images") os.makedirs(img_dir, exist_ok=True) rows = [] for idx, frame in enumerate(frames, 1): w, h, ch, px = frame["w"], frame["h"], frame["channels"], frame["pixels"] if target is not None: w, h, px = resize(w, h, ch, px, target[0], target[1], letterbox=letterbox, pad=pad) dst = os.path.abspath(os.path.join(img_dir, "%06d.%s" % (idx, fmt))) try: if fmt == "jpg": write_jpg(dst, w, h, ch, px, quality) else: write_png(dst, w, h, ch, px) except ImageError as exc: print(str(exc), file=sys.stderr) return 3 rows.append({"sha1": frame["sha1"], "src": frame["path"], "out": dst, "width": w, "height": h, "bytes": os.path.getsize(dst)}) dataset = os.path.abspath(os.path.join(out, dataset_name)) with open(dataset, "w", encoding="utf-8") as fh: for row in rows: fh.write(row["out"] + "\n") manifest = os.path.abspath(os.path.join(out, "manifest.csv")) with open(manifest, "w", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) total_mb = sum(row["bytes"] for row in rows) / 1048576.0 size_note = ("原尺寸 %dx%d" % (rows[0]["width"], rows[0]["height"])) if target is None \ else ("%dx%d%s" % (target[0], target[1], " letterbox(pad=%d)" % pad if letterbox else " 拉伸")) summary = [ "INT8 校准集构建摘要", " 来源: %s" % os.path.abspath(src), " 扫描: %d 个文件 → 解码成功 %d / 失败 %d" % (stats["scanned"], stats["decoded"], stats["failed"]), " 去重: %s(唯一 %d 张)" % ("丢重复 %d 个" % stats["dup"] if dedupe else "未去重", stats["uniq"]), " 抽样: %d 张(按来源目录轮转;目录 %d 个)" % (len(rows), len(result["groups"])), " 尺寸: %s;格式 %s" % (size_note, fmt), " 写盘: %s(%.1f MB,平均 %.0f KB/张)" % (img_dir, total_mb, total_mb * 1024.0 / max(1, len(rows))), " dataset.txt: %s(%d 行绝对路径)" % (dataset, len(rows)), " manifest.csv: %s" % manifest, "", "下一步(在装好 rknn-toolkit2 2.3.2 的机器上):", " python scripts/onnx_to_rknn.py --onnx weights/yolov8n.onnx -o /tmp/yolov8n_int8.rknn " "--target rk3588 --imgsz %d --dataset %s --quantized-dtype w8a8" % (target[0] if target else 640, dataset), " python scripts/verify_rknn.py --fp16 weights/demo/yolov8n.rknn --int8 /tmp/yolov8n_int8.rknn", ] text = "\n".join(summary) + "\n" with open(os.path.abspath(os.path.join(out, "summary.txt")), "w", encoding="utf-8") as fh: fh.write(text) if not quiet: print(text) return 0 def main(argv=None) -> int: parser = argparse.ArgumentParser( description="从采集帧生成 RKNN INT8 校准集(去重 + 抽样 + 归一尺寸 + dataset.txt)") parser.add_argument("--src", default=os.path.join(REPO, "runs"), help="采集帧目录(递归;默认 runs)") parser.add_argument("--out", default=None, help="输出目录;默认 runs/calib_<时间戳>") parser.add_argument("--limit", type=int, default=200, help="最多取多少张(按目录轮转;0=全取;经验 200~500)") parser.add_argument("--resize", default="", help="归一尺寸 WxH(32 的倍数,如 640x640)") parser.add_argument("--letterbox", action="store_true", help="等比缩放 + 居中填充(与生产预处理一致,推荐)") parser.add_argument("--pad", type=int, default=114, help="letterbox 填充灰度(默认 114)") parser.add_argument("--format", dest="fmt", default="png", choices=("png", "jpg"), help="输出格式(png 纯标准库;jpg 需要 Pillow/OpenCV)") parser.add_argument("--quality", type=int, default=88, help="jpg 质量(默认 88)") parser.add_argument("--no-dedupe", dest="dedupe", action="store_false", help="不去重(默认按像素内容去重)") parser.add_argument("--dataset-name", default="dataset.txt", help="列表文件名") parser.add_argument("-q", "--quiet", action="store_true", help="不打印摘要") args = parser.parse_args(argv) if args.letterbox and not args.resize: parser.error("--letterbox 需要同时给 --resize WxH") out = args.out or os.path.join(REPO, "runs", "calib_" + _dt.datetime.now().strftime("%Y%m%d_%H%M%S")) return build(args.src, out, limit=args.limit, resize_to=args.resize, letterbox=args.letterbox, pad=args.pad, fmt=args.fmt, quality=args.quality, dedupe=args.dedupe, dataset_name=args.dataset_name, quiet=args.quiet) if __name__ == "__main__": raise SystemExit(main())