|
|
"""
|
|
|
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
|
|
|
"""
|
|
|
|
|
|
|
|
|
vis_image = image.copy()
|
|
|
draw = ImageDraw.Draw(vis_image)
|
|
|
|
|
|
|
|
|
font = _load_font(font_size, font_path)
|
|
|
|
|
|
|
|
|
color_generator = ColorGenerator("same")
|
|
|
color_generator.color = (255, 0, 0)
|
|
|
|
|
|
for i, entity in enumerate(annotations):
|
|
|
|
|
|
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]
|
|
|
|
|
|
|
|
|
if x0 >= x1 or y0 >= y1:
|
|
|
return
|
|
|
|
|
|
|
|
|
draw.rectangle([x0, y0, x1, y1], outline=color, width=draw_width)
|
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
|
|
|
|
radius = min(8, draw_width)
|
|
|
border_width = 2
|
|
|
|
|
|
|
|
|
draw.ellipse(
|
|
|
[
|
|
|
x - radius - border_width,
|
|
|
y - radius - border_width,
|
|
|
x + radius + border_width,
|
|
|
y + radius + border_width,
|
|
|
],
|
|
|
fill="white",
|
|
|
outline="white",
|
|
|
)
|
|
|
|
|
|
|
|
|
draw.ellipse(
|
|
|
[x - radius, y - radius, x + radius, y + radius],
|
|
|
fill=color,
|
|
|
outline=color,
|
|
|
)
|
|
|
|
|
|
|
|
|
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.text((label_x, label_y - box_h), label, fill="red", font=font) |