MS103
MS103

Reputation: 55

Find nearest value X in ndarray in numpy, Python

I have got a ndarray shaped into 2D matrix of values between 0 and 255. Let's name it img. Moreover, I have got value x between 0 and 255, for example 120. I want to create matrix dist_img which calculates distance to nearest value x or lower. So I would like to have something like this:

x = 120
img = [[100, 120, 130],
       [110, 140, 160],
       [130, 150, 170]]
some_function(img, x)

And get something like this

dist_img = [[0, 0, 1],
            [0, 1, 2],
            [1, 2, 3]]

If I can be peaky, I would love to have distance in taxicab geometry, but Euclidean geometry will work. Sorry for poor English, but I hope everything is understandable.

Upvotes: 0

Views: 160

Answers (1)

javidcf
javidcf

Reputation: 59731

Make a mask of the values that match the condition and then use scipy.ndimage.morphology.distance_transform_cdt to make the distance map:

import numpy as np
from scipy.ndimage.morphology import distance_transform_cdt

x = 120
img = np.array([[100, 120, 130],
                [110, 140, 160],
                [130, 150, 170]])
m = img <= x
d = distance_transform_cdt(~m, 'taxicab')
print(d)
# [[0 0 1]
#  [0 1 2]
#  [1 2 3]]

Upvotes: 2

Related Questions