x-axis
和y-axis
是一组图像。测量成对相似度的图。
如何在 python3
中绘制这个数字。基本上,我有 50
图片。这将是 50x50
矩阵图 50
图像在 x-axis
和y-axis
.
我的目标是绘制一个像这样的图形(这个是不对称的,xlabel
和ylabel
是文本,我希望我的是图像。)
假设相似度是随机的
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,这个数字取决于带有图像标签的方 block 的大小,您可能需要在您的案例。
在我的例子中,相似矩阵是随机的,我生成范围为 [-1;+1] 的数字。矩阵的右上三角形被白化,因为没有必要。
如果您不需要在相似性单元格内绘制数字,请设置 annot = False
而不是当前的 annot = True
。
接下来的代码绘制这样的图像:
代码:
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()
关于python - 如何绘制图像-图像相似度矩阵图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67310634/