Python imshow 正态分布 2D numpy 数组数据的比例

Python imshow scale for normal distribution 2D numpy array data

我想缩放来自具有正态分布的 numpy 数组的显示数据。 Tutorial here 建议使用 clim,但在示例中限制被硬编码为 clim=(0.0, 0.7)。从教程中以前的直方图中获取这些值:

所以,我需要一种漂亮的方法来获得 clim 值(无需硬编码),也许使用标准偏差(1 西格玛、2 西格玛、3 西格玛)来获得 主要值:

我该怎么做?

要获得正态分布,您可以使用 scipy.optimize.curve_fit 将高斯函数拟合到直方图。按照读取图像并获取直方图的步骤,以下是拟合直方图的方法:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from scipy.optimize import curve_fit

# Read image
img=mpimg.imread('stinkbug.png')

# Get histogram
hist,bins,_ = plt.hist(img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')

# Get centers of histogram bins
bin_centers = np.mean([bins[:-1],bins[1:]], axis=0)

# Define the Gaussian function
def gaussian(x, mu, sigma, amp):
    return amp*np.exp( -(x - mu)**2 / (2.*sigma**2))

# Curve fit
p_opt,_ = curve_fit(gaussian, bin_centers, hist)

# Get the fit parameters
mu, sigma, amp = p_opt

您可以查看合身度:

fit = gaussian(bin_centers, mu, sigma, amp)
plt.plot(bin_centers, hist)
plt.plot(bin_centers, fit)

然后就可以使用clim的拟合参数了。首先,这是原始图像:

plt.imshow(img)

此处将像素颜色限制在 3-sigma 范围内:

plt.imshow(img, clim=(mu-3*sigma, mu+3*sigma))