DeCLIP-TPAMI / code /model_vis_tools /compute_knn.py
xiaomoguhzz's picture
Upload code/model_vis_tools/compute_knn.py with huggingface_hub
7af759c verified
import faiss
import numpy as np
import glob
import json
import os
from pycocotools.coco import COCO
import matplotlib.pyplot as plt
from PIL import Image
def load_features_from_disk(save_dir):
"""
从磁盘读取保存的特征
"""
feature_files = sorted(glob.glob(os.path.join(save_dir, "features_batch_*.npy")))
id_files = sorted(glob.glob(os.path.join(save_dir, "ids_batch_*.npy")))
all_feats = []
all_image_ids = []
for feature_file, id_file in zip(feature_files, id_files):
feats = np.load(feature_file)
ids = np.load(id_file)
all_feats.append(feats)
all_image_ids.append(ids)
# 拼接所有特征和图像ID
all_feats = np.concatenate(all_feats, axis=0)
all_image_ids = np.concatenate(all_image_ids, axis=0)
return all_feats, all_image_ids
def compute_knn(all_feats, all_image_ids, save_file, K=5, use_gpu=True):
"""
计算KNN并保存到磁盘
"""
# 对特征进行 L2 归一化
all_feats = all_feats / np.linalg.norm(all_feats, axis=1, keepdims=True)
# 构建FAISS索引
index_cpu = faiss.IndexFlatIP(all_feats.shape[1]) # 使用内积(余弦相似度)
print("构建索引结束")
if use_gpu:
# 将索引迁移到 GPU
res = faiss.StandardGpuResources() # 初始化 GPU 资源
index = faiss.index_cpu_to_gpu(res, 0, index_cpu) # 将索引从 CPU 迁移到 GPU(0表示GPU ID)
print("FAISS 正在使用 GPU 进行计算...")
else:
index = index_cpu
print("FAISS 正在使用 CPU 进行计算...")
index.add(all_feats) # 添加特征到索引中
# 计算KNN
_, indices = index.search(all_feats, K)
# 存储KNN结果到 JSON 文件
knn_results = {str(all_image_ids[i]): all_image_ids[indices[i]].tolist() for i in range(len(all_image_ids))}
with open(save_file, "w") as f:
json.dump(knn_results, f)
print(f"KNN 计算完成,结果存储在 {save_file}")
def compute_knn_with_multi_gpu(all_feats, all_image_ids, save_file, K=7, query_batch_size=1024):
"""
使用多 GPU 加速 KNN 的计算,并计算平均相似度
"""
# 对特征进行 L2 归一化
all_feats = all_feats / np.linalg.norm(all_feats, axis=1, keepdims=True)
# 初始化 GPU 资源
res = faiss.StandardGpuResources() # 创建 GPU 资源
# 构建索引
index_cpu = faiss.IndexFlatIP(all_feats.shape[1]) # 内积索引
index = faiss.index_cpu_to_all_gpus(index_cpu) # 将索引分布到所有 GPU
print("正在将特征添加到多 GPU 索引中...")
index.add(all_feats) # 添加所有特征到索引
print(f"特征添加完成!索引大小:{index.ntotal} 个特征")
knn_results = {}
# 用于计算平均相似度
total_similarity = 0
total_count = 0
# 分块处理查询
for i in range(0, all_feats.shape[0], query_batch_size):
query_feats = all_feats[i:i+query_batch_size]
print(f"正在处理查询样本 {i}{i + query_feats.shape[0]} / {all_feats.shape[0]} ...")
# 查询 K + 1 个最近邻
distances, indices = index.search(query_feats, K + 1)
# 去掉自身(排名第 1 的 index)
for j, idx in enumerate(range(i, i + query_feats.shape[0])):
filtered_indices = indices[j][1:] # 排除第一个结果
filtered_distances = distances[j][1:] # 排除与自身的相似度
# 存储 KNN 结果
knn_results[str(all_image_ids[idx])] = all_image_ids[filtered_indices].tolist()
# 更新相似度统计
total_similarity += np.mean(filtered_distances)
total_count += len(filtered_distances)
# 计算所有图像的平均相似度
average_similarity = total_similarity / total_count if total_count > 0 else 0
# 存储 KNN 结果到 JSON 文件
with open(save_file, "w") as f:
json.dump(knn_results, f)
print(f"KNN 计算完成,结果存储在 {save_file}")
print(f"所有图像的平均相似度为:{average_similarity:.4f}")
def load_knn_results(knn_json_path):
"""
加载 KNN 结果
"""
with open(knn_json_path, "r") as f:
knn_results = json.load(f)
return knn_results
def load_coco_annotations(coco_json_path):
"""
加载 COCO 格式的标注
"""
coco = COCO(coco_json_path)
return coco
def get_image_path(coco, image_root, image_id):
"""
获取图像的完整路径
"""
img_info = coco.loadImgs(image_id)[0]
img_path = os.path.join(image_root, img_info["file_name"])
return img_path, img_info["file_name"]
def visualize_knn(image_id, knn_results, coco, image_root, save_path, num_neighbors=5):
"""
可视化指定图像及其 KNN,并保存到文件
"""
# 获取目标图像路径
query_img_path, query_img_name = get_image_path(coco, image_root, int(image_id))
# 获取 KNN 图像 ID 列表
knn_image_ids = knn_results[image_id][:num_neighbors]
# 加载 KNN 图像路径
knn_image_paths = [get_image_path(coco, image_root, int(knn_id))[0] for knn_id in knn_image_ids]
knn_image_names = [get_image_path(coco, image_root, int(knn_id))[1] for knn_id in knn_image_ids]
# 可视化
plt.figure(figsize=(15, 5))
# 显示查询图像
plt.subplot(1, num_neighbors + 1, 1)
query_img = Image.open(query_img_path).convert("RGB")
plt.imshow(query_img)
plt.axis("off")
plt.title(f"Query: {query_img_name}")
# 显示 KNN 图像
for i, (knn_img_path, knn_img_name) in enumerate(zip(knn_image_paths, knn_image_names), start=2):
knn_img = Image.open(knn_img_path).convert("RGB")
plt.subplot(1, num_neighbors + 1, i)
plt.imshow(knn_img)
plt.axis("off")
plt.title(f"KNN {i-1}: {knn_img_name}")
plt.tight_layout()
# 保存图片而不是显示
os.makedirs(os.path.dirname(save_path), exist_ok=True) # 确保保存目录存在
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close() # 关闭图形,释放内存
print(f"可视化结果已保存到 {save_path}")
if __name__ == "__main__":
# all_feats, all_image_ids = load_features_from_disk(save_dir="coco_knn_results")
# compute_knn_with_multi_gpu(all_feats, all_image_ids, save_file="knn_results.json", K=7,query_batch_size=32)
coco_json="/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/instances_train2017.json"
image_root="/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017"
knn_json="coco_knn_results/knn_results.json"
knn_results = load_knn_results(knn_json)
coco = load_coco_annotations(coco_json)
query_image_id = "72892"
save_path = f"visualizations/{query_image_id}_knn.png" # 保存图片的路径
visualize_knn(query_image_id, knn_results, coco, image_root, save_path, num_neighbors=5)