Search code examples
pythonimage-processingscipydistancedeque

Calculate the distance between two Centriods


I'm trying to track a detected object in a binary video frames. Therefore I've stored the Centroids of the detected object(small red car) in a dequeue and used scypi spatial distance to calculate the distance between two successive centroids using the following code:

import scipy.spatial.distance
from collections import  deque

#defining the Centroid
centroids=deque(maxlen=40)
.
.
.
centroids.appendleft(center)
#center comes from detection process. e.g centroids=[(120,130), (125,132),...

Distance=scipy.spatial.distance.cdist(center[0],center[1)]
print('Distance ",Distance)

when i run the code, i get the following error:

 raise ValueError('XA must be a 2-dimensional array.')
 ValueError: XA must be a 2-dimensional array.

The error is logical,because the stored centroids are point vector of the the center of the car

So my question is:

How can i make this work in such a way so that i get the distance difference between every two successive Centroids?


Solution

  • scipy.spatial.distance.cdist() requires two 2-Dimensional array as input, but by providing it center[0] and center[1] you are giving it two 1-dimensional arrays.

    If you want to feed elements of centroids one at a time, scipy.spatial.distance includes a function called euclidean which measures the distance between two 1-dimensional arrays.

    To get the distances between every pair of sequential centroids in this way, you can just loop over the list of centroids like this:

    distances = []
    for i in range(len(centroids) - 1):
        distances.append(euclidean(centroids[i], centroids[i+1]))