| import math |
| import matplotlib |
| from shapely.geometry import Polygon |
| import cv2 |
| import datetime |
| import matplotlib.pyplot as plt |
| import numpy as np |
| import os |
| import random |
| from PIL import Image, ImageFile |
| ImageFile.LOAD_TRUNCATED_IMAGES = True |
| from PIL import ImageDraw, ImageFont |
| from io import BytesIO |
|
|
|
|
| def annotate_image_with_coordinates(image_path, visual_marks, output_path, format="coordinate", default_font_size=18): |
| script_path = os.path.dirname(os.path.realpath(__file__)) |
| |
| img = Image.open(image_path) |
| img_width, img_height = img.size |
| draw = ImageDraw.Draw(img) |
|
|
| wall_font_size = 18 * img_width / 1000 |
| wall_font = ImageFont.truetype(os.path.join(script_path, "Arial.ttf"), wall_font_size) |
|
|
| to_draw_list = [] |
| if format == "coordinate": |
| assert type(visual_marks) == dict |
| for (x, y), (pixel_x, pixel_y) in visual_marks.items(): |
| to_draw_list.append({"pixel": (pixel_x, pixel_y), "text": f"({x},{y})"}) |
|
|
| |
| |
| default_font_size = 18 * img_width / 1000 |
| font = ImageFont.truetype(os.path.join(script_path, "Arial.ttf"), default_font_size) |
|
|
| elif format == "text": |
| assert type(visual_marks) == list |
| for visual_mark in visual_marks: |
| assert type(visual_mark) == dict |
| assert "pixel" in visual_mark and "text" in visual_mark |
| to_draw_list = visual_marks |
|
|
| default_font_size = default_font_size * img_width / 1000 |
| font = ImageFont.truetype(os.path.join(script_path, "Arial.ttf"), default_font_size) |
|
|
| else: |
| raise ValueError("Invalid format. Choose 'coordinate' or 'text'.") |
|
|
| |
| for to_draw_dict in to_draw_list: |
|
|
| pixel_x, pixel_y = to_draw_dict["pixel"] |
| text = to_draw_dict["text"] |
|
|
| pixel_x = pixel_x * img_width |
| pixel_y = pixel_y * img_height |
|
|
| |
| if "end_arrow_pixel" in to_draw_dict: |
| end_pixel_x, end_pixel_y = to_draw_dict["end_arrow_pixel"] |
| end_pixel_x = end_pixel_x * img_width |
| end_pixel_y = end_pixel_y * img_height |
| |
| arrow_length = ((end_pixel_x - pixel_x)**2 + (end_pixel_y - pixel_y)**2)**0.5 |
| angle = math.atan2(end_pixel_y - pixel_y, end_pixel_x - pixel_x) |
| |
| draw.line([pixel_x, pixel_y, end_pixel_x, end_pixel_y], fill="black", width=5) |
| |
| arrow_head_length = min(15, arrow_length / 3) |
| arrow_head_width = arrow_head_length |
| x1 = end_pixel_x - arrow_head_length * math.cos(angle) + arrow_head_width * math.sin(angle) |
| y1 = end_pixel_y - arrow_head_length * math.sin(angle) - arrow_head_width * math.cos(angle) |
| x2 = end_pixel_x - arrow_head_length * math.cos(angle) - arrow_head_width * math.sin(angle) |
| y2 = end_pixel_y - arrow_head_length * math.sin(angle) + arrow_head_width * math.cos(angle) |
| draw.polygon([end_pixel_x, end_pixel_y, x1, y1, x2, y2], fill="black") |
|
|
| |
| dot_radius = 3 |
| draw.ellipse([pixel_x - dot_radius, pixel_y - dot_radius, |
| pixel_x + dot_radius, pixel_y + dot_radius], |
| fill="red", outline="red") |
| |
| text_bbox = draw.textbbox((pixel_x, pixel_y), text, font=font) |
| text_w = text_bbox[2] - text_bbox[0] |
| text_h = text_bbox[3] - text_bbox[1] |
|
|
| |
| if text.startswith("("): |
| draw.text((pixel_x - text_w/2, pixel_y + dot_radius - 2), text, font=font, fill="red") |
| else: |
| |
| |
| |
| |
| |
| font_color = "black" |
| if "end_arrow_pixel" in to_draw_dict: |
| if end_pixel_y >= pixel_y: |
| if default_font_size > 80: |
| |
| draw.text((pixel_x - text_w/2, pixel_y + dot_radius - 2 - text_h*1.3), text, font=font, fill=font_color) |
| else: |
| draw.text((pixel_x - text_w/2, pixel_y + dot_radius - 2 - text_h*1.1), text, font=font, fill=font_color) |
| else: |
| draw.text((pixel_x - text_w/2, pixel_y + dot_radius - 2), text, font=font, fill=font_color) |
| else: |
| draw.text((pixel_x - text_w/2, pixel_y + dot_radius - 2), text, font=font, fill=font_color) |
| |
| img.save(output_path) |
| print(f"Annotated image saved to {output_path}") |
|
|
|
|
| def load_image(image_path): |
| |
| image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) |
| if image is None: |
| raise ValueError("Image not loaded correctly.") |
| return image |
| |
| |
| |
|
|
|
|
| def overlay_bounding_box(image_path, output_path, visual_mark_path="./data/visual_mark_num.png"): |
| image1 = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) |
| image2 = cv2.imread(visual_mark_path, cv2.IMREAD_UNCHANGED) |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| mask1 = image1[..., -1] / 255.0 |
| mask2 = image2[..., -1] / 255.0 |
| |
| |
| image1[mask1 > 0, -1] = image1[mask1 > 0, -1] * 0.5 |
| for c in range(0, 3): image1[..., c] = (1-mask2) * image1[..., c] + mask2 * image2[..., c] |
| |
| |
| has_content = (mask1 + mask2) > 0 |
| image1[..., -1] = has_content * 255 + (1 - has_content) * 0 |
| cv2.imwrite(output_path, image1) |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| def overlay_text(image_paths, texts=None, output_path=None, text_color=(255, 255, 255)): |
| if texts is not None: |
| if len(image_paths) != len(texts): |
| texts = None |
| |
| images = [Image.open(image_path) for image_path in image_paths] |
| img_width, img_height = images[0].size |
| positions = [(0, 0), (img_width, 0), (0, img_height), (img_width, img_height)] |
|
|
| if len(image_paths) == 4: |
| grid_image = Image.new('RGB', (img_width * 2, img_height * 2), (255, 255, 255)) |
| else: |
| grid_image = Image.new('RGB', (img_width * 2, img_height), (255, 255, 255)) |
| |
| for index, image in enumerate(images): |
| |
| if image.mode == 'RGBA': |
| white_bg = Image.new('RGBA', image.size, (255, 255, 255, 255)) |
| white_bg.paste(image, (0, 0), image) |
| image = white_bg.convert('RGB') |
| |
| |
| x = (index % 2) * img_width |
| y = (index // 2) * img_height |
| if texts is not None: |
| |
| |
| |
| draw = ImageDraw.Draw(image) |
| |
| position = (10, 10) |
| |
| text_color = (0,0,0) |
| |
| font = ImageFont.truetype("utils/Arial.ttf", 50) |
| |
| |
| draw.text(position, texts[index], fill=text_color, font=font) |
| |
| grid_image.paste(image, (x, y)) |
|
|
| |
| draw = ImageDraw.Draw(grid_image) |
| line_width = 3 |
| for i in range(1, 2): |
| |
| draw.line((img_width * i + line_width * i, 0, img_width * i + line_width * i, grid_image.height), fill='black', width=line_width) |
| |
| draw.line((0, img_height * i + line_width * i, grid_image.width, img_height * i + line_width * i), fill='black', width=line_width) |
|
|
| grid_image.save(output_path) |
| return output_path |
|
|
|
|
| def visualize_grid(room_poly, assets: dict, output_path: str, grid_points=None, randomize_color=False, output_size=(1200,1200), dpi=300): |
| |
| room_poly = Polygon(room_poly) |
| |
| plt.rcParams["font.size"] = 12 |
| |
| color_palette = [ |
| 'red', 'blue', 'green', 'purple', 'orange', 'brown', 'pink', 'gray', 'olive', 'cyan' |
| ] |
|
|
| |
| fig_size = (output_size[0] / dpi, output_size[1] / dpi) |
| |
| fig, ax = plt.subplots(figsize=fig_size, dpi=dpi) |
| fig.set_dpi(dpi) |
|
|
| |
| x, y = room_poly.exterior.xy |
| ax.plot(x, y, '-', label='Room', color='black', linewidth=2) |
|
|
| |
| idx = 0 |
| for instance_id, asset in assets.items(): |
| if instance_id.startswith('walls'): |
| continue |
| center_x, center_y, center_z = asset.position.cpu().detach().numpy() |
| |
| rotation = asset.get_theta() |
| rotated_corners = asset.get_2dpolygon().cpu().detach().numpy() |
|
|
| |
| if randomize_color: |
| color = (random.random(), random.random(), random.random()) |
| else: |
| color = color_palette[idx % len(color_palette)] |
|
|
| |
| obj_poly = Polygon(rotated_corners) |
| x, y = obj_poly.exterior.xy |
| ax.plot(x, y, '-', linewidth=2, color=color, clip_on=False) |
| ax.text(rotated_corners[0][0]-0.3, rotated_corners[0][1]-0.3, asset.id, fontsize=8, ha='center', color=color, clip_on=False) |
|
|
| |
|
|
| |
| |
| |
| |
| ax.arrow(center_x, center_y, np.cos(rotation)/2, np.sin(rotation)/2, head_width=0.1, fc=color, clip_on=False, color=color) |
| idx += 1 |
|
|
| |
| min_x, min_y, max_x, max_y = room_poly.bounds |
| ax.set_xlim(min_x, max_x) |
| ax.set_ylim(min_y, max_y) |
| |
| |
| ax.spines['top'].set_visible(False) |
| ax.spines['right'].set_visible(False) |
| ax.spines['bottom'].set_visible(False) |
| ax.spines['left'].set_visible(False) |
| ax.set_aspect('equal', 'box') |
| |
| plt.tight_layout(pad=0) |
| plt.savefig(output_path, pad_inches=0.1, dpi=dpi) |
| plt.close(fig) |
|
|
|
|
| if __name__ == "__main__": |
| |
| |
| |
| |
| |
| |
| vertices = [ |
| [-1, -1, -1.6], |
| [-1, 5, -1.6], |
| [5, 5, -1.6], |
| [5, -1, -1.6], |
| ] |
| assets = [ |
| Asset( |
| id=1, |
| category="chair", |
| bounding_box=[[1, 1, 1], [2, 2, 2]], |
| rotation=[0, 90, 0] |
| ), |
| Asset( |
| id=1, |
| category="chair", |
| bounding_box=[[0, 0, 0], [1, 1, 1]], |
| rotation=[0, 30, 0] |
| ), |
| Asset( |
| id=2, |
| category="table", |
| bounding_box=[[1, 1, 0.8], [2, 3, 1]], |
| rotation=[0, 145, 0] |
| ), |
| ] |
| create_time = str(datetime.datetime.now()).replace(" ", "-").replace(":", "-").replace(".", "-") |
| |
| output_path = f"tmp/test.pdf" |
| os.makedirs("tmp", exist_ok=True) |
| visualize_grid(vertices, assets, output_path) |
|
|
| |
| image_path = "/Users/sunfanyun/Downloads/3D_scene_generation/GenLayout/data/sceneVerse/preprocessed/ProcThor/0_shelf/render_{}.png" |
| image_paths = [image_path.format(degree) for degree in [0, 90, 180, 270]] |
| texts = [f"{degree}°" for degree in [0, 90, 180, 270]] |
| output_path = "tmp.png" |
| overlay_text(image_paths, texts, output_path) |
|
|
|
|