对于我的问题,我找到了类似但不合适的答案。我需要在接收到的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值?
发布于 2020-05-27 15:02:26
您可以放置一个条件语句来检查生成的随机数是否在您要求的范围内。
代码:
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)发布于 2020-05-27 15:14:46
为了确保保持在一定范围内,使用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)
)发布于 2020-05-27 15:27:29
您可以先计算随机值,然后将其钳制到所需的0,255范围,也可以先限制随机范围。
计算随机值,然后钳位
def clamp(value, minValue, maxValue):
"""Returns `value` clamped to the range [minValue, maxValue]."""
return max(minValue, min(value, maxValue))
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范围内的任何值。
你将不得不根据你想要的来选择。
https://stackoverflow.com/questions/62037041
复制相似问题