How can the Euclidean distance be calculated with NumPy?

后端 未结 22 938
春和景丽
春和景丽 2020-11-22 02:29

I have two points in 3D:

(xa, ya, za)
(xb, yb, zb)

And I want to calculate the distance:

dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (         


        
相关标签:
22条回答
  • 2020-11-22 02:50

    Calculate the Euclidean distance for multidimensional space:

     import math
    
     x = [1, 2, 6] 
     y = [-2, 3, 2]
    
     dist = math.sqrt(sum([(xi-yi)**2 for xi,yi in zip(x, y)]))
     5.0990195135927845
    
    0 讨论(0)
  • 2020-11-22 02:53

    I find a 'dist' function in matplotlib.mlab, but I don't think it's handy enough.

    I'm posting it here just for reference.

    import numpy as np
    import matplotlib as plt
    
    a = np.array([1, 2, 3])
    b = np.array([2, 3, 4])
    
    # Distance between a and b
    dis = plt.mlab.dist(a, b)
    
    0 讨论(0)
  • 2020-11-22 02:55

    Having a and b as you defined them, you can use also:

    distance = np.sqrt(np.sum((a-b)**2))
    
    0 讨论(0)
  • 2020-11-22 02:55

    The other answers work for floating point numbers, but do not correctly compute the distance for integer dtypes which are subject to overflow and underflow. Note that even scipy.distance.euclidean has this issue:

    >>> a1 = np.array([1], dtype='uint8')
    >>> a2 = np.array([2], dtype='uint8')
    >>> a1 - a2
    array([255], dtype=uint8)
    >>> np.linalg.norm(a1 - a2)
    255.0
    >>> from scipy.spatial import distance
    >>> distance.euclidean(a1, a2)
    255.0
    

    This is common, since many image libraries represent an image as an ndarray with dtype="uint8". This means that if you have a greyscale image which consists of very dark grey pixels (say all the pixels have color #000001) and you're diffing it against black image (#000000), you can end up with x-y consisting of 255 in all cells, which registers as the two images being very far apart from each other. For unsigned integer types (e.g. uint8), you can safely compute the distance in numpy as:

    np.linalg.norm(np.maximum(x, y) - np.minimum(x, y))
    

    For signed integer types, you can cast to a float first:

    np.linalg.norm(x.astype("float") - y.astype("float"))
    

    For image data specifically, you can use opencv's norm method:

    import cv2
    cv2.norm(x, y, cv2.NORM_L2)
    
    0 讨论(0)
提交回复
热议问题