utils
最后更新
luxonis_train.attached_modules.visualizers.utils可视化工具的辅助函数。这些辅助函数在张量和图像之间进行转换,对输入图像进行反归一化,选择颜色和字体大小,绘制标签,并将标签图像和预测图像组合成一个图像。Color 是一种颜色的类型:颜色名称或十六进制字符串,例如 "#FF0000",或 RGB 元组。函数
combine_visualizations
Python
1def combine_visualizations(visualization: Tensor | tuple[Tensor, Tensor] | tuple[Tensor, list[Tensor]]) -> Tensor:- 单个张量:函数返回它不变。
- 一对
(labels, predictions)张量,以元组或列表形式:函数将两个批次的大小调整为较大的高度。每个批次保持其纵横比。然后函数将批次并排放置,标签在左侧。 - 一个张量和一个张量列表或元组:函数引发
NotImplementedError。
示例
Pycon
1>>> import torch
2>>> labels = torch.zeros(1, 3, 4, 4, dtype=torch.uint8)
3>>> predictions = torch.zeros(1, 3, 8, 6, dtype=torch.uint8)
4>>> combine_visualizations((labels, predictions)).shape
5torch.Size([1, 3, 8, 14])
6>>> combine_visualizations(labels) is labels
7Truevisualization(Tensor | tuple[Tensor, Tensor] | tuple[Tensor, list[Tensor]]):可视化工具的输出。图像的形状为[B, C, H, W],一对中的两个批次具有相同的B和C。
Tensor:形状为[B, C, H, W]的图像。对于一对,H是较大的高度,W是调整大小后的宽度之和。
NotImplementedError:当第二个项目是张量列表或元组时。ValueError:当visualization具有任何其他形式时。
denormalize
Python
1def denormalize(img: Tensor, mean: list[float] | float | None = None, std: list[float] | float | None = None, to_uint8: bool = False) -> Tensor:mean,σ 是 std。使用 to_uint8,它将结果乘以 255,将其裁剪到 [0, 255],并将其截断为 uint8。示例
Pycon
1>>> import torch
2>>> img = torch.tensor([[[0.0]], [[1.0]], [[-1.0]]])
3>>> denormalize(img, mean=0.5, std=0.25).flatten().tolist()
4[0.5, 0.75, 0.25]
5>>> image = denormalize(img, mean=0.5, std=0.25, to_uint8=True)
6>>> image.flatten().tolist()
7[127, 191, 63]img(Tensor):形状为[C, H, W]的归一化图像。mean(list[float] | float | None):归一化的均值,每个通道一个值或所有通道一个float。None选择0。std(list[float] | float | None):归一化的标准差,与mean形式相同。None选择1。to_uint8(bool):是否将结果缩放到uint8图像。
Tensor:形状为[C, H, W]的新图像,如果to_uint8为uint8类型。
draw_bounding_box_labels
Python
1def draw_bounding_box_labels(img: Tensor, label: Tensor, **kwargs) -> Tensor:xywh(其中 x 和 y 是左上角)转换为具有图像大小的像素 xyxy。然后它调用 torchvision.utils.draw_bounding_boxes。它不改变 label。示例
宽度为
8、高度为 4 的图像上的框 [0.25, 0.25, 0.5, 0.5] 变为像素框 [2, 1, 6, 3]:Pycon
1>>> import torch
2>>> img = torch.zeros(3, 4, 8, dtype=torch.uint8)
3>>> label = torch.tensor([[0.25, 0.25, 0.5, 0.5]])
4>>> draw_bounding_box_labels(img, label, colors="red")[0].tolist()
5[[0, 0, 0, 0, 0, 0, 0, 0],
6 [0, 0, 255, 255, 255, 255, 255, 0],
7 [0, 0, 255, 0, 0, 0, 255, 0],
8 [0, 0, 255, 255, 255, 255, 255, 0]]img(Tensor):形状为[C, H, W]的uint8图像。label(Tensor):形状为[N, 4]的框,行格式为[x, y, w, h],归一化到[0, 1]。**kwargs:转发给draw_bounding_boxes的关键字参数,例如labels、colors和width。
Tensor:与img形状相同的新图像,并绘制了框。
draw_keypoint_labels
Python
1def draw_keypoint_labels(img: Tensor, label: Tensor, **kwargs) -> Tensor:x 和 y 值按图像宽度和高度缩放,将其截断为整数,并调用 torchvision.utils.draw_keypoints。它绘制每个关键点并忽略可见性。副作用: 当 label 是连续的时,函数会就地缩放 label 的 x 和 y 值到像素坐标。示例
关键点落在第
1 行第 2 列的像素上。调用还会将 label 更改为像素坐标:Pycon
1>>> import torch
2>>> img = torch.zeros(3, 4, 4, dtype=torch.uint8)
3>>> label = torch.tensor([[0.5, 0.25, 2.0]])
4>>> out = draw_keypoint_labels(img, label, colors="red", radius=1)
5>>> out[0, 1, 2].item(), label.tolist()
6(255, [[2.0, 1.0, 2.0]])img(Tensor):形状为[C, H, W]的uint8图像。label(Tensor):形状为[N, 3K]的关键点,行格式为[x_1, y_1, v_1, ..., x_K, y_K, v_K]。坐标归一化到[0, 1]。**kwargs:转发给draw_keypoints的关键字参数,例如colors、radius和connectivity。
Tensor:与img形状相同的新图像,并绘制了关键点。如果label不包含关键点,则返回img本身。
draw_segmentation_targets
Python
1def draw_segmentation_targets(image: Tensor, target: Tensor, alpha: float = 0.4, colors: Color | list[Color] | None = None) -> Tensor:torchvision.utils.draw_segmentation_masks。在混合之前,多个掩码中的像素会变为黑色。示例
Pycon
1>>> import torch
2>>> image = torch.zeros(3, 1, 3, dtype=torch.uint8)
3>>> masks = torch.tensor([[[1, 1, 0]], [[0, 1, 1]]])
4>>> out = draw_segmentation_targets(
5... image, masks, alpha=1.0, colors=["red", "blue"]
6... )
7>>> out[0].tolist(), out[2].tolist()
8([[255, 0, 0]], [[0, 0, 255]])image(Tensor):形状为[3, H, W]的 RGB 图像,uint8类型,或[0, 1]范围内的浮点类型。target(Tensor):形状为[N, H, W]的掩码,或形状为[H, W]的单个掩码。每个非零值标记掩码的一个像素。alpha(float):掩码的不透明度,从0(透明)到1(不透明)。colors(Color | list[Color] | None):每个掩码一种颜色,或所有掩码一种颜色。当为None时,torchvision选择颜色。
Tensor:CPU 上的新图像,与image形状和类型相同。当target不包含掩码时,torchvision会发出警告,函数返回未更改的图像。
dynamically_determine_font_scale
Python
1def dynamically_determine_font_scale(height: int, width: int, thickness: int, font_scale: float | None = None, scale_factor: float = 500.0) -> tuple[float, int]:font_scale,函数会根据高度 H 和宽度 W 的加权平均值推导出比例:w = min⎛⎝0.4, (W)/(10max(H, 1))⎞⎠, s = ((1 − w)H + w**W)/(scale_factor)比例低于 1 时,粗细为 1。比例为 1 或更高时,保持 thickness。示例
Pycon
1>>> dynamically_determine_font_scale(500, 500, thickness=2)
2(1.0, 2)
3>>> dynamically_determine_font_scale(100, 200, thickness=2)
4(0.24, 1)height(int):图像高度,以像素为单位。width(int):图像宽度,以像素为单位。thickness(int):比例为1或更高时的线条粗细。font_scale(float | None):固定的字体比例。None选择计算出的比例。scale_factor(float):产生比例1的有效图像大小,以像素为单位。
tuple[float, int]:字体比例和线条粗细。
figure_to_torch
Python
1def figure_to_torch(fig: Figure, width: int, height: int) -> Tensor:width 和 height。然后它使用 plt.close 关闭图形。示例
Pycon
1>>> import matplotlib.pyplot as plt
2>>> fig, ax = plt.subplots()
3>>> _ = ax.plot([0, 1], [0, 1])
4>>> figure_to_torch(fig, width=64, height=32).shape
5torch.Size([3, 32, 64])fig(Figure):要渲染的 matplotlib 图形。width(int):图像宽度,以像素为单位。height(int):图像高度,以像素为单位。
Tensor:形状为[3, height, width]的uint8图像。
get_color
Python
1def get_color(seed: int) -> Color:seed 总是给出相同的颜色。函数将 45 添加到 seed,并使用 number_to_hsl 和 hsl_to_rgb 转换结果。可视化工具将类索引作为 seed 传递。示例
Pycon
1>>> get_color(0)
2(25, 76, 229)seed(int):选择颜色的整数。
Color:红色、绿色和蓝色值,范围为[0, 255]。
get_denormalized_images
Python
1def get_denormalized_images(cfg: Config, images: Tensor) -> Tensor:uint8 图像。当 trainer.preprocessing.normalize 处于活动状态时,函数从其 params 读取 mean 和 std,并且 preprocess_images 撤销归一化。缺失的键选择 ImageNet 值,mean 为 [0.485, 0.456, 0.406],std 为 [0.229, 0.224, 0.225]。当归一化不处于活动状态时,函数只将图像转换为 uint8。LuxonisLightningModule 和推理实用程序将结果用作可视化工具的画布。GradCamCallback 在其上绘制热图。参数cfg(Config):模型的配置。images(Tensor):形状为[B, C, H, W]的输入图像,如加载器返回的那样。
Tensor:形状为[B, C, H, W]的新uint8张量。
get_prediction_labels
Python
1def get_prediction_labels(prediction: Tensor, label_dict: Mapping[int, str] | None, draw_labels: bool, draw_scores: bool) -> list[str] | None:draw_labels 时,标签包含类名;当设置 draw_scores 时,标签包含置信度,保留两位小数。两者之间用空格分隔。示例
Pycon
1>>> import torch
2>>> prediction = torch.tensor(
3... [
4... [0.0, 0.0, 4.0, 4.0, 0.75, 1.0],
5... [1.0, 1.0, 2.0, 2.0, 0.5, 7.0],
6... ]
7... )
8>>> get_prediction_labels(prediction, {'1': "cat"}, True, True)
9['cat 0.75', '7 0.50']
10>>> get_prediction_labels(prediction, None, False, True)
11['0.75', '0.50']prediction(Tensor):形状为[M, 6]的框,行格式为[x1, y1, x2, y2, conf, class]。label_dict(Mapping[int, str] | None):按类索引分类的类名。没有名称的类,或当为None时所有类,都将其索引作为名称。draw_labels(bool):标签是否包含类名。draw_scores(bool):标签是否包含置信度。
list[str] | None:每个框一个标签,或者当draw_labels和draw_scores都为False时为None。
hsl_to_rgb
Python
1def hsl_to_rgb(hsl: tuple[float, float, float]) -> Color:示例
Pycon
1>>> hsl_to_rgb((0, 1.0, 0.5))
2(255, 0, 0)hsl(tuple[float, float, float]):色相(以度为单位,范围为[0, 360)),饱和度和亮度(范围为[0, 1])。
Color:红色、绿色和蓝色值,范围为[0, 255]。
number_to_hsl
Python
1def number_to_hsl(seed: int) -> tuple[float, float, float]:(seed * 157) % 360。素数因子将连续种子的色相分布在色轮上。饱和度为 0.8,亮度为 0.5。示例
Pycon
1>>> number_to_hsl(3)
2(111, 0.8, 0.5)seed(int):要映射的整数。
tuple[float, float, float]:色相(以度为单位,范围为[0, 360)),饱和度和亮度。
numpy_to_torch_img
Python
1def numpy_to_torch_img(img: np.ndarray) -> Tensor:img 共享内存并保持其 dtype。示例
Pycon
1>>> import numpy as np
2>>> numpy_to_torch_img(np.zeros((4, 6, 3), dtype=np.uint8)).shape
3torch.Size([3, 4, 6])img(np.ndarray):形状为[H, W, C]的图像。
Tensor:形状为[C, H, W]的视图。
potentially_upscale_masks
Python
1def potentially_upscale_masks(image_masks: Tensor, scale: float = 1.0) -> Tensor:int(H * scale) 和 int(W * scale),因此小于 1 的因子会缩小掩码。当因子为 1 时,函数返回未更改的 image_masks。示例
Pycon
1>>> import torch
2>>> masks = torch.tensor([[[True, False], [False, True]]])
3>>> potentially_upscale_masks(masks, scale=2.0).int().tolist()
4[[[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]]]image_masks(Tensor):形状为[N, H, W]的掩码。每个非零值标记掩码的一个像素。scale(float):调整大小的因子。
Tensor:形状为[N, int(H * scale), int(W * scale)]的布尔掩码,或者当scale为1时为image_masks本身。
preprocess_images
Python
1def preprocess_images(imgs: Tensor, mean: list[float] | float | None = None, std: list[float] | float | None = None) -> Tensor:uint8 图像。当给定 mean 或 std 时,denormalize 恢复每个图像并将其缩放到 [0, 255]。否则,函数只将图像转换为 uint8,因此它们必须已经具有 [0, 255] 范围内的值。示例
Pycon
1>>> import torch
2>>> imgs = torch.zeros(2, 3, 4, 4)
3>>> out = preprocess_images(imgs, mean=[0.5, 0.5, 0.5], std=0.5)
4>>> out.dtype, out[0, :, 0, 0].tolist()
5(torch.uint8, [127, 127, 127])imgs(Tensor):形状为[B, C, H, W]的图像。mean(list[float] | float | None):归一化的均值,每个通道一个值或所有通道一个值。std(list[float] | float | None):归一化的标准差,与mean形式相同。
Tensor:形状为[B, C, H, W]的新uint8张量。
torch_img_to_numpy
Python
1def torch_img_to_numpy(img: Tensor, reverse_colors: bool = False) -> npt.NDArray[np.uint8]:uint8 NumPy 图像。函数将浮点图像乘以 255 并将其截断为整数。它将所有值裁剪到 [0, 255]。示例
Pycon
1>>> import torch
2>>> img = torch.tensor([[[0.5]], [[1.0]], [[2.0]]])
3>>> torch_img_to_numpy(img).tolist()
4[[[127, 255, 255]]]
5>>> torch_img_to_numpy(img, reverse_colors=True).tolist()
6[[[255, 255, 127]]]img(Tensor):形状为[C, H, W]的图像。浮点图像的值范围为[0, 1]。reverse_colors(bool):是否交换第一个和第三个通道,例如从 RGB 到 BGR。图像必须有三个通道。
npt.NDArray[np.uint8]:形状为[H, W, C]的新连续图像。