When processing a video, you may want to buffer n consecutive frames. So, when you want to roll the buffer and use it, you have to shift the index of the buffer.
When processing with numpy, I think there are the following two processing methods.
I want to take the fastest processing method possible, so I will consider which of these two processes is faster.
I tried the following process on jupyter notebook.
arr1 = np.zeros((30, 720, 1280))
# numpy.use the roll method
%timeit np.roll(arr1, 1, axis = 0)
# 147 ms ± 1.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
#Substitute by shifting by index
%timeit arr1[1:,:,:] = arr1[0:-1,:,:]
# 189 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
arr2 = np.zeros((720, 1280, 30))
# numpy.use the roll method
%timeit np.roll(arr2, 1, axis = 2)
# 186 ms ± 2.71 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
#Substitute by shifting by index
%timeit arr2[:,:, 1:] = arr2[:,:,0:-1]
# 203 ms ± 1.06 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
It seems that using numpy.roll is faster under the condition that the image size is large. Also, it seems faster to switch images at the first index.
When the image is very small (20x20pixel), the result is that the index shift is faster as shown below.
arr3 = np.zeros((30, 20, 20))
# numpy.use the roll method
%timeit np.roll(arr3, 1, axis = 0)
# 17.1 µs ± 551 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#Substitute by shifting by index
%timeit arr3[1:,:,:] = arr3[0:-1,:,:]
# 7.36 µs ± 90.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#mistake
arr[0:-2,:,:] = arr[1:-1,:,:]
arr[-1,:,:] = new_image
#Correct answer
arr[0:-1,:,:] = arr[1:,:,:]
arr[-1,:,:] = new_image
Setting the first index to -1 specifies the last index.
arr[1:-1,:,:]Then
At first glance, it seems that you can specify from the second to the first (up to the last index).
Actually, since the second to the penultimate is specified, the movement is that the last image does not shift to the front.
Recommended Posts