| 1 | import json |
| 2 | import re |
| 3 | from typing import Union |
| 4 | |
| 5 | import matplotlib.patches as patches |
| 6 | import matplotlib.pyplot as plt |
| 7 | import numpy as np |
| 8 | from PIL import Image |
| 9 | |
| 10 | |
| 11 | def normalize_bbox(model_type, x_min, y_min, x_max, y_max, image_width, image_height): |
| 12 | # Normalize coordinates |
| 13 | if model_type == "paligemma": |
| 14 | y_min_norm = max(0, min(y_min / 1024 * image_height, image_height)) |
| 15 | x_min_norm = max(0, min(x_min / 1024 * image_width, image_width)) |
| 16 | y_max_norm = max(0, min(y_max / 1024 * image_height, image_height)) |
| 17 | x_max_norm = max(0, min(x_max / 1024 * image_width, image_width)) |
| 18 | elif model_type == "qwen": |
| 19 | y_min_norm = y_min / 1000 * image_height |
| 20 | x_min_norm = x_min / 1000 * image_width |
| 21 | y_max_norm = y_max / 1000 * image_height |
| 22 | x_max_norm = x_max / 1000 * image_width |
| 23 | return x_min_norm, y_min_norm, x_max_norm, y_max_norm |
| 24 | |
| 25 | |
| 26 | def plot_image_with_bboxes(image, bboxes=None, labels=None, model_type="qwen"): |
| 27 | # Load the image if it's a string path, otherwise use the image object |
| 28 | image = Image.open(image) if isinstance(image, str) else image |
| 29 | image_width, image_height = image.size |
| 30 | |
| 31 | # Create figure and axes |
| 32 | fig, ax = plt.subplots(1) |
| 33 | |
| 34 | # Display the image |
| 35 | ax.imshow(image) |
| 36 | |
| 37 | if bboxes is not None: |
| 38 | # Check if bboxes is a list of dictionaries |
| 39 | if isinstance(bboxes, list) and all(isinstance(bbox, dict) for bbox in bboxes): |
| 40 | # Define colors for different objects |
| 41 | num_boxes = len(bboxes) |
| 42 | colors = plt.cm.rainbow(np.linspace(0, 1, num_boxes)) |
| 43 | |
| 44 | # Iterate over each bbox dictionary |
| 45 | for i, (bbox, color) in enumerate(zip(bboxes, colors)): |
| 46 | label = bbox.get("object", None) |
| 47 | bbox_coords = bbox.get("bboxes", None) |
| 48 | x_min, y_min, x_max, y_max = bbox_coords[0] |
| 49 | |
| 50 | # Normalize coordinates |
| 51 | x_min_norm, y_min_norm, x_max_norm, y_max_norm = normalize_bbox( |
| 52 | model_type, x_min, y_min, x_max, y_max, image_width, image_height |
| 53 | ) |
| 54 | |
| 55 | # Calculate width and height |
| 56 | width = x_max_norm - x_min_norm |
| 57 | height = y_max_norm - y_min_norm |
| 58 | |
| 59 | # Create and add the rectangle patch |
| 60 | rect = patches.Rectangle( |
| 61 | (x_min_norm, y_min_norm), |
| 62 | width, |
| 63 | height, |
| 64 | linewidth=2, |
| 65 | edgecolor=color, |
| 66 | facecolor="none", |
| 67 | ) |
| 68 | ax.add_patch(rect) |
| 69 | |
| 70 | # Add label if available |
| 71 | if label is not None: |
| 72 | ax.text( |
| 73 | x_min_norm, |
| 74 | y_min_norm, |
| 75 | label, |
| 76 | color=color, |
| 77 | fontweight="bold", |
| 78 | bbox=dict(facecolor="white", edgecolor=color, alpha=0.8), |
| 79 | ) |
| 80 | else: |
| 81 | # Original code for handling bboxes as a flat list |
| 82 | num_boxes = len(bboxes) // 4 |
| 83 | colors = plt.cm.rainbow(np.linspace(0, 1, num_boxes)) |
| 84 | |
| 85 | for i, color in zip(range(0, len(bboxes), 4), colors): |
| 86 | x_min, y_min, x_max, y_max = bboxes[i : i + 4] |
| 87 | |
| 88 | # Normalize coordinates |
| 89 | x_min_norm, y_min_norm, x_max_norm, y_max_norm = normalize_bbox( |
| 90 | model_type, x_min, y_min, x_max, y_max, image_width, image_height |
| 91 | ) |
| 92 | |
| 93 | # Calculate width and height |
| 94 | width = x_max_norm - x_min_norm |
| 95 | height = y_max_norm - y_min_norm |
| 96 | |
| 97 | # Create and add the rectangle patch |
| 98 | rect = patches.Rectangle( |
| 99 | (x_min_norm, y_min_norm), |
| 100 | width, |
| 101 | height, |
| 102 | linewidth=2, |
| 103 | edgecolor=color, |
| 104 | facecolor="none", |
| 105 | ) |
| 106 | ax.add_patch(rect) |
| 107 | |
| 108 | # Add label if available |
| 109 | if labels is not None and i // 4 < len(labels): |
| 110 | ax.text( |
| 111 | x_min_norm, |
| 112 | y_min_norm, |
| 113 | labels[i // 4], |
| 114 | color=color, |
| 115 | fontweight="bold", |
| 116 | bbox=dict(facecolor="white", edgecolor=color, alpha=0.8), |
| 117 | ) |
| 118 | |
| 119 | plt.axis("off") |
| 120 | plt.tight_layout() |
| 121 | |
| 122 | |
| 123 | def swap_x_y(bboxes): |
| 124 | bboxes[0], bboxes[1] = bboxes[1], bboxes[0] |
| 125 | bboxes[2], bboxes[3] = bboxes[3], bboxes[2] |
| 126 | return bboxes |
| 127 | |
| 128 | |
| 129 | def parse_bbox(bbox_str, model_type="paligemma"): |
| 130 | if model_type == "paligemma": |
| 131 | objects = [] |
| 132 | bboxes = bbox_str.split(";") |
| 133 | for bbox in bboxes: |
| 134 | reg = re.finditer(r"<loc(\d+)>", bbox) |
| 135 | name = bbox.split(">")[-1].strip() |
| 136 | objects.append( |
| 137 | { |
| 138 | "object": name, |
| 139 | "bboxes": [swap_x_y([int(loc.group(1)) for loc in reg])], |
| 140 | } |
| 141 | ) |
| 142 | return objects |
| 143 | if model_type == "qwen": |
| 144 | return json.loads(bbox_str.replace("```json", "").replace("```", "")) |
| 145 | |
| 146 | |
| 147 | def parse_points(points_str): |
| 148 | """Parse points from XML-like string into x and y coordinates""" |
| 149 | # Handle case where points_str is already a tuple |
| 150 | if isinstance(points_str, tuple): |
| 151 | return points_str |
| 152 | |
| 153 | # Extract x and y coordinates from attributes |
| 154 | x_coords = [] |
| 155 | y_coords = [] |
| 156 | |
| 157 | # Handle multi-point format |
| 158 | if 'x1="' in points_str: |
| 159 | i = 1 |
| 160 | while True: |
| 161 | try: |
| 162 | x = float(points_str.split(f'x{i}="')[1].split('"')[0]) |
| 163 | y = float(points_str.split(f'y{i}="')[1].split('"')[0]) |
| 164 | x_coords.append(x) |
| 165 | y_coords.append(y) |
| 166 | i += 1 |
| 167 | except IndexError: |
| 168 | break |
| 169 | # Handle single point format |
| 170 | elif 'x="' in points_str: |
| 171 | x = float(points_str.split('x="')[1].split('"')[0]) |
| 172 | y = float(points_str.split('y="')[1].split('"')[0]) |
| 173 | x_coords.append(x) |
| 174 | y_coords.append(y) |
| 175 | |
| 176 | # Extract labels from points string |
| 177 | try: |
| 178 | labels = points_str.split('alt="')[1].split('">')[0].split(", ") |
| 179 | item_labels = labels # Use the alt labels to maintain order |
| 180 | except IndexError: |
| 181 | # If no labels found, create numbered labels |
| 182 | item_labels = [f"Point {i+1}" for i in range(len(x_coords))] |
| 183 | |
| 184 | return x_coords, y_coords, item_labels |
| 185 | |
| 186 | |
| 187 | # Parse the points string |
| 188 | def plot_locations(points: Union[str, tuple], image): |
| 189 | # Parse points |
| 190 | if isinstance(points, str): |
| 191 | x_coords, y_coords, item_labels = parse_points(points) |
| 192 | else: |
| 193 | x_coords, y_coords, item_labels = points |
| 194 | |
| 195 | # Create figure and axis |
| 196 | plt.figure(figsize=(10, 8)) |
| 197 | |
| 198 | # Get image dimensions for normalization |
| 199 | img_width, img_height = image.size |
| 200 | |
| 201 | # Normalize coordinates |
| 202 | x_norm = [(x / 100) * img_width for x in x_coords] |
| 203 | y_norm = [(y / 100) * img_height for y in y_coords] |
| 204 | if len(item_labels) != len(x_norm): |
| 205 | item_labels *= len(x_norm) |
| 206 | |
| 207 | plt.imshow(image) |
| 208 | |
| 209 | # Plot points with different colors for each label |
| 210 | colors = ["red", "blue", "green", "orange", "purple"] |
| 211 | for i, (x, y, label) in enumerate(zip(x_norm, y_norm, item_labels)): |
| 212 | color = colors[i % len(colors)] |
| 213 | plt.plot(x, y, "o", color=color, markersize=5, label=label) |
| 214 | |
| 215 | # Add individual labels |
| 216 | plt.annotate( |
| 217 | label, |
| 218 | (x, y), |
| 219 | xytext=(0, 10), |
| 220 | textcoords="offset points", |
| 221 | ha="center", |
| 222 | color=color, |
| 223 | ) |
| 224 | |
| 225 | plt.title("Object Locations") |
| 226 | plt.legend() |
| 227 | plt.show() |