import json
import numpy as np
import matplotlib.pyplot as plt
import random

json_file = '2D_Semantic_Map_839920.json'  # 或你的semantic_map_2d.json
with open(json_file, 'r') as f:
    instances = json.load(f)

# 推断画布shape（可根据所有bbox确定，或提前设定h, w）
max_x, max_y = 0, 0
for inst in instances:
    bbox = inst['bbox']  # [xmin, ymin, xmax, ymax]
    max_x = max(max_x, bbox[2])
    max_y = max(max_y, bbox[3])
h = max_y + 10  # 留边界
w = max_x + 10

plt.figure(figsize=(12, 10))
plt.axis('equal')
plt.xlim(0, w)
plt.ylim(h, 0)

category_color = {}
cat_set = set([inst['category_label'] for inst in instances])
cmap = plt.get_cmap('tab20')
cat2col = {cat: cmap(i % 20) for i, cat in enumerate(cat_set)}

# 可先清空背景
plt.imshow(np.zeros((h, w)), cmap='gray', vmin=0, vmax=1, alpha=0.05)

for inst in instances:
    cat = inst['category_label']
    color = cat2col[cat]
    bbox = inst['bbox']
    xmin, ymin, xmax, ymax = bbox
    xmin_flip = w - 1 - xmax
    xmax_flip = w - 1 - xmin
    rect = plt.Rectangle((xmin_flip, ymin), xmax_flip - xmin_flip, ymax - ymin,
                         edgecolor=color, fill=False, linewidth=2, alpha=0.9)
    plt.gca().add_patch(rect)
    plt.text(xmin_flip, ymin-2, f"{cat}", color=color, fontsize=9, backgroundcolor='white')
    # 高亮mask
    mask_coords = inst.get('mask_coords', [])
    for rr, cc in mask_coords:
        plt.plot(w - 1 - cc, rr, '.', markersize=1, color=color, alpha=0.6)


# 图例
for i, (cat, color) in enumerate(cat2col.items()):
    plt.scatter([], [], c=[color], label=cat)
# plt.legend(loc='best', fontsize=8, bbox_to_anchor=(1,1))

plt.title("Semantic Map 2D with Semantic (from JSON)")
plt.savefig('2D_Semantic_Map_wo_Occupancy_839920.png', bbox_inches='tight', dpi=300)
plt.show()