My task involves working with an array of N
HTMLCanvasElements that represent frames from a video. I aim to calculate the "median canvas" where every pixel's components (r, g, b, opacity) are the median values from all the canvases.
Each video frame is sized 1280x720, resulting in pixel data for each canvas (retrieved using
canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data
) being a Uint8ClampedArray with a length of 3,686,400.
The traditional method to find the median includes:
- Create a result Uint8ClampedArray with a length of 3,686,400
- Create a temporary Uint8ClampedArray with a length equal to N
- Loop through 0 to 3,686,399
- a) Iterate over the N canvases to populate the array
- b) Calculate the median of the array
- c) Store the median in the result array
This approach is sluggish, especially when dealing with just 4 canvases.
I am looking for a more efficient method or existing code to achieve this. While my question is similar to Find median of list of images, I specifically need a solution in JavaScript, not Python.
Note: For step b), I am using d3.median(). However, it doesn't support typed arrays, so conversion to numbers and then back to Uint8Clamped type becomes necessary.
Note 2: Although I lack expertise in GLSL shaders, perhaps exploring GPU utilization could lead to quicker results. This approach may involve transferring data from CPU to GPU, which might incur time if done frequently.
Note 3: The basic solution can be found here: