test_make_calib_dataset.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. """``scripts/make_calib_dataset.py`` 的单测(INT8 校准集造集,不需要 rknn-toolkit / 板卡)。
  2. 守四件事:
  3. 1. **PGM 解码**(P5/P6、头部注释、像素不足要报错)与 **PNG 编码**(zlib 解回去逐字节一致);
  4. 2. **去重按像素内容**:同一帧的两个文件名只算一张(现场 ``runs/`` 就是这种一堆重复拷贝的状态);
  5. 3. **抽样按来源目录轮转**:不能让某一批场景把 200 张全占满;
  6. 4. **``dataset.txt`` 必须是绝对路径**(``onnx_to_rknn.py --dataset`` 在板端 cwd 不一定对),
  7. 且尺寸不合法(不是 32 的倍数)时要**拒绝**而不是悄悄出个错尺寸。
  8. """
  9. from __future__ import annotations
  10. import importlib.util
  11. import os
  12. import struct
  13. import sys
  14. import tempfile
  15. import unittest
  16. import zlib
  17. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  18. if ROOT not in sys.path:
  19. sys.path.insert(0, ROOT)
  20. def _load(name: str = "make_calib_dataset"):
  21. """按路径加载 ``scripts/<name>.py``(scripts 不是包)。"""
  22. path = os.path.join(ROOT, "scripts", name + ".py")
  23. spec = importlib.util.spec_from_file_location(name, path)
  24. module = importlib.util.module_from_spec(spec)
  25. assert spec.loader is not None
  26. sys.modules.setdefault(name, module)
  27. spec.loader.exec_module(module)
  28. return module
  29. calib = _load()
  30. def write_pgm(path: str, w: int, h: int, value: int, channels: int = 1) -> str:
  31. """写一张常量灰度/彩色 PGM(P5/P6),带上注释行以覆盖头部解析。"""
  32. magic = b"P5" if channels == 1 else b"P6"
  33. header = magic + b"\n# generated by test\n%d %d\n255\n" % (w, h)
  34. with open(path, "wb") as fh:
  35. fh.write(header + bytes([value]) * (w * h * channels))
  36. return path
  37. def read_png_pixels(path: str):
  38. """解我们自己写的 PNG(filter 必须全 0),返回 ``(w, h, channels, pixels)``。"""
  39. with open(path, "rb") as fh:
  40. data = fh.read()
  41. assert data.startswith(calib.PNG_SIG), "不是 PNG"
  42. pos = len(calib.PNG_SIG)
  43. width = height = channels = 0
  44. idat = b""
  45. while pos < len(data):
  46. length = struct.unpack(">I", data[pos:pos + 4])[0]
  47. tag = data[pos + 4:pos + 8]
  48. payload = data[pos + 8:pos + 8 + length]
  49. pos += 12 + length
  50. if tag == b"IHDR":
  51. width, height, depth, color_type = struct.unpack(">IIBB", payload[:10])
  52. assert depth == 8
  53. channels = 1 if color_type == 0 else 3
  54. elif tag == b"IDAT":
  55. idat += payload
  56. raw = zlib.decompress(idat)
  57. stride = width * channels
  58. out = bytearray()
  59. for y in range(height):
  60. base = y * (stride + 1)
  61. assert raw[base] == 0, "只支持 filter=0"
  62. out += raw[base + 1:base + 1 + stride]
  63. return width, height, channels, bytes(out)
  64. class PgmTest(unittest.TestCase):
  65. def test_p5(self):
  66. with tempfile.TemporaryDirectory() as tmp:
  67. path = write_pgm(os.path.join(tmp, "a.pgm"), 4, 3, 7)
  68. w, h, ch, px = calib.read_pgm(path)
  69. self.assertEqual((w, h, ch), (4, 3, 1))
  70. self.assertEqual(px, bytes([7]) * 12)
  71. def test_p6(self):
  72. with tempfile.TemporaryDirectory() as tmp:
  73. path = write_pgm(os.path.join(tmp, "b.pgm"), 2, 2, 9, channels=3)
  74. w, h, ch, px = calib.read_pgm(path)
  75. self.assertEqual((w, h, ch), (2, 2, 3))
  76. self.assertEqual(len(px), 12)
  77. def test_truncated_pixels_rejected(self):
  78. with tempfile.TemporaryDirectory() as tmp:
  79. path = os.path.join(tmp, "bad.pgm")
  80. with open(path, "wb") as fh:
  81. fh.write(b"P5\n4 4\n255\n" + bytes(5)) # 只给 5 个像素
  82. with self.assertRaises(calib.ImageError):
  83. calib.read_pgm(path)
  84. class PngTest(unittest.TestCase):
  85. def test_roundtrip_rgb(self):
  86. with tempfile.TemporaryDirectory() as tmp:
  87. path = os.path.join(tmp, "x.png")
  88. pixels = bytes((i * 7) % 256 for i in range(6 * 4 * 3))
  89. calib.write_png(path, 6, 4, 3, pixels)
  90. self.assertEqual(read_png_pixels(path), (6, 4, 3, pixels))
  91. def test_roundtrip_gray(self):
  92. with tempfile.TemporaryDirectory() as tmp:
  93. path = os.path.join(tmp, "y.png")
  94. pixels = bytes((i * 3) % 256 for i in range(5 * 5))
  95. calib.write_png(path, 5, 5, 1, pixels)
  96. self.assertEqual(read_png_pixels(path), (5, 5, 1, pixels))
  97. class DedupeAndPickTest(unittest.TestCase):
  98. def test_content_dedupe(self):
  99. with tempfile.TemporaryDirectory() as tmp:
  100. a = os.path.join(tmp, "a"); os.makedirs(a)
  101. b = os.path.join(tmp, "b"); os.makedirs(b)
  102. write_pgm(os.path.join(a, "1.pgm"), 4, 4, 10)
  103. write_pgm(os.path.join(b, "2.pgm"), 4, 4, 10) # 像素相同 → 重复
  104. write_pgm(os.path.join(b, "3.pgm"), 4, 4, 11)
  105. result = calib.scan(tmp)
  106. self.assertEqual(result["stats"]["scanned"], 3)
  107. self.assertEqual(result["stats"]["dup"], 1)
  108. self.assertEqual(result["stats"]["uniq"], 2)
  109. self.assertEqual(sorted(result["groups"]), ["a", "b"])
  110. def test_no_dedupe_keeps_both(self):
  111. with tempfile.TemporaryDirectory() as tmp:
  112. write_pgm(os.path.join(tmp, "1.pgm"), 3, 3, 42)
  113. write_pgm(os.path.join(tmp, "2.pgm"), 3, 3, 42)
  114. self.assertEqual(calib.scan(tmp, dedupe=False)["stats"]["uniq"], 2)
  115. def test_pick_round_robin(self):
  116. groups = {"a": [1, 2, 3], "b": [9]}
  117. self.assertEqual(calib.pick(groups, 3), [1, 9, 2])
  118. self.assertEqual(calib.pick(groups, 0), [1, 2, 3, 9])
  119. class BuildTest(unittest.TestCase):
  120. def test_build_writes_absolute_dataset_and_manifest(self):
  121. with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out:
  122. os.makedirs(os.path.join(src, "dump_a"))
  123. os.makedirs(os.path.join(src, "dump_b"))
  124. write_pgm(os.path.join(src, "dump_a", "f1.pgm"), 8, 8, 1)
  125. write_pgm(os.path.join(src, "dump_a", "f1_copy.pgm"), 8, 8, 1)
  126. write_pgm(os.path.join(src, "dump_b", "f2.pgm"), 8, 8, 2)
  127. rc = calib.build(src, out, limit=2, resize_to="64x64", letterbox=True, quiet=True)
  128. self.assertEqual(rc, 0)
  129. with open(os.path.join(out, "dataset.txt"), encoding="utf-8") as fh:
  130. lines = [ln.strip() for ln in fh if ln.strip()]
  131. self.assertEqual(len(lines), 2)
  132. for line in lines:
  133. self.assertTrue(os.path.isabs(line), line)
  134. self.assertTrue(os.path.exists(line), line)
  135. # letterbox 到 64x64:manifest 里必须是归一后的尺寸
  136. with open(os.path.join(out, "manifest.csv"), encoding="utf-8") as fh:
  137. rows = fh.read().strip().splitlines()
  138. self.assertEqual(rows[0], "sha1,src,out,width,height,bytes")
  139. self.assertEqual(len(rows), 3)
  140. self.assertIn(",64,64,", rows[1])
  141. self.assertTrue(os.path.exists(os.path.join(out, "summary.txt")))
  142. self.assertEqual(read_png_pixels(lines[0])[0:2], (64, 64))
  143. def test_bad_resize_rejected(self):
  144. with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out:
  145. write_pgm(os.path.join(src, "f.pgm"), 8, 8, 1)
  146. self.assertEqual(calib.build(src, out, resize_to="100x100", quiet=True), 2)
  147. self.assertEqual(calib.build(src, out, resize_to="abc", quiet=True), 2)
  148. def test_empty_src(self):
  149. with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out:
  150. self.assertEqual(calib.build(src, out, quiet=True), 2)
  151. class ResizeTest(unittest.TestCase):
  152. def test_letterbox_keeps_aspect_and_pads(self):
  153. pixels = bytes([200]) * (4 * 2) # 4x2 灰度
  154. w, h, out = calib.resize(4, 2, 1, pixels, 8, 8, letterbox=True, pad=0)
  155. self.assertEqual((w, h), (8, 8))
  156. self.assertEqual(len(out), 64)
  157. self.assertEqual(out[0], 0) # 顶部是填充
  158. self.assertEqual(out[4 * 8 + 4], 200) # 中间是内容
  159. def test_stretch(self):
  160. w, h, out = calib.resize(2, 2, 1, bytes([5, 5, 5, 5]), 4, 4)
  161. self.assertEqual((w, h), (4, 4))
  162. self.assertEqual(set(out), {5})
  163. self.assertEqual(calib.resize(3, 3, 1, bytes(9), 3, 3)[2], bytes(9)) # 同尺寸直通
  164. if __name__ == "__main__":
  165. unittest.main()