jack
jack

Reputation: 923

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

Suppose I have a color histogram. Is there a slick way in python to generate a random image from the color histogram?

More specifically, I want to generate each pixel with a random color according to the distribution of the color histogram.

thanks!

Upvotes: 3

Views: 1286

Answers (2)

en_Knight
en_Knight

Reputation: 5381

numpy.random.choice

The arguments, from the linked docs:

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.


The argument shape should be the size of your image, e.g., (100,100). The argument a should be the distribution, and the argument p should be the distribution generated by the histogram.

For example,

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)

yields

Random image


To support multiple color channels, you have several options. Here is one, where we choose from the color indices instead of the colors themselves:

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]

Upvotes: 4

Kevin
Kevin

Reputation: 76194

random.choices can select elements from a weighted population. Example:

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

Upvotes: 1

Related Questions