Visualizing the output folder from Basic Writer()
Visualizing the output folder from Basic Writer() — Omniverse Extensions documentation
After generating data, it is always useful to visualize the outputs. In this tutorial, we give you a couple of helper functions to visualize the output of basic writer. Generating all data types available with Basic Writer() First generate data, you can us
docs.omniverse.nvidia.com
데이터를 생성한 후에는 항상 출력을 시각화하는 것이 유용합니다. 이 튜토리얼에서는 기본 작성기의 출력을 시각화할 수 있는 몇 가지 도우미 기능을 제공합니다.
Basic Writer()에서 사용할 수 있는 모든 데이터 유형을 생성
먼저 데이터를 생성하면 Basic_writer를 사용하는 복제자로 작성한 스크립트를 사용할 수 있습니다. 가장 간단한 예를 보려면, 레플리케이터의 "Hello World" 핵심 기능의 단계를 수행하십시오. Basic_writer에서 사용할 수 있는 데이터 유형을 쓰려면 Initialize Writer를 True로 바꿉니다.
writer.initialize(
output_dir="out_dir_test_visualization",
rgb=True,
bounding_box_2d_tight=True,
bounding_box_2d_loose=True,
semantic_segmentation=True,
instance_segmentation=True,
distance_to_camera=True,
distance_to_image_plane=True,
bounding_box_3d=True,
occlusion=True,
normals=True,
)
다음은 데이터를 생성할 준비가 된 수정된 레플리케이터의 "Hello World"의 스크립트입니다.
import omni.replicator.core as rep
with rep.new_layer():
camera = rep.create.camera(position=(0, 0, 1000))
render_product = rep.create.render_product(camera, (1024, 1024))
torus = rep.create.torus(semantics=[('class', 'torus')] , position=(0, -200 , 100))
sphere = rep.create.sphere(semantics=[('class', 'sphere')], position=(0, 100, 100))
cube = rep.create.cube(semantics=[('class', 'cube')], position=(100, -200 , 100) )
with rep.trigger.on_frame(num_frames=10):
with rep.create.group([torus, sphere, cube]):
rep.modify.pose(
position=rep.distribution.uniform((-100, -100, -100), (200, 200, 200)),
scale=rep.distribution.uniform(0.1, 2))
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir="out_dir_test_visualization",
rgb=True,
bounding_box_2d_tight=True,
bounding_box_2d_loose=True,
semantic_segmentation=True,
instance_segmentation=True,
distance_to_camera=True,
distance_to_image_plane=True,
bounding_box_3d=True,
occlusion=True,
normals=True,
)
writer.attach([render_product])
rep.orchestrator.run()
위의 출력 폴더를 수정하지 않은 경우 HOME/out_dir_test_visualization에 데이터 세트가 생성되었습니다. 레플라케이터의 모든 주석을 찾을 수 있습니다. 출력을 시각화하려면 몇 가지 도우미 기능이 필요합니다.
시각화 기능의 도움
아래 기능은 출력을 시각화하는 데 도움이 됩니다. 이러한 기능은 단순한 시각화 도우미입니다. 경계 상자의 경우 경계 상자에 색을 입히고 레이블을 지정하며, 분할의 경우 출력에 색을 입히고 의미 태그를 표시하며, 깊이의 경우 깊이를 나타내는 색상으로 깊이를 표시합니다.
import asyncio
from dis import dis
import os
import json
import hashlib
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
'''
Takes in the data from a specific label id and maps it to the proper color for the bounding box
'''
def data_to_colour(data):
if isinstance(data, str):
data = bytes(data, "utf-8")
else:
data = bytes(data)
m = hashlib.sha256()
m.update(data)
key = int(m.hexdigest()[:8], 16)
r = ((((key >> 0) & 0xFF) + 1) * 33) % 255
g = ((((key >> 8) & 0xFF) + 1) * 33) % 255
b = ((((key >> 16) & 0xFF) + 1) * 33) % 255
# illumination normalization to 128
inv_norm_i = 128 * (3.0 / (r + g + b))
return (int(r * inv_norm_i) / 255, int(g * inv_norm_i) / 255, int(b * inv_norm_i) / 255)
'''
Takes in the path to the rgb image for the background, then it takes bounding box data, the labels and the place to store the visualization. It outputs a colorized bounding box.
'''
def colorize_bbox_2d(rgb_path, data, id_to_labels, file_path):
rgb_img = Image.open(rgb_path)
colors = [data_to_colour(bbox["semanticId"]) for bbox in data]
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(rgb_img)
for bbox_2d, color, index in zip(data, colors, range(len(data))):
labels = id_to_labels[str(index)]
rect = patches.Rectangle(
xy=(bbox_2d["x_min"], bbox_2d["y_min"]),
width=bbox_2d["x_max"] - bbox_2d["x_min"],
height=bbox_2d["y_max"] - bbox_2d["y_min"],
edgecolor=color,
linewidth=2,
label=labels,
fill=False,
)
ax.add_patch(rect)
plt.legend(loc="upper left")
plt.savefig(file_path)
'''
Takes the depth data and colorizes it.
'''
def colorize_depth(depth_data):
near = 0.01
far = 100
depth_data = np.clip(depth_data, near, far)
# depth_data = depth_data / far
depth_data = (np.log(depth_data) - np.log(near)) / (np.log(far) - np.log(near))
# depth_data = depth_data / far
depth_data = 1.0 - depth_data
depth_data_uint8 = (depth_data * 255).astype(np.uint8)
return Image.fromarray(depth_data_uint8)
'''
Takes the segmentation images, the color for the labels and the output path to visualize the segmentation output
'''
def create_segmentation_legend(segmentation_img, color_to_labels, file_path):
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(segmentation_img)
color_patch_list = []
for color, labels in color_to_labels.items():
color_val = eval(color)
color_patch = patches.Patch(color=[i / 255 for i in color_val], label=labels)
color_patch_list.append(color_patch)
ax.legend(handles=color_patch_list)
plt.savefig(file_path)
출력 시각화
RGB 시각화
레플리케이터의 출력은 RGB와 함께 제공되므로 시각화하기 위해 별도의 작업을 수행할 필요가 없습니다. 그러나 나머지 샘플은 배경으로 사용할 것입니다. 불러오는 방법은 다음과 같습니다.
out_dir = PATH_TO_REPLICATOR_OUTPUT_DIR
rgb = "rgb_0.png" # to be changed by you
rgb_path = os.path.join(out_dir, rgb_file_name)
rgb_image = Image.open(rgb_path)
Normal 시각화
Normal은 RGB와 매우 유사합니다. PNG는 normals_n.png로 이미 저장되어 있습니다.
normals_file_name = "normals_0.png"
normals_image = Image.open(os.path.join(out_dir, normals_file_name))
normals_image.save(os.path.join(vis_out_dir, "normals.png"))
바운딩 박스 2D가 tight하거나 loose
이 경우에는 bounding_box_2d_loose_N.npy를 사용합니다. 이 숫자형 배열을 로드한 다음 bounding_box_2d_loose_labels_N.json에서 레이블을 가져옵니다. tight 경계 상자의 경우 이름을 bounding_box_2d_tight_labels_N.json 및 bounding_box_2d_tight_labels_N.py로 변경합니다. 그렇지 않으면 코드가 동일합니다.
bbox2d_loose_file_name = "bounding_box_2d_loose_0.npy"
data = np.load(os.path.join(out_dir, bbox2d_loose_file_name))
# Check for labels
bbox2d_loose_labels_file_name = "bounding_box_2d_loose_labels_0.json"
with open(os.path.join(out_dir, bbox2d_loose_labels_file_name), "r") as json_data:
bbox2d_loose_id_to_labels = json.load(json_data)
# colorize and save image
colorize_bbox_2d(rgb_path, data, bbox2d_loose_id_to_labels, os.path.join(vis_out_dir, "bbox2d_loose.png"))
카메라 또는 이미지 평면까지의 거리
여기서는 각각 카메라 또는 영상 평면 거리를 원하는지 여부에 따라 numpy 배열인 distance_to_camera_N.npy 또는 distance_to_image_plane_N.py가 필요합니다. 그런 다음 도우미 함수 colorize_depth를 사용합니다.
distance_to_camera_file_name = "distance_to_camera_0.npy"
distance_to_camera_data = np.load(os.path.join(out_dir, distance_to_camera_file_name))
distance_to_camera_file_name = np.nan_to_num(distance_to_camera_data, posinf=0)
distance_to_camera_image = colorize_depth(distance_to_camera_data)
distance_to_camera_image.save(os.path.join(vis_out_dir, "distance_to_camera.png"))
인스턴스 또는 semantic Segmentation
여기서 instance_segmentation_N.png 및 instance_segmentation_mapping_N.json을 전달합니다. png는 우리에게 각 픽셀의 라벨을 주고, json 파일은 그것을 매핑합니다. semantic Segmentation의 경우 파일 이름을 인스턴스 대신 semantic으로 바꿉니다.
instance_seg_file_name = "instance_segmentation_0.png"
instance_seg_img = Image.open(os.path.join(out_dir, instance_seg_file_name))
# Check labels
instance_seg_labels_file_name = "instance_segmentation_mapping_0.json"
with open(os.path.join(out_dir, instance_seg_labels_file_name), "r") as json_data:
instance_seg_color_to_labels = json.load(json_data)
create_segmentation_legend(
instance_seg_img, instance_seg_color_to_labels, os.path.join(vis_out_dir, "instance_seg.png"))
'omniverse > replicator' 카테고리의 다른 글
옴니버스 레플리케이터 예제 9탄 (0) | 2022.05.30 |
---|---|
옴니버스 레플리케이터 예제 8탄 (0) | 2022.05.29 |
옴니버스 레플리케이터 예제 6탄 (0) | 2022.05.27 |
옴니버스 레플리케이터 예제 5탄 (0) | 2022.05.26 |
옴니버스 레플리케이터 예제 4탄 (0) | 2022.05.25 |