正态分布二维numpy数组数据的Python imshow比例

标签 python numpy statistics imshow

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

Histogram data example

所以,我需要一种漂亮的方法来获取 clim 值(无需硬编码),也许使用标准差(1 sigma、2 sigma、3 sigma)来获取principal值:

Normal distribution

我怎样才能做到这一点?

最佳答案

要获得正态分布,您可以使用 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)

enter image description here

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

plt.imshow(img)

enter image description here

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

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

enter image description here

关于正态分布二维numpy数组数据的Python imshow比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53560923/

相关文章:

python - 如何删除groupby的最后一行

python - 合并缺少键的字典以创建组合字典

python - 如何通过其他数据框对一列的值进行分类?

r - Logistic 回归的模型拟合统计量

php - 我的自定义 PHP stdev 函数 VS mysql 的 STDDEV_POP

python - 如何在plotly 3D曲面图中标记区域?

python - 如何使用 psycopg2.sql 将列列表或 *(所有列)传递给动态 SQL 查询

python - 删除 numpy 数组中的重复元组(彼此直接相邻的元组)

python - 在 scipy 优化中限制/最小化步长?

algorithm - 给定一个真正的随机数生成器,每次调用输出 1 或 0,你如何使用它从任意范围中选择一个数字?