Home > Software design >  Modifying alternate indices of 3d numpy array
Modifying alternate indices of 3d numpy array

Time:12-22

I have a numpy array with shape (140, 23, 2) being 140 frames, 23 objects, and x,y locations. The data has been generated by a GAN and when I animate the movement it's very jittery. I want to smooth it by converting the coordinates for each object so every odd number index to be the mid-point between the even numbered indices either side of it. e.g.

x[1] = (x[0] x[2]) / 2

x[3] = (x[2] x[4]) / 2

Below is my code:

def smooth_coordinates(df):
    # df shape is (140, 23, 2)
    # iterate through each object (23)
    for j in range(len(df[0])):
        # iterate through 140 frames
        for i in range(len(df)):
            # if it's an even number and index allows at least 1 index after it
            if (i%2 != 0) and (i < (len(df[0])-2)):
                df[i][j][0] = ( (df[i-1][j][0] df[i 1][j][0]) /2 )
                df[i][j][1] = ( (df[i-1][j][1] df[i 1][j][1]) /2 )
    return df

Aside from it being very inefficient my input df and output df are identical. Any suggestions for how to achieve this more efficiently?

CodePudding user response:

import numpy as np

a = np.random.randint(100, size= [140, 23, 2])  # input array
b = a.copy()

i = np.ogrid[1: a.shape[0]-1: 2]    # odd indicies
i

>>> [  1,   3,   5,   7,   9,  11,  13,  15,  17,  19,  21,  23,  25,
      27,  29,  31,  33,  35,  37,  39,  41,  43,  45,  47,  49,  51,
      53,  55,  57,  59,  61,  63,  65,  67,  69,  71,  73,  75,  77,
      79,  81,  83,  85,  87,  89,  91,  93,  95,  97,  99, 101, 103,
     105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129,
     131, 133, 135, 137]
(a == b).all()                  # testing for equality

>>> True
a[i] = (a[i-1]   a[i 1]) / 2    # averaging positions across frames
(a == b).all()                  # testing for equality again

>>> False
  • Related