mihagazvoda
mihagazvoda

Reputation: 1367

Condition true if numpy array does't have dimension or if the dimension is less than n

I have to calculate average (mean) of first 30 frames which are coming from a while(true) loop. How to transform condition of the 2th to be true only when fourth dimension is less than 30 or if there is no fourth dimension? Any other ways to optimize code? frame.shape = (480,640,3). Values are from 0 to 255.

    if isFirst == True:
        first_frames = frame
        isFirst == False

    if first_frames.shape[3] < 30:
        np.append(first_frames, frame, axis=3)
        avg_frames = np.mean(first_frames, axis=3)

    new_frame = frame - avg_frames

Upvotes: 1

Views: 59

Answers (1)

Divakar
Divakar

Reputation: 221504

I would suggest initializing an array to store a running summation of all the frames until the first 30 frames, for which we could have a loop iterating range. At the end of each loop, we will compute the average frame by dividing the running summation by the loop iterator. That's all! The idea is to optimize on memory by using a 3D array for storing the summation instead of appending onto a costly 4D array.

Thus, the implementation would be -

# Initialize array for storing running summation
first_frames = np.zeros((480,640,3),dtype=np.uint64)

for i in range(30):       # Runs until first 30 frames
    first_frames += frame # Add each frame
    new_frame = frame - first_frames/float(i)

Upvotes: 1

Related Questions