I have a 2D array representing a binary image.
I do:
ndxs=np.argwhere(obj_img==0)
to get an array of indices into the 2D image array that I can then use to replace the 0s there with nan
values via:
obj_img[ndxs]=np.nan
However, when I do this, I get an error similar to this, IndexError: index 22 is out of bounds for axis 0 with size 22
I tracked it down to the way the 2D array of ndxs is being interpreted in the obj_img[ndxs]
, but I don't understand why. If I instead do,
obj_img[ndxs[:,0],ndxs[:,1]]=np.nan
this works.
When I use ndxs
as the index into obj_img, what is python doing? Why is obj_img[ndxs]
not the same as obj_img[ndxs[:,0],ndxs[:,1]]
?
CodePudding user response:
You can use numpy built-in Fancy indexing
to replace all values when equals 0:
obj_img = obj_img.astype(float)
obj_img[obj_img==0] = np.nan
Note that you first have to convert it to float since NaN
is a special floating point sentinel value