Skip to content

Instantly share code, notes, and snippets.

@jnewb1
Created September 19, 2023 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jnewb1/65f58ff25e9457f8ebb7581f0a31a716 to your computer and use it in GitHub Desktop.
Save jnewb1/65f58ff25e9457f8ebb7581f0a31a716 to your computer and use it in GitHub Desktop.
opencl vs opencv
import cv2
import numpy as np
import os
import pyopencl as cl
import pyopencl.array as cl_array
import time
from openpilot.common.basedir import BASEDIR
W, H = 1920, 1080
# set up for pyopencl rgb to yuv conversion
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
cl_arg = f" -DHEIGHT={H} -DWIDTH={W} -DRGB_STRIDE={W * 3} -DUV_WIDTH={W // 2} -DUV_HEIGHT={H // 2} -DRGB_SIZE={W * H} -DCL_DEBUG "
kernel_fn = os.path.join(BASEDIR, "tools/sim/rgb_to_nv12.cl")
with open(kernel_fn) as f:
prg = cl.Program(ctx, f.read()).build(cl_arg)
krnl = prg.rgb_to_nv12
Wdiv4 = W // 4 if (W % 4 == 0) else (W + (4 - W % 4)) // 4
Hdiv4 = H // 4 if (H % 4 == 0) else (H + (4 - H % 4)) // 4
def cl_rgb2nv12(rgb):
rgb_cl = cl_array.to_device(queue, rgb)
yuv_cl = cl_array.empty_like(rgb_cl)
krnl(queue, (Wdiv4, Hdiv4), None, rgb_cl.data, yuv_cl.data).wait()
yuv = np.resize(yuv_cl.get(), rgb.size // 2)
return yuv.data.tobytes()
def cv_rgb2nv12(rgb):
yuv = cv2.cvtColor(rgb, cv2.COLOR_BGR2YUV_I420)
uv_row_cnt = yuv.shape[0] // 3
uv_plane = np.transpose(yuv[uv_row_cnt * 2:].reshape(2, -1), [1, 0])
yuv[uv_row_cnt * 2:] = uv_plane.reshape(uv_row_cnt, -1)
return yuv.tobytes()
def test_time():
image = (np.random.random((W, H, 3)) * 255).astype(np.uint8)
cl_time = 0
cv_time = 0
for i in range(100):
start = time.monotonic()
cv_nv12 = cv_rgb2nv12(image)
cv_time += time.monotonic() - start
start = time.monotonic()
cl_nv12 = cl_rgb2nv12(image)
cl_time += time.monotonic() - start
print(f"{len(cl_nv12)} {len(cv_nv12)}")
print(f"CV: {1/cv_time}, CL: {1/cl_time}")
test_time()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment