test_debayer.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import bz2
  5. import numpy as np
  6. import pyopencl as cl # install with `PYOPENCL_CL_PRETEND_VERSION=2.0 pip install pyopencl`
  7. from openpilot.system.hardware import PC, TICI
  8. from openpilot.common.basedir import BASEDIR
  9. from openpilot.tools.lib.openpilotci import BASE_URL
  10. from openpilot.system.version import get_commit
  11. from openpilot.system.camerad.snapshot.snapshot import yuv_to_rgb
  12. from openpilot.tools.lib.logreader import LogReader
  13. from openpilot.tools.lib.filereader import FileReader
  14. TEST_ROUTE = "8345e3b82948d454|2022-05-04--13-45-33/0"
  15. FRAME_WIDTH = 1928
  16. FRAME_HEIGHT = 1208
  17. FRAME_STRIDE = 2896
  18. UV_WIDTH = FRAME_WIDTH // 2
  19. UV_HEIGHT = FRAME_HEIGHT // 2
  20. UV_SIZE = UV_WIDTH * UV_HEIGHT
  21. def get_frame_fn(ref_commit, test_route, tici=True):
  22. return f"{test_route}_debayer{'_tici' if tici else ''}_{ref_commit}.bz2"
  23. def bzip_frames(frames):
  24. data = b''
  25. for y, u, v in frames:
  26. data += y.tobytes()
  27. data += u.tobytes()
  28. data += v.tobytes()
  29. return bz2.compress(data)
  30. def unbzip_frames(url):
  31. with FileReader(url) as f:
  32. dat = f.read()
  33. data = bz2.decompress(dat)
  34. res = []
  35. for y_start in range(0, len(data), FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2):
  36. u_start = y_start + FRAME_WIDTH * FRAME_HEIGHT
  37. v_start = u_start + UV_SIZE
  38. y = np.frombuffer(data[y_start: u_start], dtype=np.uint8).reshape((FRAME_HEIGHT, FRAME_WIDTH))
  39. u = np.frombuffer(data[u_start: v_start], dtype=np.uint8).reshape((UV_HEIGHT, UV_WIDTH))
  40. v = np.frombuffer(data[v_start: v_start + UV_SIZE], dtype=np.uint8).reshape((UV_HEIGHT, UV_WIDTH))
  41. res.append((y, u, v))
  42. return res
  43. def init_kernels(frame_offset=0):
  44. ctx = cl.create_some_context(interactive=False)
  45. with open(os.path.join(BASEDIR, 'system/camerad/cameras/real_debayer.cl')) as f:
  46. build_args = ' -cl-fast-relaxed-math -cl-denorms-are-zero -cl-single-precision-constant' + \
  47. f' -DFRAME_STRIDE={FRAME_STRIDE} -DRGB_WIDTH={FRAME_WIDTH} -DRGB_HEIGHT={FRAME_HEIGHT} -DFRAME_OFFSET={frame_offset} -DCAM_NUM=0'
  48. if PC:
  49. build_args += ' -DHALF_AS_FLOAT=1 -cl-std=CL2.0'
  50. debayer_prg = cl.Program(ctx, f.read()).build(options=build_args)
  51. return ctx, debayer_prg
  52. def debayer_frame(ctx, debayer_prg, data, rgb=False):
  53. q = cl.CommandQueue(ctx)
  54. yuv_buff = np.empty(FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2, dtype=np.uint8)
  55. cam_g = cl.Buffer(ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=data)
  56. yuv_g = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2)
  57. local_worksize = (20, 20) if TICI else (4, 4)
  58. ev1 = debayer_prg.debayer10(q, (UV_WIDTH, UV_HEIGHT), local_worksize, cam_g, yuv_g)
  59. cl.enqueue_copy(q, yuv_buff, yuv_g, wait_for=[ev1]).wait()
  60. cl.enqueue_barrier(q)
  61. y = yuv_buff[:FRAME_WIDTH*FRAME_HEIGHT].reshape((FRAME_HEIGHT, FRAME_WIDTH))
  62. u = yuv_buff[FRAME_WIDTH*FRAME_HEIGHT:FRAME_WIDTH*FRAME_HEIGHT+UV_SIZE].reshape((UV_HEIGHT, UV_WIDTH))
  63. v = yuv_buff[FRAME_WIDTH*FRAME_HEIGHT+UV_SIZE:].reshape((UV_HEIGHT, UV_WIDTH))
  64. if rgb:
  65. return yuv_to_rgb(y, u, v)
  66. else:
  67. return y, u, v
  68. def debayer_replay(lr):
  69. ctx, debayer_prg = init_kernels()
  70. frames = []
  71. for m in lr:
  72. if m.which() == 'roadCameraState':
  73. cs = m.roadCameraState
  74. if cs.image:
  75. data = np.frombuffer(cs.image, dtype=np.uint8)
  76. img = debayer_frame(ctx, debayer_prg, data)
  77. frames.append(img)
  78. return frames
  79. if __name__ == "__main__":
  80. update = "--update" in sys.argv
  81. replay_dir = os.path.dirname(os.path.abspath(__file__))
  82. ref_commit_fn = os.path.join(replay_dir, "debayer_replay_ref_commit")
  83. # load logs
  84. lr = list(LogReader(TEST_ROUTE))
  85. # run replay
  86. frames = debayer_replay(lr)
  87. # get diff
  88. failed = False
  89. diff = ''
  90. yuv_i = ['y', 'u', 'v']
  91. if not update:
  92. with open(ref_commit_fn) as f:
  93. ref_commit = f.read().strip()
  94. frame_fn = get_frame_fn(ref_commit, TEST_ROUTE, tici=TICI)
  95. try:
  96. cmp_frames = unbzip_frames(BASE_URL + frame_fn)
  97. if len(frames) != len(cmp_frames):
  98. failed = True
  99. diff += 'amount of frames not equal\n'
  100. for i, (frame, cmp_frame) in enumerate(zip(frames, cmp_frames, strict=True)):
  101. for j in range(3):
  102. fr = frame[j]
  103. cmp_f = cmp_frame[j]
  104. if fr.shape != cmp_f.shape:
  105. failed = True
  106. diff += f'frame shapes not equal for ({i}, {yuv_i[j]})\n'
  107. diff += f'{ref_commit}: {cmp_f.shape}\n'
  108. diff += f'HEAD: {fr.shape}\n'
  109. elif not np.array_equal(fr, cmp_f):
  110. failed = True
  111. if np.allclose(fr, cmp_f, atol=1):
  112. diff += f'frames not equal for ({i}, {yuv_i[j]}), but are all close\n'
  113. else:
  114. diff += f'frames not equal for ({i}, {yuv_i[j]})\n'
  115. frame_diff = np.abs(np.subtract(fr, cmp_f))
  116. diff_len = len(np.nonzero(frame_diff)[0])
  117. if diff_len > 10000:
  118. diff += f'different at a large amount of pixels ({diff_len})\n'
  119. else:
  120. diff += 'different at (frame, yuv, pixel, ref, HEAD):\n'
  121. for k in zip(*np.nonzero(frame_diff), strict=True):
  122. diff += f'{i}, {yuv_i[j]}, {k}, {cmp_f[k]}, {fr[k]}\n'
  123. if failed:
  124. print(diff)
  125. with open("debayer_diff.txt", "w") as f:
  126. f.write(diff)
  127. except Exception as e:
  128. print(str(e))
  129. failed = True
  130. # upload new refs
  131. if update or (failed and TICI):
  132. from openpilot.tools.lib.openpilotci import upload_file
  133. print("Uploading new refs")
  134. frames_bzip = bzip_frames(frames)
  135. new_commit = get_commit()
  136. frame_fn = os.path.join(replay_dir, get_frame_fn(new_commit, TEST_ROUTE, tici=TICI))
  137. with open(frame_fn, "wb") as f2:
  138. f2.write(frames_bzip)
  139. try:
  140. upload_file(frame_fn, os.path.basename(frame_fn))
  141. except Exception as e:
  142. print("failed to upload", e)
  143. if update:
  144. with open(ref_commit_fn, 'w') as f:
  145. f.write(str(new_commit))
  146. print("\nNew ref commit: ", new_commit)
  147. sys.exit(int(failed))