How can the Euclidean distance be calculated with NumPy?

后端 未结 22 1328
春和景丽
春和景丽 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: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)
    

提交回复
热议问题