我找到了类似但不适合我的问题的答案。我需要在接收到的RGB值中构建一些噪点,但值不能超过255或低于0。
我有以下示例:
red,green,blue = (253, 4, 130)
print(
(np.random.randint(red-10,red+10),
np.random.randint(green-10,green+10),
np.random.randint(blue-10,blue+10)))
# output values cannot be over 255 or under 0
#The following output would not be ok.
>>>(257, -2, 132)
如何从0-255范围内的任何点生成不超过255或0的随机+/- 10值?
您可以放置条件语句来检查生成的随机数是否在所需范围内。
代码:
import numpy as np
red,green,blue = (253, 4, 130)
def rand_within_rgb(inp, thres):
if np.random.randint(inp - thres, inp + thres) > 255:
return 255
elif np.random.randint(inp - thres, inp + thres) < 0:
return 0
else:
return np.random.randint(inp - thres, inp + thres)
print((rand_within_rgb(red, 10),
rand_within_rgb(green, 10),
rand_within_rgb(blue, 10)))
输出:
(253, 0, 127)
如果您不喜欢上面的剪辑,可以尝试将函数更改为下面提供的功能,这也会提供您所需的输出。
def rand_within_rgb(inp, thres):
if inp + thres > 255:
return np.random.randint(inp - thres, 255)
elif inp - thres < 0:
return np.random.randint(0, inp + thres)
else:
return np.random.randint(inp - thres, inp + thres)
为了确保您不受限制,使用min()
和max()
函数而不是if/else
语句会更优雅。
np.random.randint(max(x-10, 0), min(x+10, 255))
因此您的代码可以更改为
def mutate_color(x):
return np.random.randint(max(x-10, 0), min(x+10, 255))
red,green,blue = (253, 4, 130)
print(
mutate_color(red),
mutate_color(green),
mutate_color(blue)
)
您可以先计算随机值,然后将其钳位到所需的[0,255]范围,或者您可以先限制随机范围。
def clamp(n, minimum, maximum):
"""Returns n clamped to the range [minimum, maximum]."""
return max(minimum, min(n, maximum))
clamp(np.random.randint(red - 10, red + 10))
np.random.randint(max(0, red - 10), min(255, red + 10))
请注意,值的分布将有所不同。在第一个版本中,最初为5的值可以更改为[-5,15]范围内的值,该值将被裁剪为[0,15]。由于在[-5,0]范围内的所有值都将映射为0,因此新值变为0的机会更大(21之6)。
使用第二种方法,调整随机范围本身。最初为5的值将以相等的概率更改为[0,15]范围内的任何值。
您将不得不根据需要进行选择。