如何绘制图像-图像相似度矩阵图?

问题描述

我正在尝试绘制如下图像。

enter image description here

x-axisy-axis 是一组图像。测量成对相似度的地图。

如何在 python3 中绘制此图。基本上,我有 50 图像。它将是 50x5050 中带有 x-axis 图像的 y-axis 矩阵映射。

我的目标是绘制一个类似的图形(这个图形是不对称的,xlabelylabel 是文本,我希望我的是图像。)

enter image description here

假设相似度是随机

import numpy as np

S = np.random.rand(3,3)

并且在某些路径中有 3 图像。

解决方法

我使用可通过 pip install numpy matplotlib seaborn tensorflow 安装的库实现了下一个代码片段。

Tensorflow 只是用来加载一些示例图像,在我的例子中是 MNIST 数字,在你的例子中你不需要 tensorflow,你有自己的图像。

Seaborn 用于绘制 HeatMap,它是一个类似矩阵的相关性。

内部代码 HeatMap() 函数用于绘制热图本身。 ImgLabels() 函数用于将图像绘制为 X/Y 刻度标签,该函数使用从 Tensorflow 的 MNIST 数据集获得的 MNIST 手绘数字图像,您可以使用任何图像代替。 ImgLabels() 函数中有一个可调整的参数,它是数字 -18/-14/+14,这个数字取决于带有图像标签的正方形的大小,您可能需要根据自己的情况更改它们。

在我的情况下,相似度矩阵是随机的,我生成范围为 [-1;+1] 的数字。矩阵的右上三角被白化,因为它不是必需的。

如果您不需要在相似性单元格内绘制数字,则设置 annot = False 而不是当前的 annot = True

接下来的代码绘制这样的图像:

enter image description here

代码

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

def ImgLabels(N,ax):
    imgs = None
    def offset_image(coord,name,ax):
        nonlocal imgs
        if imgs is None:
            import tensorflow as tf
            (imgs,_),(_,_) = tf.keras.datasets.mnist.load_data()

        img = imgs[name]
        im = matplotlib.offsetbox.OffsetImage(img,zoom = 0.9)
        im.image.axes = ax

        for co,xyb in [((0,coord),(-18,-14)),((coord,N),(+14,-18))]:
            ab = matplotlib.offsetbox.AnnotationBbox(im,co,xybox = xyb,frameon=False,xycoords='data',boxcoords="offset points",pad=0)
            ax.add_artist(ab)

    for i,c in enumerate(range(N)):
        offset_image(i,c,ax)

def HeatMap(N):
    sns.set_theme(style = "white")
    corr = np.random.uniform(-1,1,size = (N,N))
    mask = np.triu(np.ones_like(corr,dtype = bool))
    cmap = sns.diverging_palette(230,20,as_cmap=True)
    sns.heatmap(corr,mask=mask,cmap=cmap,vmin=-1,vmax=1,center=0,square=True,annot = True,xticklabels = False,yticklabels = False)

N = 10
f,ax = plt.subplots(figsize=(7,5))
HeatMap(N)
ImgLabels(N,ax)

plt.show()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...