用matplotlib制作渐变光点

Making gradient light spots with matplotlib

我正在尝试使用以下示例在天空图像上制作光点:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize


def normal_pdf(x, mean, var):
    return np.exp(-(x - mean)**2 / (2*var))


# Generate the space in which the blobs will live
xmin, xmax, ymin, ymax = (0, 100, 0, 100)
n_bins = 100
xx = np.linspace(xmin, xmax, n_bins)
yy = np.linspace(ymin, ymax, n_bins)

# Generate the blobs. The range of the values is roughly -.0002 to .0002
means_high = [20, 50]
means_low = [50, 60]
var = [150, 200]

gauss_x_high = normal_pdf(xx, means_high[0], var[0])
gauss_y_high = normal_pdf(yy, means_high[1], var[0])

gauss_x_low = normal_pdf(xx, means_low[0], var[1])
gauss_y_low = normal_pdf(yy, means_low[1], var[1])

weights = (np.outer(gauss_y_high, gauss_x_high)
           - np.outer(gauss_y_low, gauss_x_low))

# We'll also create a grey background into which the pixels will fade
greys = np.full((*weights.shape, 3), 70, dtype=np.uint8)

# First we'll plot these blobs using ``imshow`` without transparency.
vmax = np.abs(weights).max()
imshow_kwargs = {
    'vmax': vmax,
    'vmin': -vmax,
    'cmap': 'RdYlBu',
    'extent': (xmin, xmax, ymin, ymax),
}

fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, **imshow_kwargs)
ax.set_axis_off()

这给了我这张照片:

我需要相同的形状但不同的颜色,像这样(最好是随机的):

我正在阅读 the documentation,但我无法理解更改这些颜色。请帮忙。

下面的代码使用了一些随机生成的均值、方差和比例因子。以及两种蓝色阴影之间的色图。欢迎进一步尝试。

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

def normal_pdf(x, mean, var):
    return np.exp(-(x - mean) ** 2 / (2 * var))

xmin, xmax = 0, 50
ymin, ymax = 0, 30
xs = np.linspace(xmin, xmax, 300)
ys = np.linspace(ymin, ymax, 200)
weights = np.zeros((len(ys), len(xs)))
N = 5
for mean0, mean1, var, scale in zip(np.random.uniform(xs.min(), xs.max(), N),
                                    np.random.uniform(ys.min(), ys.max(), N),
                                    np.random.uniform(10, 20, N),
                                    np.random.uniform(0.8, 1.1, N)):
    weights += scale * np.outer(normal_pdf(ys, mean1, var), normal_pdf(xs, mean0, var))
cmap = LinearSegmentedColormap.from_list('', ['#2e4367', '#425b88'])
plt.imshow(weights, cmap=cmap, vmin=0, vmax=1, extent=[xmin, xmax, ymin, ymax])
plt.show()