如何在2d numpyarray中用1替换小于或等于0的值? [英] How can I replace values less than or equal to 0 with 1 in a 2d numpyarray?
问题描述
我需要采用两个图像numpyarrays的比例,不幸的是数据有一堆负值和零点散落。
I need to take the ratio of two image numpyarrays, and unfortunately the data has a bunch of negative values and zeros scattered about.
我找到了一个优雅的方法从numpyarray中删除值, pixels = pixels [pixels> 0]
(非常优雅),但遗憾的是不会替换值。
I found one elegant way to remove values from a numpyarray, pixels = pixels[pixels>0]
(really elegant), but unfortunately doesn't replace values.
我还尝试使用while循环,找到当前最小值和当前最小索引,将每个指定为1,直到没有值< = 0,但它没有'工作。
I also tried using a while loop, finding the current minimum value, and the current minimum index, assigning each to 1 until there is no value <=0, but it didn't work.
while(np.amin(pixels)<= 0):
print "found low value of ", np.amin(evenpixels), "at", np.unravel_index(np.argmin(evenpixels), im_sz), "setting to 1"
pixels[np.unravel_index(np.argmin(pixels), im_sz)] = 1
我对这个while循环有一些奇怪的行为,它永远无法退出尝试将最终的低值更改为1后的循环:它在(0,0)处找到0并在此处卡住。我无法理解,我想知道它是不是一个无关的bug。请注意,我的数据形状是(2160,2560)
。
I got some weird behavior with this while loop and it is never able to exit the loop after trying to change the final low value to 1: it finds a 0 at (0,0) and get stuck here. I can't understand that and I wonder if it is an unrelated bug. Note that the shape of my data is (2160, 2560)
.
推荐答案
如果像素的最小值可以是1(正整数),那么一个简单的修复是使用 np.clip
,例如:
If the minimum value a pixel can be is 1 (positive integers), then a simple fix is to use np.clip
, eg:
pixels = np.clip(pixels,min,np.inf)
在这种情况下, min = 1
。
这篇关于如何在2d numpyarray中用1替换小于或等于0的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!