将两个不同的图像直方图绘制为单个2D直方图

时间:2019-12-15 12:02:17

标签: python image numpy histogram histogram2d

我希望在x轴上绘制一个uint16图像的直方图,并在y轴上绘制另一个uint16图像的直方图,以便我将它们之间的关系的色图绘制为2D图。

this is the sort of plot I am after

我试图形成两个单独的直方图,然后在一个循环中构造2D数组,但这失败了。

〜python

first = np.histogram(img1,bins = 1000) 第一=第一[0]

second = np.histogram(img2,bins = 1000) 秒=秒[0]

empty_array = np.zeros((1000,1000),dtype = np.float64)

对于范围在1000的i:     对于范围(1000)中的j:         empty_array [i,j] =第一[j] +第二[1000-j]

2 个答案:

答案 0 :(得分:1)

这是使用seaborn的解决方案,如@kilozulu所建议。 我不会使用已经装箱的数据来生成此绘图,因为您正在丢失两个图像之间的数据点关联。而是直接输入像素意图:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

#dummy images
img1 = np.random.normal(0,10,(100,100))
img2 = np.random.normal(0,10,(100,100))

# make jointplot with linearised images:
sns.jointplot(img1.ravel(), img2.ravel(), kind='kde')

enter image description here

答案 1 :(得分:0)

如果您要研究两个变量的直方图以及它们在单个函数中的相互关系,请考虑阅读有关多元正态分布的文章。当然,这将适用于研究图像中像素的分布。 https://juanitorduz.github.io/multivariate_normal/

这似乎是您要执行的操作?:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(color_codes=True)
sns.set_context("notebook")
sns.set_style("darkgrid")


# %% Construct normal distribution data
n = 100
hist1 = np.random.normal(0,1,n)
hist2 = np.random.normal(0,1,n)

# %% Plot distributions on their own axis
sns.jointplot(x=hist1, y=hist2, kind="kde", space=0)

KDE Plot of multi-variate normal

与KDE绘图不同的过程,该过程实际上会找到定义您的数据的多元PDF,然后对PDF进行绘图。这次hist2的分布与hist1的分布不同,这使得轮廓图上的分布有所不同:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(color_codes=True)
sns.set_context("notebook")
sns.set_style("darkgrid")
from scipy.stats import multivariate_normal as mvn

# %% Create test data for multivariate PDF
n = 1000
hist1 = np.random.normal(0,1,n)
hist2 = np.random.normal(0,2,n)

# %% Calculate mean and covariance of data
mean = [hist1.mean(), hist2.mean()]
cov_mat = np.cov( np.array([hist1, hist2]) )

# %% Create multivariate function with calculated means and covariance
mv_norm_f = mvn(mean=mean, cov=cov_mat)

# %% Setup ranges of variables for PDF function
range = np.linspace(-1,1,n)
x, y = np.meshgrid(range, range, indexing='xy')
xy = np.empty(x.shape + (2,))
xy[:, :, 0] = x
xy[:, :, 1] = y
print(x.shape)
print(xy.shape)

# %% Call PDF function on ranges of variables
z = mv_norm_f.pdf( xy )

# %% Shaded contour plot the PDF
plt.figure()

plt.contourf(x, y, z)

plt.xlabel("X")
plt.ylabel("Y")
plt.colorbar()
plt.grid('on')
plt.show()

Shaded contour plot of multi-variate PDF

相关问题