William Grimes
William Grimes

Reputation: 697

Numpy averaging a series

numpy_frames_original are frames in a video. Firstly, I wanted to find the average of these frames and subtract it from each frame giving numpy_frames. For the problem I am trying to tackle I thought it would be a good idea to find the average of all of these frames, to do this I wrote the code below:

arr=np.zeros((height,width), np.float)

for i in range(0, number_frames):
    imarr=np.array(numpy_frames_original[i,:,:].astype(float))
    arr=arr+imarr/number_frames

img_avg=np.array(np.round(arr),dtype=np.uint8)
numpy_frames = np.array(np.absolute(np.round(np.array(numpy_frames_original.astype(float))-np.array(img_avg.astype(float)))), dtype=np.uint8)

Now I have decided It would be better not to get an average of all of the frames, but instead for each frame subtract an average of 100 frames closest to it.

I'm not sure how to write this code?

For example for frame 0 it would average frames 0 - 99 and subtract the average. For frame 3 it would also average frames 0 - 99 and subtract, for frames 62 it would average frames 12-112 and subtract.

Thanks

Upvotes: 1

Views: 337

Answers (1)

Daniel Renshaw
Daniel Renshaw

Reputation: 34177

I think this does what you need.

import numpy

# Create some fake data
frame_count = 10
frame_width = 2
frame_height = 3
frames = numpy.random.randn(frame_count, frame_width, frame_height).astype(numpy.float32)
print 'Original frames\n', frames

# Compute the modified frames over a specified range
mean_range_size = 2
assert frame_count >= mean_range_size * 2

start_mean = frames[:2 * mean_range_size + 1].mean(axis=0)
start_frames = frames[:mean_range_size] - start_mean

middle_frames = numpy.empty((frames.shape[0] - 2 * mean_range_size,
                             frames.shape[1], frames.shape[2]),
                            dtype=frames.dtype)

for index in xrange(middle_frames.shape[0]):
    middle_frames[index] = frames[mean_range_size + index] - \
                           frames[index:index + 2 * mean_range_size + 1].mean(axis=0)

end_mean = frames[-2 * mean_range_size - 1:].mean(axis=0)
end_frames = frames[-mean_range_size:] - end_mean

modified_frames = numpy.concatenate([start_frames, middle_frames, end_frames])
print 'Modified frames\n', modified_frames

Note the assert, the code will need to be modified if your shortest sequence is shorter than the total range size (e.g. 100 frames).

Upvotes: 1

Related Questions