import json
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import random
# 读取JSON文件
with open(r'F:\openmmlab\mmdetection-main\data\balloon_dataset/balloon/train/via_region_data.json') as f:
annotations = json.load(f)
# 获取所有图像的ID
image_ids = list(annotations.keys())
# 随机选择16个图像ID
random_image_ids = random.sample(image_ids, 16)
# 创建一个4x4的子图
fig, axs = plt.subplots(4, 4, figsize=(16, 16))
# 遍历每个图像ID
for i, image_id in enumerate(random_image_ids):
# 获取图像的文件名和大小
filename = annotations[image_id]['filename']
size = annotations[image_id]['size']
# 读取图像文件
image = Image.open(f'F:\\openmmlab\\mmdetection-main\\data\\balloon_dataset\\balloon\\train/{filename}')
# 获取多边形注释信息
regions = annotations[image_id]['regions']
patches = []
for region_id, region_info in regions.items():
# 获取多边形顶点坐标
x = region_info['shape_attributes']['all_points_x']
y = region_info['shape_attributes']['all_points_y']
points = list(zip(x, y))
# 创建多边形对象
polygon = Polygon(points, True)
patches.append(polygon)
# 计算子图的行和列索引
row = i // 4
col = i % 4
# 在子图中显示图像和注释
axs[row, col].imshow(image)
axs[row, col].set_title(filename)
p = PatchCollection(patches, alpha=0.5, facecolor='none', edgecolor='yellow')
axs[row, col].add_collection(p)
# 调整子图的间距和轴的可见性
plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95, wspace=0.2, hspace=0.4)
for ax in axs.flat:
ax.axis('off')
# 显示子图
plt.show()