| import matplotlib.pyplot as plt |
| from PIL import Image |
| import matplotlib.patches as patches |
|
|
| |
| image_path = "demo_images/yidali2.jpg" |
| output_path = "output_image_2.jpg" |
| image = Image.open(image_path) |
|
|
| |
| data = [ |
| {"bbox_2d": [668, 240, 799, 538], "label": "Person"}, |
| {"bbox_2d": [531, 319, 703, 580], "label": "Person"}, |
| {"bbox_2d": [207, 235, 348, 569], "label": "Person"}, |
| {"bbox_2d": [623, 344, 691, 389], "label": "Violin"}, |
| {"bbox_2d": [281, 195, 425, 560], "label": "cello"}, |
| {"bbox_2d": [0, 302, 208, 492], "label": "bicycle"}, |
| {"bbox_2d": [338, 316, 432, 449], "label": "bicycle"}, |
| {"bbox_2d": [679, 270, 840, 384], "label": "guitar"} |
| ] |
|
|
| |
| color_map = { |
| "Person": "#ff5733", |
| "Violin": "#33ff57", |
| "cello": "#5733ff", |
| "bicycle": "#e3d820", |
| "guitar": "#ff33a1" |
| } |
|
|
| |
| fig, ax = plt.subplots(1, figsize=(12, 8)) |
| ax.imshow(image) |
|
|
| |
| instance_count = {} |
| for item in data: |
| bbox = item["bbox_2d"] |
| label = item["label"] |
|
|
| |
| if label not in instance_count: |
| instance_count[label] = 0 |
| color = color_map[label] |
| instance_count[label] += 1 |
|
|
| |
| rect = patches.Rectangle( |
| (bbox[0], bbox[1]), |
| bbox[2] - bbox[0], |
| bbox[3] - bbox[1], |
| linewidth=4, |
| edgecolor=color, |
| facecolor="none" |
| ) |
| ax.add_patch(rect) |
|
|
| |
| ax.text( |
| bbox[0], |
| bbox[1] - 10, |
| label, |
| color="white", |
| fontsize=13, |
| bbox=dict(facecolor=color, edgecolor="none", boxstyle="round,pad=0.2") |
| ) |
|
|
| |
| ax.axis("off") |
|
|
| |
| plt.savefig(output_path, bbox_inches="tight", pad_inches=0, dpi=300) |
| plt.close() |
|
|
| print(f"Image saved to {output_path}") |