0

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.

4
  • Can you elaborate on the scheme used for the mapping? Commented Mar 3, 2020 at 11:05
  • I am not sure if I understand the question, but I generate perlin noise with "noise" library, then I normalize it from [-1,1] to [0,255]. After that I say: "Everything under 120 is water". I want to find distance to nearest water Commented Mar 3, 2020 at 11:11
  • I mean how did you end up with each of the elements in dist_img? Why is dist_img[0,0] 0 and so on? Commented Mar 3, 2020 at 11:18
  • Oh, so if img[0,0] is lower of equal to x, then it is 0. If not, for each field I need to walk in matrix to get to nearest value <=x I add 1. I hope, it is more clear now Commented Mar 3, 2020 at 11:23

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

That's it! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.