| 1 | import json |
| 2 | import re |
| 3 | |
| 4 | import matplotlib.patches as patches |
| 5 | import matplotlib.pyplot as plt |
| 6 | import numpy as np |
| 7 | from PIL import Image |
| 8 | |
| 9 | |
| 10 | def normalize_bbox(model_type, x_min, y_min, x_max, y_max, image_width, image_height): |
| 11 | # Normalize coordinates |
| 12 | if model_type == "paligemma": |
| 13 | y_min_norm = max(0, min(y_min / 1024 * image_height, image_height)) |
| 14 | x_min_norm = max(0, min(x_min / 1024 * image_width, image_width)) |
| 15 | y_max_norm = max(0, min(y_max / 1024 * image_height, image_height)) |
| 16 | x_max_norm = max(0, min(x_max / 1024 * image_width, image_width)) |
| 17 | elif model_type == "qwen": |
| 18 | y_min_norm = y_min / 1000 * image_height |
| 19 | x_min_norm = x_min / 1000 * image_width |
| 20 | y_max_norm = y_max / 1000 * image_height |
| 21 | x_max_norm = x_max / 1000 * image_width |
| 22 | return x_min_norm, y_min_norm, x_max_norm, y_max_norm |
| 23 | |
| 24 | |
| 25 | def plot_image_with_bboxes(image, bboxes=None, labels=None, model_type="qwen"): |
| 26 | # Load the image if it's a string path, otherwise use the image object |
| 27 | image = Image.open(image) if isinstance(image, str) else image |
| 28 | image_width, image_height = image.size |
| 29 | |
| 30 | # Create figure and axes |
| 31 | fig, ax = plt.subplots(1) |
| 32 | |
| 33 | # Display the image |
| 34 | ax.imshow(image) |
| 35 | |
| 36 | if bboxes is not None: |
| 37 | # Check if bboxes is a list of dictionaries |
| 38 | if isinstance(bboxes, list) and all(isinstance(bbox, dict) for bbox in bboxes): |
| 39 | # Define colors for different objects |
| 40 | num_boxes = len(bboxes) |
| 41 | colors = plt.cm.rainbow(np.linspace(0, 1, num_boxes)) |
| 42 | |
| 43 | # Iterate over each bbox dictionary |
| 44 | for i, (bbox, color) in enumerate(zip(bboxes, colors)): |
| 45 | label = bbox.get("object", None) |
| 46 | bbox_coords = bbox.get("bboxes", None) |
| 47 | x_min, y_min, x_max, y_max = bbox_coords[0] |
| 48 | |
| 49 | # Normalize coordinates |
| 50 | x_min_norm, y_min_norm, x_max_norm, y_max_norm = normalize_bbox( |
| 51 | model_type, x_min, y_min, x_max, y_max, image_width, image_height |
| 52 | ) |
| 53 | |
| 54 | # Calculate width and height |
| 55 | width = x_max_norm - x_min_norm |
| 56 | height = y_max_norm - y_min_norm |
| 57 | |
| 58 | # Create and add the rectangle patch |
| 59 | rect = patches.Rectangle( |
| 60 | (x_min_norm, y_min_norm), |
| 61 | width, |
| 62 | height, |
| 63 | linewidth=2, |
| 64 | edgecolor=color, |
| 65 | facecolor="none", |
| 66 | ) |
| 67 | ax.add_patch(rect) |
| 68 | |
| 69 | # Add label if available |
| 70 | if label is not None: |
| 71 | ax.text( |
| 72 | x_min_norm, |
| 73 | y_min_norm, |
| 74 | label, |
| 75 | color=color, |
| 76 | fontweight="bold", |
| 77 | bbox=dict(facecolor="white", edgecolor=color, alpha=0.8), |
| 78 | ) |
| 79 | else: |
| 80 | # Original code for handling bboxes as a flat list |
| 81 | num_boxes = len(bboxes) // 4 |
| 82 | colors = plt.cm.rainbow(np.linspace(0, 1, num_boxes)) |
| 83 | |
| 84 | for i, color in zip(range(0, len(bboxes), 4), colors): |
| 85 | x_min, y_min, x_max, y_max = bboxes[i : i + 4] |
| 86 | |
| 87 | # Normalize coordinates |
| 88 | x_min_norm, y_min_norm, x_max_norm, y_max_norm = normalize_bbox( |
| 89 | model_type, x_min, y_min, x_max, y_max, image_width, image_height |
| 90 | ) |
| 91 | |
| 92 | # Calculate width and height |
| 93 | width = x_max_norm - x_min_norm |
| 94 | height = y_max_norm - y_min_norm |
| 95 | |
| 96 | # Create and add the rectangle patch |
| 97 | rect = patches.Rectangle( |
| 98 | (x_min_norm, y_min_norm), |
| 99 | width, |
| 100 | height, |
| 101 | linewidth=2, |
| 102 | edgecolor=color, |
| 103 | facecolor="none", |
| 104 | ) |
| 105 | ax.add_patch(rect) |
| 106 | |
| 107 | # Add label if available |
| 108 | if labels is not None and i // 4 < len(labels): |
| 109 | ax.text( |
| 110 | x_min_norm, |
| 111 | y_min_norm, |
| 112 | labels[i // 4], |
| 113 | color=color, |
| 114 | fontweight="bold", |
| 115 | bbox=dict(facecolor="white", edgecolor=color, alpha=0.8), |
| 116 | ) |
| 117 | |
| 118 | plt.axis("off") |
| 119 | plt.tight_layout() |
| 120 | |
| 121 | |
| 122 | def swap_x_y(bboxes): |
| 123 | bboxes[0], bboxes[1] = bboxes[1], bboxes[0] |
| 124 | bboxes[2], bboxes[3] = bboxes[3], bboxes[2] |
| 125 | return bboxes |
| 126 | |
| 127 | |
| 128 | def parse_bbox(bbox_str, model_type="paligemma"): |
| 129 | if model_type == "paligemma": |
| 130 | objects = [] |
| 131 | bboxes = bbox_str.split(";") |
| 132 | for bbox in bboxes: |
| 133 | reg = re.finditer(r"<loc(\d+)>", bbox) |
| 134 | name = bbox.split(">")[-1].strip() |
| 135 | objects.append( |
| 136 | { |
| 137 | "object": name, |
| 138 | "bboxes": [swap_x_y([int(loc.group(1)) for loc in reg])], |
| 139 | } |
| 140 | ) |
| 141 | return objects |
| 142 | if model_type == "qwen": |
| 143 | return json.loads(bbox_str.replace("```json", "").replace("```", "")) |