简体   繁体   English

如何在python中设置溢出减法以导致零?

[英]How to set overflowed subtraction in python to result in a zero?

I am trying to find regions which have features strikingly different from the baseline.我试图找到特征与基线截然不同的区域。

To do that I subtract current image from the base, f and b are grayscale 2d image matrices.为此,我从基础中减去当前图像, fb是灰度二维图像矩阵。

diff = f - b

Some of the oeprations result in overflow and this leads to regions of high pixel value where really they should be set to zero.一些操作会导致溢出,这会导致像素值高的区域实际上应该将它们设置为零。

在此处输入图片说明

How do I specify that the operation diff = f - b should yield 0 for individual pixel value if f[x][y] < b[x][y] ?如果f[x][y] < b[x][y]我如何指定操作diff = f - b应该为单个像素值产生 0 ?

Here is one way of doing it in numpy that doesn't require casting to a larger integer type:这是在 numpy 中执行此操作的一种方法,不需要转换为更大的整数类型:

f - b.clip(None, f)

or, equivalently,或者,等效地,

f - np.minimum(b, f)

I fixed that by making my own function which compares each pixel before subtracting it to prevent any overflow from occuring.我通过创建自己的函数来解决这个问题,该函数在减去每个像素之前比较每个像素以防止发生任何溢出。

def custom_sub(i2,i1):      
    x =  len(i1)
    y =  len(i1[0])

    o = deepcopy(i1)

    for ix in range(x):             
            for iy in range(y):
                if i1[ix][iy] > i2[ix][iy]:
                    o[ix][iy] = 0
                else:
                    o[ix][iy] = i2[ix][iy]-i1[ix][iy]
    return o

This is the output, bright regions now only where the spark flash is occurring.这是输出,现在只有发生火花的明亮区域。

在此处输入图片说明

This question is similiar to mine.这个问题和我的很相似。 Subtraction in my case was performed with uint8 type, this can be converted to int16.在我的例子中,减法是用 uint8 类型执行的,这可以转换为 int16。 Resulting picture can then be iterated over and any negative number removed.然后可以迭代生成的图片并删除任何负数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM