Is it possible to shorten the if statements below ?
if r < 0: r = 0
elif r > 255: r = 255
if g < 0: g = 0
elif g > 255: g = 255
if b < 0: b = 0
elif b > 255: b = 255
3 Answers 3
This is what you call as clamping. Create a clamp function as below:
def clamp(n, smallest, largest):
return max(smallest, min(n, largest))
Now you can call it on your variables as
r = clamp(r, 0, 255)
Comments
You can use min and max.
r = min(max(r, 0), 255)
The inner expression makes sure r is at least 0. The outer expression makes sure it's no more than 255.
Comments
To answer your question on shorting the if statement code you provided and not providing an alternative solution to getting the same result as your if statement.
def rgb_8bit_trunc(r,g,b):
print("Input: r:{}, g:{}, b:{}".format(r,g,b))
r = 0 if r < 0 else r if r < 255 else 255
g = 0 if g < 0 else g if g < 255 else 255
b = 0 if b < 0 else b if b < 255 else 255
print("Output: r:{}, g:{}, b:{}".format(r,g,b))
rgb_8bit_trunc(256,256,256)
rgb_8bit_trunc(-1,-1,-1)
Each ternary conditional operator is equivalent to the if statement code below where 'value' may be any of your RGB variables.
if value < 255:
if value < 0:
value = 0
else:
value
else:
value = 255