File size: 7,100 Bytes
36e9a77 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
"""
Modified from: https://github.com/IDEA-Research/Rex-Omni/blob/master/rex_omni/utils.py
"""
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from PIL import Image, ImageDraw, ImageFont
class ColorGenerator:
"""Generate consistent colors for visualization"""
def __init__(self, color_type: str = "text"):
self.color_type = color_type
if color_type == "same":
self.color = tuple((np.random.randint(0, 127, size=3) + 128).tolist())
elif color_type == "text":
np.random.seed(3396)
self.num_colors = 300
self.colors = np.random.randint(0, 127, size=(self.num_colors, 3)) + 128
else:
raise ValueError(f"Unknown color type: {color_type}")
def get_color(self, text: str) -> Tuple[int, int, int]:
"""Get color for given text"""
if self.color_type == "same":
return self.color
if self.color_type == "text":
text_hash = hash(text)
index = text_hash % self.num_colors
color = tuple(self.colors[index])
return color
raise ValueError(f"Unknown color type: {self.color_type}")
def Visualize(
image: Image.Image,
annotations: Dict[str, List[Dict]],
font_size: int = 10,
draw_width: int = 6,
show_labels: bool = True,
custom_colors: Optional[Dict[str, Tuple[int, int, int]]] = None,
font_path: Optional[str] = None,
) -> Image.Image:
"""
Visualize predictions on image
Args:
image: Input image
annotations: Target entities (from the JSON file) need to be drawn on the image
font_size: Font size for labels
draw_width: Line width for drawing
show_labels: Whether to show text labels
custom_colors: Custom colors for categories
font_path: Path to font file
Returns:
Image with visualizations
"""
# Create a copy of the image
vis_image = image.copy()
draw = ImageDraw.Draw(vis_image)
# Load font
font = _load_font(font_size, font_path)
# Color generator
color_generator = ColorGenerator("same")
color_generator.color = (255, 0, 0)
for i, entity in enumerate(annotations):
# Get color
color = color_generator.color
annotation_type = entity.get("entity_type", "region")
coords = entity.get("bbox", [])
if annotation_type in ["region", "object", "human"] and len(coords) == 4:
draw_width = _adjust_draw_width(coords, vis_image.size)
if "label" in entity.keys():
_draw_box(draw, coords, color, draw_width, entity["label"], font, show_labels)
else:
_draw_box(draw, coords, color, draw_width, "", font, show_labels=False)
elif annotation_type == "point" and len(coords) == 2:
draw_width = 1
_draw_point(
draw, coords, color, draw_width, entity["label"], font, show_labels
)
return vis_image
def _adjust_draw_width(
coords: List[float],
image_size: Tuple[int, int]
) -> int:
x0, y0, x1, y1 = coords
image_width, image_height = image_size
box_width = max(1, x1 - x0)
box_height = max(1, y1 - y0)
box_area = box_width * box_height
image_total_area = image_width * image_height
if image_total_area == 0:
return 6
area_ratio = box_area / image_total_area
if area_ratio >= 0.05:
return 6
elif area_ratio >= 0.01:
return 4
elif area_ratio >= 0.005:
return 3
else:
return 2
def _load_font(font_size: int, font_path: Optional[str] = None) -> ImageFont.ImageFont:
"""Load font for drawing"""
font_paths = [
"C:/Windows/Fonts/simhei.ttf",
"C:/Windows/Fonts/arial.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/System/Library/Fonts/Arial.ttf",
"/System/Library/Fonts/Helvetica.ttc",
"arial.ttf",
]
font = None
for font_path_ in font_paths:
try:
font = ImageFont.truetype(font_path_, font_size)
break
except:
continue
if font is None:
font = ImageFont.load_default()
return font
def _draw_box(
draw: ImageDraw.ImageDraw,
coords: List[float],
color: Tuple[int, int, int],
draw_width: int,
label: str,
font: ImageFont.ImageFont,
show_labels: bool,
):
"""Draw bounding box"""
x0, y0, x1, y1 = [int(c) for c in coords]
# Check valid box
if x0 >= x1 or y0 >= y1:
return
# Draw rectangle
draw.rectangle([x0, y0, x1, y1], outline=color, width=draw_width)
# Draw label
if show_labels and label:
bbox = draw.textbbox((x0, y0), label, font)
box_h = bbox[3] - bbox[1]
y0_text = y0 - box_h - (draw_width * 2)
y1_text = y0 + draw_width
if y0_text < 0:
y0_text = 0
y1_text = y0 + 2 * draw_width + box_h
draw.rectangle(
[x0, y0_text, bbox[2] + draw_width * 2, y1_text],
fill=color,
)
draw.text(
(x0 + draw_width, y0_text),
label,
fill="black",
font=font,
)
def _draw_point(
draw: ImageDraw.ImageDraw,
coords: List[float],
color: Tuple[int, int, int],
draw_width: int,
label: str,
font: ImageFont.ImageFont,
show_labels: bool,
):
"""Draw point"""
x, y = [int(c) for c in coords]
# Draw point as circle
radius = min(8, draw_width)
border_width = 2
# Draw white border
draw.ellipse(
[
x - radius - border_width,
y - radius - border_width,
x + radius + border_width,
y + radius + border_width,
],
fill="white",
outline="white",
)
# Draw colored center
draw.ellipse(
[x - radius, y - radius, x + radius, y + radius],
fill=color,
outline=color,
)
# Draw label
if show_labels and label:
label_x, label_y = x + 5, y - 5
if label_y < 0:
label_y = y + 15
bbox = draw.textbbox((label_x, label_y), label, font)
box_h = bbox[3] - bbox[1]
box_w = bbox[2] - bbox[0]
padding = 4
"""
We choose not to draw background as the ground occludes key perceptual information in many cases.
"""
# Draw background
# draw.rectangle(
# [
# label_x - padding,
# label_y - box_h - padding,
# label_x + box_w + padding,
# label_y + padding,
# ],
# fill=color,
# )
# Draw text
draw.text((label_x, label_y - box_h), label, fill="red", font=font) |