python - 将联合直方图的值映射回图像空间

标签 python numpy matplotlib imaging

我有两个 8 位灰度图像,尺寸为 166 x 256 像素。我计算了它们之间的联合直方图,并发现了一些有趣的簇,我想将它们映射回图像空间中的值以找到其对应的位置。因此,对于两个图像 A 和 B(已通过 numpy 数组访问其值)

import numpy as np
import matplotlib.pyplot as plt
rows, cols = A.shape[0], B.shape[1]
N = 256 # bins

#### Numpy's method
#H,xedge,yedge = np.histogram2d(A, B, bins=(N,N))


#### Manually
H1 = np.zeros((N, N), dtype=float)
Hindex = []
IMGindex = []
for i,j in product(range(rows), range(cols)):
    H1[A[i,j], B[i,j]] = H1[A[i,j], B[i,j]] + 1
    IMGindex.append((i,j))
    Hindex.append((A[i,j], B[i,j]))

img = plt.imshow(H1.T, origin='low', interpolation='nearest') 
img.set_cmap('hot')                                                                         

plt.colorbar()
plt.show(img) 

现在假设这会产生下图: x 在 0 到 ~45 之间、y 在 0 到 ~2-3 之间的区域发生了一些事情。这可能是一个有点空泛的问题,但是如何使用我存储的 IMGindex 和 Hindex 数组映射回原始图像中的这些值?或者我对“反向映射”问题的处理完全错误?

最佳答案

您的直方图可能更容易被视为交叉图。 x 轴对应于图像 B和图像的 y 轴 A .

换句话说,您感兴趣的区域可能是图像 A 中恒定低值的大面积区域。 。 (也许是边框或背景值?)

要“向后”使用 bool 索引,而不是 IMGindexHindex数组。例如:

xmin, xmax = 0, 45
ymin, ymax = 0, 3
region = (A >= ymin) & (A <= ymax) & (B >= xmin) & (B <= xmax)

(不过,在这种情况下,您可能只需要 region = A <= 3 就可以逃脱惩罚。)

要通过“灰显”其他所有内容来突出显示这些区域,您可以执行以下操作:(我使用随机数据,这比实际情况要复杂一些,但希望它能给您一些想法.)

import numpy as np
import matplotlib.pyplot as plt

A = np.random.random((10,10))
B = np.random.random((10,10))

region = (A > 0.5) & (B > 0.5)

fig, axes = plt.subplots(ncols=2)
for ax, image in zip(axes.flat,[A, B]):
    im = ax.imshow(image, cmap='copper')
    fig.colorbar(im, ax=ax, orientation='horizontal')

    mask = np.ma.masked_where(region, ~region)
    ax.imshow(mask, cmap='gray_r', interpolation='none', alpha=0.5)

plt.show()

enter image description here

关于python - 将联合直方图的值映射回图像空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26069888/

相关文章:

Python RegEx 缺少括号错误

python - 正确使用 fftw fft

python - 你如何计算无限分布的期望值? (特别是在 python )

python - Matplotlib 散点图,其中每个 x 的 y 值数组

python - Pandas 用 yerr 绘图给出关键错误 :0

python - 正则表达式查找两个可选模式之间的所有内容,如果没有则返回全部

python - argparse,两个参数相互依赖

python - 如何在 python 中删除给定开始和结束标记的子字符串?

python - : import scipy as sp/sc 的官方缩写

python - networkx 与 matplotlib 的交互