基于t-SNE的图像描述子可视化:如何替换散点为对应图像?
把t-SNE散点替换为对应图像的实现方案
要实现将降维后的散点替换为关联图像,我们可以借助matplotlib的OffsetImage和AnnotationBbox工具,把小图像精准贴到t-SNE输出的二维坐标上。下面是修改后的完整代码和关键说明:
关键修改步骤
- 关联描述子与图像路径:确保每个4096维描述子对应到正确的图像文件(这里假设你的
fulldescriptors.txt每行格式为[图像文件名] [4096个浮点值],如果不是,你需要维护一个和描述子顺序一致的图像路径列表) - 导入图像放置工具:从matplotlib的
offsetbox模块导入处理图像定位的类 - 图像缩放处理:定义辅助函数加载并缩放图像,避免过大导致重叠
- 图像贴至坐标点:遍历每个降维后的坐标,将对应小图像添加到画布上
修改后的完整代码
import os import numpy as np from sklearn.manifold import TSNE import time import pandas as pd import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox # 1. 读取描述子并关联图像路径 table = [] img_paths = [] # 假设fulldescriptors.txt每行格式:图像文件名 + 空格分隔的4096个浮点值 with open(os.path.join("folder", "fulldescriptors.txt")) as f: for line in f.readlines(): line = line.strip() if not line: continue parts = line.split(" ") # 拼接完整图像路径(假设图像和描述子文件在同一个folder下) img_path = os.path.join("folder", parts[0]) # 读取4096维描述子 d = [float(i) for i in parts[1:]] table.append(d) img_paths.append(img_path) n_sne = len(table) df = pd.DataFrame(table) # 2. 运行t-SNE降维(改为2维即可,减少计算量) time_start = time.time() tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=50000) tsne_results = tsne.fit_transform(df) print(f"t-SNE完成,耗时: {time.time() - time_start:.2f}秒") # 3. 定义加载并缩放图像的辅助函数 def get_scaled_image(img_path, zoom=0.08): # 读取图像 img = plt.imread(img_path) # 返回缩放后的图像对象 return OffsetImage(img, zoom=zoom) # 4. 创建画布并放置图像 # 设置较大的画布尺寸,避免图像重叠 fig, ax = plt.subplots(figsize=(20, 20)) # 可选:先画一层淡色散点作为坐标参考(也可以省略) ax.scatter(tsne_results[:,0], tsne_results[:,1], alpha=0.2, s=10) # 遍历每个坐标和对应图像,贴到画布上 for x, y, img_path in zip(tsne_results[:,0], tsne_results[:,1], img_paths): try: img = get_scaled_image(img_path) # 创建图像标注框,关闭边框 ab = AnnotationBbox(img, (x, y), frameon=False) ax.add_artist(ab) except Exception as e: print(f"加载图像失败 {img_path}: {e}") # 隐藏坐标轴,让可视化更整洁 ax.axis('off') plt.show()
注意事项
- 调整缩放比例:根据你的图像大小,修改
zoom参数(比如0.05~0.15之间),避免图像过度重叠 - 抽样优化:如果你的图像数量超过1000张,建议抽样显示(比如取前500个),否则会出现严重卡顿和重叠问题
- 路径校验:确保
img_paths里的路径都是有效的,否则会抛出加载失败的错误
内容的提问来源于stack exchange,提问作者D.Giunchi
相关产品推荐
相关产品推荐

