6

I got this 2D numpy array with missing values. Is there a simple (and reasonably fast) way of filling the nan values with the closest (preferably euclidean distance, but manhattan is ok too) non-nan value? I couldn't find such a function in numpy or scipy...

asked Jun 30, 2021 at 15:34
5
  • Not that this is not a duplicate of stackoverflow.com/questions/9537543/…, that question's title is just misleading Commented Jun 30, 2021 at 15:35
  • would filling the point with the average of the surrounding pixels be sufficient? Commented Jun 30, 2021 at 15:37
  • And if there are multiple different values the same distance away? Commented Jun 30, 2021 at 15:37
  • @Conic the surrounding pixels may be NaN too. But for my application, mean would be alright too Commented Jun 30, 2021 at 15:37
  • @Scott Hunter then any of these is fine Commented Jun 30, 2021 at 15:38

1 Answer 1

15

Use scipy.interpolate.NearestNDInterpolator.

E.g.:

from scipy.interpolate import NearestNDInterpolator
data = ... # shape (w, h)
mask = np.where(~np.isnan(data))
interp = NearestNDInterpolator(np.transpose(mask), data[mask])
filled_data = interp(*np.indices(data.shape))

Showing it in action (with black as the mask here, image_defect is from from here):

data = image_defect
mask = np.where(~(data == 0))
interp = NearestNDInterpolator(np.transpose(mask), data[mask])
image_result = interp(*np.indices(data.shape))

Then, using the plotting code from scipy: enter image description here

answered Jun 30, 2021 at 15:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.