| 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) |
|
|
| |
| 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并保存到磁盘 |
| """ |
| |
| all_feats = all_feats / np.linalg.norm(all_feats, axis=1, keepdims=True) |
| |
| index_cpu = faiss.IndexFlatIP(all_feats.shape[1]) |
| print("构建索引结束") |
| if use_gpu: |
| |
| res = faiss.StandardGpuResources() |
| index = faiss.index_cpu_to_gpu(res, 0, index_cpu) |
| print("FAISS 正在使用 GPU 进行计算...") |
| else: |
| index = index_cpu |
| print("FAISS 正在使用 CPU 进行计算...") |
|
|
| index.add(all_feats) |
|
|
| |
| _, indices = index.search(all_feats, K) |
|
|
| |
| 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 的计算,并计算平均相似度 |
| """ |
| |
| all_feats = all_feats / np.linalg.norm(all_feats, axis=1, keepdims=True) |
|
|
| |
| res = faiss.StandardGpuResources() |
|
|
| |
| index_cpu = faiss.IndexFlatIP(all_feats.shape[1]) |
| index = faiss.index_cpu_to_all_gpus(index_cpu) |
|
|
| 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]} ...") |
|
|
| |
| distances, indices = index.search(query_feats, K + 1) |
|
|
| |
| for j, idx in enumerate(range(i, i + query_feats.shape[0])): |
| filtered_indices = indices[j][1:] |
| filtered_distances = distances[j][1:] |
|
|
| |
| 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 |
|
|
| |
| 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_image_ids = knn_results[image_id][:num_neighbors] |
|
|
| |
| 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}") |
|
|
| |
| 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__": |
| |
| |
| 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) |