简体   繁体   English

停止数字为负的简单方法

[英]Simple way to stop a number going negative

I have a simple exercise. 我有一个简单的练习。 I need to minus 2 tuples from each other but I dont want the result to go negative, I want to stop at 0. Similarly I want to add 2 tuples but I want to upper limit the value to 255. 我需要彼此减去2个元组,但我不希望结果为负,我想在0处停止。类似地,我想添加2个元组,但我想将该值的上限限制为255。

So when I do (1,1,1)-(5,200,30) I should get the result (0,0,0) . 所以当我做(1,1,1)-(5,200,30)我应该得到结果(0,0,0) And if I do (200,10,150)+(90,20,50) I should get (255,30,200) . 如果我做到(200,10,150)+(90,20,50)我应该得到(255,30,200)

Are there any convenience functions in math or numpy that can do this? mathnumpy中是否有任何便利函数可以做到这一点?

Check clip in numpy numpy检查clip

np.clip(np.array((1,1,1))-np.array((5,200,30)),a_min=0,a_max=255)
Out[186]: array([0, 0, 0])

You can do something like choose max of (the result or 0). 您可以执行类似选择最大值(结果或0)的操作。 That way if the result is negative, it will return 0 instead. 这样,如果结果为负数,它将返回0。 For example: 例如:

t1 = (1,1,1)
t2 = (5, 200, 30)

for subtraction 减法

[max(x[0]-x[1], 0) for x in zip(t1, t2)]

for addition 补充

[min(x[0]+x[1], 255) for x in zip(t1, t2)]
def add(t1,t2):
    """
    input: t1,t2 are tuples.
    example t1(1,2,3) t2(7,8,9)
    result=(a=1+7,b=2+8,c=3+9)
    max of a, b, and c are 255
    """
    a=t1[0]+t2[0]
    b=t1[1]+t2[1]
    c=t1[2]+t2[2]
    if(a>255):
        a=255
    if(b>255):
        b=255
    if(c>255):
        c=255
    result=(a,b,c)
    return result

#CALLING
x=(1,1,1)
y=(5,200,30)
z=(200,10,150)
t=(90,20,50)


print(add(z,t))
(255, 30, 200)

A pure python way to clip values would be as follows: 截取值的纯python方法如下:

>>> x = (25, 400, 30) 
>>> tuple(map(min, zip(x, (255,255,255))))
(25, 255, 30)

Likewise for lower limit: 同样的下限:

>>> x = (25, -20, 30) 
>>> tuple(map(max, zip(x, (0,0,0))))
(25, 0, 30)

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

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