import json import random from pathlib import Path import matplotlib.pyplot as plt import matplotlib.patches as patches from PIL import Image import numpy as np def scale_bbox_to_1023(bbox, img_width, img_height): """将 bbox 坐标缩放到 0-1023 范围""" x1, y1, x2, y2 = bbox x1_scaled = int(x1 / img_width * 1023) y1_scaled = int(y1 / img_height * 1023) x2_scaled = int(x2 / img_width * 1023) y2_scaled = int(y2 / img_height * 1023) return [x1_scaled, y1_scaled, x2_scaled, y2_scaled] def visualize_fewshot_sample(image_path, prompt_boxes, all_boxes, category, output_path, img_width=None, img_height=None): """ 可视化 few-shot 样本 - prompt_boxes: 蓝色 (prompt 框) - all_boxes: 红色 (所有框) """ # 读取图片 img = Image.open(image_path) if img_width and img_height: # 如果需要缩放显示,可以调整 img = img.resize((img_width, img_height)) fig, ax = plt.subplots(1, figsize=(12, 9)) ax.imshow(img) # 记录已画的框,用于处理重叠 drawn_boxes = [] # 先画所有框(红色,较粗,带透明度) for box_info in all_boxes: bbox = box_info['bbox'] class_id = box_info.get('class_id', 0) # 创建矩形 rect = patches.Rectangle( (bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], linewidth=2, edgecolor='red', facecolor='none', alpha=0.8 ) ax.add_patch(rect) # 添加标签(在框的左上角) label = f"{category}_{class_id}" ax.text( bbox[0], bbox[1] - 5, label, fontsize=8, color='red', weight='bold', bbox=dict(boxstyle='round,pad=0.3', facecolor='white', alpha=0.7, edgecolor='red') ) drawn_boxes.append(('red', bbox)) # 再画 prompt 框(蓝色,虚线,更突出) for box_info in prompt_boxes: bbox = box_info['bbox'] class_id = box_info.get('class_id', 0) # 创建矩形(蓝色虚线) rect = patches.Rectangle( (bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], linewidth=3, edgecolor='blue', facecolor='none', linestyle='--', alpha=0.9 ) ax.add_patch(rect) # 添加标签(在框的右上角) label = f"PROMPT_{category}_{class_id}" ax.text( bbox[2], bbox[1] - 5, label, fontsize=8, color='blue', weight='bold', bbox=dict(boxstyle='round,pad=0.3', facecolor='white', alpha=0.7, edgecolor='blue'), horizontalalignment='right' ) # 添加图例 from matplotlib.patches import Patch legend_elements = [ Patch(facecolor='none', edgecolor='blue', linewidth=3, linestyle='--', label='Prompt Boxes (Few-shot)'), Patch(facecolor='none', edgecolor='red', linewidth=2, label='All GT Boxes') ] ax.legend(handles=legend_elements, loc='upper right', fontsize=10) # 添加标题 ax.set_title(f"Few-shot Detection (k={len(prompt_boxes)} prompts)", fontsize=14, weight='bold') ax.axis('off') plt.tight_layout() plt.savefig(output_path, dpi=150, bbox_inches='tight') plt.close() print(f" 保存可视化: {output_path}") def visualize_multiple_samples(data_file, output_dir, num_samples=10): """ 可视化多个样本 """ output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) # 读取所有数据 samples = [] with open(data_file, 'r', encoding='utf-8') as f: for line in f: samples.append(json.loads(line.strip())) # 随机选择 num_samples 个样本 if len(samples) > num_samples: selected_samples = random.sample(samples, num_samples) else: selected_samples = samples print(f"从 {len(samples)} 个样本中选择了 {len(selected_samples)} 个进行可视化") for idx, data in enumerate(selected_samples): image_path = data['image'] prompt_boxes = data['prompt_boxes'] all_boxes = data['all_boxes'] category = all_boxes[0]['category'] if all_boxes else 'unknown' k = data['k'] # 输出文件路径 output_path = output_dir / f"sample_{idx+1}_k{k}.png" print(f"\n可视化样本 {idx+1}:") print(f" 图片: {Path(image_path).name}") print(f" K={k}, Prompt框数={len(prompt_boxes)}, 总框数={len(all_boxes)}") print(f" 类别: {category}") try: visualize_fewshot_sample( image_path, prompt_boxes, all_boxes, category, output_path ) except Exception as e: print(f" 错误: {e}") print(f"\n可视化完成!保存到: {output_dir}") def main(): # 设置随机种子 random.seed(42) # 输入文件(k=2 的数据) input_file = Path("/home/disk2/hjl/ICL_QWEN/ICL_benchmark/fewshot_data/nested/fewshot_k2_nested.jsonl") # 输出目录 output_dir = Path("/home/disk2/hjl/ICL_QWEN/ICL_benchmark/visualizations_k2") print("="*60) print("Few-shot 可视化工具 (k=2)") print("="*60) print(f"输入文件: {input_file}") print(f"输出目录: {output_dir}") print() # 可视化 10 个样本 visualize_multiple_samples(input_file, output_dir, num_samples=10) if __name__ == "__main__": main()