假设我有一个颜色直方图。在Python中是否有一种巧妙的方法可以从颜色直方图生成随机图像?
更具体地说,我想根据颜色直方图的分布为每个像素生成随机颜色。
谢谢!
更具体地说,我想根据颜色直方图的分布为每个像素生成随机颜色。
谢谢!
以下是来自链接文档的参数:
a : 1-D 数组或 int
如果是一个 ndarray,则从其元素中生成随机样本。 如果是 int,则生成的随机样本就像 a 是 np.arange(a) 一样。
size : int 或者 int 元组,可选
输出形状。 如果给定的形状为 (m, n, k),则会抽取 m * n * k 个样本。默认值为 None,此时返回单个值。
replace : boolean,可选
样本是否带或不带替换
p : 1-D 数组或类似数组,可选
a 中每个条目相关联的概率。 如果未给出,则假定样本在 a 的所有条目上具有均匀分布。
参数 shape
应该是您的图像大小,例如 (100,100)
。 参数 a
应该是分布,参数 p
应该是由直方图生成的分布。
例如:
import numpy as np
bins = np.array([0,0.5,1])
freq = np.array([1.,2,3])
prob = freq / np.sum(freq)
image = np.random.choice(bins, size=(100,100), replace=True, p=prob)
plt.imshow(image)
收益率
为了支持多个颜色通道,您有几个选择。这里是其中之一,我们从颜色索引中选择而不是颜色本身:
colors = np.array([(255.,0,0), (0,255,0), (0,0,255)])
indices = np.array(range(len(colors)))
im_indices = np.random.choice(indices, size=(100,100), p=prob)
image = colors[im_indices]
random.choices 可以从加权种群中选择元素。例如:
>>> import random
>>> histogram = {"white": 1, "red": 5, "blue": 10}
>>> pixels = random.choices(list(histogram.keys()), list(histogram.values()), k=25)
>>> pixels
['blue', 'red', 'red', 'red', 'blue', 'red', 'red', 'white', 'blue', 'white', 'red', 'red', 'blue', 'red', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue']