"""``scripts/make_calib_dataset.py`` 的单测(INT8 校准集造集,不需要 rknn-toolkit / 板卡)。 守四件事: 1. **PGM 解码**(P5/P6、头部注释、像素不足要报错)与 **PNG 编码**(zlib 解回去逐字节一致); 2. **去重按像素内容**:同一帧的两个文件名只算一张(现场 ``runs/`` 就是这种一堆重复拷贝的状态); 3. **抽样按来源目录轮转**:不能让某一批场景把 200 张全占满; 4. **``dataset.txt`` 必须是绝对路径**(``onnx_to_rknn.py --dataset`` 在板端 cwd 不一定对), 且尺寸不合法(不是 32 的倍数)时要**拒绝**而不是悄悄出个错尺寸。 """ from __future__ import annotations import importlib.util import os import struct import sys import tempfile import unittest import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) def _load(name: str = "make_calib_dataset"): """按路径加载 ``scripts/.py``(scripts 不是包)。""" path = os.path.join(ROOT, "scripts", name + ".py") spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) assert spec.loader is not None sys.modules.setdefault(name, module) spec.loader.exec_module(module) return module calib = _load() def write_pgm(path: str, w: int, h: int, value: int, channels: int = 1) -> str: """写一张常量灰度/彩色 PGM(P5/P6),带上注释行以覆盖头部解析。""" magic = b"P5" if channels == 1 else b"P6" header = magic + b"\n# generated by test\n%d %d\n255\n" % (w, h) with open(path, "wb") as fh: fh.write(header + bytes([value]) * (w * h * channels)) return path def read_png_pixels(path: str): """解我们自己写的 PNG(filter 必须全 0),返回 ``(w, h, channels, pixels)``。""" with open(path, "rb") as fh: data = fh.read() assert data.startswith(calib.PNG_SIG), "不是 PNG" pos = len(calib.PNG_SIG) width = height = channels = 0 idat = b"" while pos < len(data): length = struct.unpack(">I", data[pos:pos + 4])[0] tag = data[pos + 4:pos + 8] payload = data[pos + 8:pos + 8 + length] pos += 12 + length if tag == b"IHDR": width, height, depth, color_type = struct.unpack(">IIBB", payload[:10]) assert depth == 8 channels = 1 if color_type == 0 else 3 elif tag == b"IDAT": idat += payload raw = zlib.decompress(idat) stride = width * channels out = bytearray() for y in range(height): base = y * (stride + 1) assert raw[base] == 0, "只支持 filter=0" out += raw[base + 1:base + 1 + stride] return width, height, channels, bytes(out) class PgmTest(unittest.TestCase): def test_p5(self): with tempfile.TemporaryDirectory() as tmp: path = write_pgm(os.path.join(tmp, "a.pgm"), 4, 3, 7) w, h, ch, px = calib.read_pgm(path) self.assertEqual((w, h, ch), (4, 3, 1)) self.assertEqual(px, bytes([7]) * 12) def test_p6(self): with tempfile.TemporaryDirectory() as tmp: path = write_pgm(os.path.join(tmp, "b.pgm"), 2, 2, 9, channels=3) w, h, ch, px = calib.read_pgm(path) self.assertEqual((w, h, ch), (2, 2, 3)) self.assertEqual(len(px), 12) def test_truncated_pixels_rejected(self): with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "bad.pgm") with open(path, "wb") as fh: fh.write(b"P5\n4 4\n255\n" + bytes(5)) # 只给 5 个像素 with self.assertRaises(calib.ImageError): calib.read_pgm(path) class PngTest(unittest.TestCase): def test_roundtrip_rgb(self): with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "x.png") pixels = bytes((i * 7) % 256 for i in range(6 * 4 * 3)) calib.write_png(path, 6, 4, 3, pixels) self.assertEqual(read_png_pixels(path), (6, 4, 3, pixels)) def test_roundtrip_gray(self): with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "y.png") pixels = bytes((i * 3) % 256 for i in range(5 * 5)) calib.write_png(path, 5, 5, 1, pixels) self.assertEqual(read_png_pixels(path), (5, 5, 1, pixels)) class DedupeAndPickTest(unittest.TestCase): def test_content_dedupe(self): with tempfile.TemporaryDirectory() as tmp: a = os.path.join(tmp, "a"); os.makedirs(a) b = os.path.join(tmp, "b"); os.makedirs(b) write_pgm(os.path.join(a, "1.pgm"), 4, 4, 10) write_pgm(os.path.join(b, "2.pgm"), 4, 4, 10) # 像素相同 → 重复 write_pgm(os.path.join(b, "3.pgm"), 4, 4, 11) result = calib.scan(tmp) self.assertEqual(result["stats"]["scanned"], 3) self.assertEqual(result["stats"]["dup"], 1) self.assertEqual(result["stats"]["uniq"], 2) self.assertEqual(sorted(result["groups"]), ["a", "b"]) def test_no_dedupe_keeps_both(self): with tempfile.TemporaryDirectory() as tmp: write_pgm(os.path.join(tmp, "1.pgm"), 3, 3, 42) write_pgm(os.path.join(tmp, "2.pgm"), 3, 3, 42) self.assertEqual(calib.scan(tmp, dedupe=False)["stats"]["uniq"], 2) def test_pick_round_robin(self): groups = {"a": [1, 2, 3], "b": [9]} self.assertEqual(calib.pick(groups, 3), [1, 9, 2]) self.assertEqual(calib.pick(groups, 0), [1, 2, 3, 9]) class BuildTest(unittest.TestCase): def test_build_writes_absolute_dataset_and_manifest(self): with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out: os.makedirs(os.path.join(src, "dump_a")) os.makedirs(os.path.join(src, "dump_b")) write_pgm(os.path.join(src, "dump_a", "f1.pgm"), 8, 8, 1) write_pgm(os.path.join(src, "dump_a", "f1_copy.pgm"), 8, 8, 1) write_pgm(os.path.join(src, "dump_b", "f2.pgm"), 8, 8, 2) rc = calib.build(src, out, limit=2, resize_to="64x64", letterbox=True, quiet=True) self.assertEqual(rc, 0) with open(os.path.join(out, "dataset.txt"), encoding="utf-8") as fh: lines = [ln.strip() for ln in fh if ln.strip()] self.assertEqual(len(lines), 2) for line in lines: self.assertTrue(os.path.isabs(line), line) self.assertTrue(os.path.exists(line), line) # letterbox 到 64x64:manifest 里必须是归一后的尺寸 with open(os.path.join(out, "manifest.csv"), encoding="utf-8") as fh: rows = fh.read().strip().splitlines() self.assertEqual(rows[0], "sha1,src,out,width,height,bytes") self.assertEqual(len(rows), 3) self.assertIn(",64,64,", rows[1]) self.assertTrue(os.path.exists(os.path.join(out, "summary.txt"))) self.assertEqual(read_png_pixels(lines[0])[0:2], (64, 64)) def test_bad_resize_rejected(self): with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out: write_pgm(os.path.join(src, "f.pgm"), 8, 8, 1) self.assertEqual(calib.build(src, out, resize_to="100x100", quiet=True), 2) self.assertEqual(calib.build(src, out, resize_to="abc", quiet=True), 2) def test_empty_src(self): with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out: self.assertEqual(calib.build(src, out, quiet=True), 2) class ResizeTest(unittest.TestCase): def test_letterbox_keeps_aspect_and_pads(self): pixels = bytes([200]) * (4 * 2) # 4x2 灰度 w, h, out = calib.resize(4, 2, 1, pixels, 8, 8, letterbox=True, pad=0) self.assertEqual((w, h), (8, 8)) self.assertEqual(len(out), 64) self.assertEqual(out[0], 0) # 顶部是填充 self.assertEqual(out[4 * 8 + 4], 200) # 中间是内容 def test_stretch(self): w, h, out = calib.resize(2, 2, 1, bytes([5, 5, 5, 5]), 4, 4) self.assertEqual((w, h), (4, 4)) self.assertEqual(set(out), {5}) self.assertEqual(calib.resize(3, 3, 1, bytes(9), 3, 3)[2], bytes(9)) # 同尺寸直通 if __name__ == "__main__": unittest.main()