从颜色直方图生成随机图像的最快方法是什么?

what is the fastest way to generate random images from a color histogram?

假设我有一个颜色直方图。 python 中是否有巧妙的方法从颜色直方图生成随机图像?

更具体地说,我想根据颜色直方图的分布生成具有随机颜色的每个像素。

谢谢!

numpy.random.choice

参数,来自链接文档:

a : 1-D array-like or int

If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a)

size : int or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

replace : boolean, optional

Whether the sample is with or without replacement

p : 1-D array-like, optional

The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in 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 可以 select 来自加权总体的元素。示例:

>>> 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']