detectron2.utils

detectron2.utils.colormap 模块

一个出色的色彩映射方案,用于实现非常清晰的可视化效果。 从Detectron复制而来,并移除了灰色系颜色。

detectron2.utils.colormap.colormap(rgb=False, maximum=255)[源代码]
Parameters
  • rgb (bool) - 是否返回RGB颜色或BGR颜色。

  • maximum (int) – 取值可以是255或1

Returns

ndarray – 一个Nx3颜色的float32数组,取值范围为[0, 255]或[0, 1]

detectron2.utils.colormap.random_color(rgb=False, maximum=255)[源代码]
Parameters
  • rgb (bool) - 是否返回RGB颜色或BGR颜色。

  • maximum (int) - 可以是255或1

Returns

ndarray – 一个包含3个数字的向量

detectron2.utils.colormap.random_colors(N, rgb=False, maximum=255)[源代码]
Parameters
  • N (int) – 所需唯一颜色的数量

  • rgb (bool) - 是否返回RGB颜色或BGR颜色。

  • maximum (int) - 可以是255或1

Returns

ndarray – 随机颜色列表

detectron2.utils.comm 模块

该文件包含多GPU通信的底层原语。这在执行分布式训练时非常有用。

detectron2.utils.comm.get_world_size()int[源代码]
detectron2.utils.comm.get_rank()int[源代码]
detectron2.utils.comm.create_local_process_group(num_workers_per_machine: int)None[源代码]

创建一个包含同一台机器内所有等级的进程组。

Detectron2的engine/launch.py中的launch()会调用此函数。如果您不使用launch()启动工作进程,您也需要调用此函数。否则像get_local_rank()这样的实用功能将无法工作。

此函数包含一个屏障。所有进程必须同时调用它。

Parameters

num_workers_per_machine – 每台机器上的工作进程数量。通常对应GPU的数量。

detectron2.utils.comm.get_local_process_group()[源代码]
Returns

一个仅包含与当前进程位于同一台机器上的进程的torch进程组。该组可用于机器内部的通信,例如每台机器的SyncBN。

detectron2.utils.comm.get_local_rank()int[源代码]
Returns

当前进程在本地(每台机器)进程组中的排名。

detectron2.utils.comm.get_local_size()int[源代码]
Returns

每台机器的进程组大小,即每台机器的进程数量。

detectron2.utils.comm.is_main_process()bool[源代码]
detectron2.utils.comm.synchronize()[源代码]

在使用分布式训练时,用于在所有进程之间同步(屏障)的辅助函数

detectron2.utils.comm.all_gather(data, group=None)[源代码]

对任意可pickle的数据(不一定是张量)执行all_gather操作。

Parameters
  • data – 任何可序列化的对象

  • group – 一个torch进程组。默认情况下,将使用一个包含gloo后端上所有进程的组。

Returns

list[data] – 从每个rank收集的数据列表

detectron2.utils.comm.gather(data, dst=0, group=None)[源代码]

对任意可pickle的数据(不一定是张量)执行gather操作。

Parameters
  • data – 任何可序列化的对象

  • dst (int) – 目标rank

  • group – 一个torch进程组。默认情况下,将使用一个包含gloo后端上所有进程的组。

Returns

list[data]

在目标节点上,是从每个rank收集的数据列表。否则,

一个空列表。

detectron2.utils.comm.shared_random_seed()[源代码]
Returns

int - 一个在所有工作进程中相同的随机数。 如果工作进程需要共享随机数生成器,它们可以使用这个共享种子来创建一个。

所有工作进程都必须调用此函数,否则会导致死锁。

detectron2.utils.comm.reduce_dict(input_dict, average=True)[源代码]

从所有进程中减少字典中的值,使得排名为0的进程拥有减少后的结果。

Parameters
  • input_dict (dict) - 需要缩减的输入。所有值必须是标量CUDA张量。

  • average (bool) - 是否进行平均或求和

Returns

一个字典,其键与input_dict相同,经过缩减处理后。

detectron2.utils.events 模块

detectron2.utils.logger 模块

detectron2.utils.logger.setup_logger(output=None, distributed_rank=0, *, color=True, name='detectron2', abbrev_name=None, enable_propagation: bool = False, configure_stdout: bool = True)[源代码]

初始化detectron2日志记录器并将其详细级别设置为“DEBUG”。

Parameters
  • output (str) – 用于保存日志的文件名或目录。如果为None,则不会保存日志文件。 如果以".txt"或".log"结尾,则假定为文件名。 否则,日志将被保存到output/log.txt

  • name (str) – 该日志记录器的根模块名称

  • abbrev_name (str) – 模块的缩写名称,用于避免日志中出现过长名称。 设置为""表示不在日志中记录根模块。 默认情况下,会将"detectron2"缩写为"d2",其他模块名称保持不变。

  • enable_propagation (bool) – 是否将日志传播到父记录器。

  • configure_stdout (bool) - 是否配置日志输出到标准输出。

Returns

logging.Logger – 一个日志记录器

detectron2.utils.logger.log_first_n(lvl, msg, n=1, *, name=None, key='caller')[源代码]

仅在前n次记录日志。

Parameters
  • lvl (int) – 日志级别

  • msg (str) –

  • n (int) –

  • name (str) – 要使用的日志记录器名称。默认将使用调用者的模块名。

  • key (strtuple[str]) – 该字符串(或字符串元组)可以是"caller"或"message"之一,用于定义如何识别重复日志。 例如,如果使用n=1, key="caller"调用,该函数将仅记录来自同一调用者的第一次调用,而不考虑消息内容。 如果使用n=1, key="message"调用,该函数将仅记录相同内容一次,即使它们来自不同位置。 如果使用n=1, key=("caller", "message")调用,该函数将仅在相同调用者之前已记录过相同消息时才会不记录。

detectron2.utils.logger.log_every_n(lvl, msg, n=1, *, name=None)[源代码]

每n次记录一次日志。

Parameters
  • lvl (int) – 日志记录级别

  • msg (str) –

  • n (int) –

  • name (str) – 要使用的日志记录器名称。默认将使用调用者的模块。

detectron2.utils.logger.log_every_n_seconds(lvl, msg, n=1, *, name=None)[源代码]

每n秒最多记录一次。

Parameters
  • lvl (int) – 日志记录级别

  • msg (str) –

  • n (int) –

  • name (str) – 要使用的日志记录器名称。默认使用调用者的模块。

detectron2.utils.registry 模块

class detectron2.utils.registry.Registry(*args, **kwds)[源代码]

基类: collections.abc.Iterable, typing.Generic

提供名称到对象映射的注册表,以支持第三方用户的自定义模块。

要创建一个注册表(例如骨干网络注册表):

BACKBONE_REGISTRY = Registry('BACKBONE')

注册一个对象:

@BACKBONE_REGISTRY.register()
class MyBackbone():
    ...

或者:

BACKBONE_REGISTRY.register(MyBackbone)
__init__(name: str)None[源代码]
Parameters

name (str) – 该注册表的名称

register(obj: Any = None) → Any[源代码]

将给定对象以名称obj.__name__进行注册。 可用作装饰器或非装饰器。使用方法请参阅本类的文档字符串。

get(name: str) → Any[源代码]
detectron2.utils.registry.locate(name: str) → Any[源代码]

通过输入字符串 {x.__module__}.{x.__qualname__}(例如"module.submodule.class_name")来定位并返回对象 x

如果找不到则抛出异常。

detectron2.utils.memory 模块

detectron2.utils.memory.retry_if_cuda_oom(func)[源代码]

Makes a function retry itself after encountering pytorch’s CUDA OOM error. It will first retry after calling torch.cuda.empty_cache().

如果仍然失败,它将尝试将输入转换为CPU后重试。 在这种情况下,它期望函数能调度到CPU实现。 返回值也可能变成CPU张量,用户需要根据需要将其转换回CUDA张量。

Parameters

func – 一个无状态的调用对象,以类张量对象作为参数

Returns

a callable which retries func if OOM is encountered.

示例:

output = retry_if_cuda_oom(some_torch_function)(input1, input2)
# output may be on CPU even if inputs are on GPU

注意

  1. 当将输入转换为CPU时,它只会检查每个参数是否具有.device.to属性以进行转换。不支持张量的嵌套结构。

  2. 由于该函数可能会被多次调用,它必须是无状态的。

detectron2.utils.analysis 模块

detectron2.utils.visualizer 模块

class detectron2.utils.visualizer.ColorMode(value)[源代码]

基类: enum.Enum

用于实例可视化的不同颜色模式的枚举。

IMAGE = 0

为每个实例随机选择一种颜色,并以低不透明度覆盖分割区域。

SEGMENTATION = 1

让同一类别的实例具有相似的颜色(来自metadata.thing_colors),并以高不透明度叠加显示。这样可以更关注分割的质量。

IMAGE_BW = 2

与IMAGE相同,但将所有无掩码区域转换为灰度。 仅适用于绘制每个实例的掩码预测。

class detectron2.utils.visualizer.VisImage(img, scale=1.0)[源代码]

基类: object

__init__(img, scale=1.0)[源代码]
Parameters
  • img (ndarray) – 一个形状为(H, W, 3)、数值范围在[0, 255]之间的RGB图像。

  • scale (float) - 缩放输入图像

reset_image(img)[源代码]
Parameters

img – 与__init__中的相同

save(filepath)[源代码]
Parameters

filepath (str) - 包含绝对路径的字符串,包括文件名,可视化图像将被保存的位置。

get_image()[源代码]
Returns

ndarray – 可视化后的图像,形状为(H, W, 3)(RGB),uint8类型。 该形状会根据给定的scale参数相对于输入图像进行缩放。

class detectron2.utils.visualizer.Visualizer(img_rgb, metadata=None, scale=1.0, instance_mode=<ColorMode.IMAGE: 0>)[源代码]

基类: object

可视化工具,用于在图像上绘制检测/分割相关的数据。

它包含诸如draw_{text,box,circle,line,binary_mask,polygon}等方法,用于在图像上绘制基本图形元素,以及高级封装器如draw_{instance_predictions,sem_seg,panoptic_seg_predictions,dataset_dict},用于按照预定义样式绘制复合数据。

请注意,高级封装器的具体可视化样式可能会发生变化。诸如颜色、透明度、标签内容、标签可见性,甚至对象本身的可见性(例如当对象过小时)等样式,可能会根据不同的启发式规则进行调整,只要最终结果在视觉上仍然合理即可。

为了保持一致的样式,您可以使用上述基本方法实现自定义绘图函数。如果需要更个性化的可视化样式,您可以按照教程中记录的格式自行处理数据(使用模型使用自定义数据集)。本类并不旨在满足每个人对绘图样式的偏好。

该可视化工具注重高质量的渲染效果而非性能表现,并非为实时应用场景设计。

__init__(img_rgb, metadata=None, scale=1.0, instance_mode=<ColorMode.IMAGE: 0>)[源代码]
Parameters
  • img_rgb – 一个形状为 (H, W, C) 的 numpy 数组,其中 H 和 W 分别对应图像的高度和宽度。C 是颜色通道的数量。图像需要采用 RGB 格式,这是 Matplotlib 库的要求。同时图像的数值范围应在 [0, 255] 之间。

  • metadata (Metadata) – 数据集元数据(例如类别名称和颜色)

  • instance_mode (ColorMode) - 定义在图像上绘制实例的预定义样式之一。

draw_instance_predictions(predictions)[源代码]

在图像上绘制实例级别的预测结果。

Parameters

predictions (Instances) - 实例检测/分割模型的输出结果。以下字段将用于绘制: "pred_boxes"、"pred_classes"、"scores"、"pred_masks"(或"pred_masks_rle")。

Returns

output (VisImage) – 带有可视化效果的图像对象。

draw_sem_seg(sem_seg, area_threshold=None, alpha=0.8)[源代码]

绘制语义分割预测/标签。

Parameters
  • sem_seg (Tensorndarray) - 形状为(H, W)的分割结果。 每个值代表像素的整数标签。

  • area_threshold (int) - 面积小于area_threshold的分段不会被绘制。

  • alpha (float) - 数值越大,分割结果越不透明。

Returns

output (VisImage) – 带有可视化效果的图像对象。

draw_panoptic_seg(panoptic_seg, segments_info, area_threshold=None, alpha=0.7)[源代码]

绘制全景预测标注或结果。

Parameters
  • panoptic_seg (Tensor) – 形状为(高度, 宽度)的张量,其中的值是每个分割区域的ID。

  • segments_info (list[dict] or None) - 描述panoptic_seg中的每个分割段。 如果是list[dict],每个字典包含"id"、"category_id"键。 如果为None,则每个像素的类别ID通过 pixel // metadata.label_divisor计算。

  • area_threshold (int) – 面积小于 area_threshold 的stuff区域不会被绘制。

Returns

output (VisImage) – 带有可视化效果的图像对象。

draw_dataset_dict(dic)[源代码]

以Detectron2数据集格式绘制标注/分割。

Parameters

dic (dict) – 一张图片的标注/分割数据,采用Detectron2数据集格式。

Returns

output (VisImage) – 带有可视化效果的图像对象。

overlay_instances(*, boxes=None, labels=None, masks=None, keypoints=None, assigned_colors=None, alpha=0.5)[源代码]
Parameters
  • boxes (Boxes, RotatedBoxesndarray) - 可以是 Boxes, 或是单张图片中N个物体的XYXY_ABS格式的Nx4 numpy数组, 或是 RotatedBoxes, 或是单张图片中N个物体的(x_center, y_center, width, height, angle_degrees)格式的Nx5 numpy数组

  • labels (list[str]) – 为每个实例显示的文本。

  • masks (类似掩码的对象) –

    支持的类型包括:

    • detectron2.structures.PolygonMasks, detectron2.structures.BitMasks.

    • list[list[ndarray]]: 包含单张图像中所有对象的分割掩码。 列表的第一层对应单个实例,第二层对应组成该实例的所有多边形, 第三层对应多边形的坐标。第三层应具有[x0, y0, x1, y1, ..., xn, yn] (n >= 3)的格式。

    • list[ndarray]: 每个ndarray是一个形状为(H, W)的二进制掩码。

    • list[dict]: 每个字典是一个COCO风格的RLE。

  • keypoints (Keypoint类数组) - 一个形状为 (N, K, 3) 的类数组对象, 其中 N 是实例数量,K 是关键点数量。 最后一个维度对应 (x, y, 可见性或分数)。

  • assigned_colors (list[matplotlib.colors]) – 一个颜色列表,其中每个颜色对应图像中的每个掩码或方框。有关支持的颜色格式的完整列表,请参考'matplotlib.colors'。

Returns

output (VisImage) – 带有可视化效果的图像对象。

overlay_rotated_instances(boxes=None, labels=None, assigned_colors=None)[源代码]
Parameters
  • boxes (ndarray) - 一个Nx5的numpy数组,表示单张图像中N个物体的(x_center, y_center, width, height, angle_degrees)格式。

  • labels (list[str]) – 为每个实例显示的文本。

  • assigned_colors (list[matplotlib.colors]) – 一个颜色列表,其中每个颜色对应图像中的每个掩码或方框。有关支持的颜色格式的完整列表,请参考'matplotlib.colors'。

Returns

output (VisImage) – 带有可视化效果的图像对象。

draw_and_connect_keypoints(keypoints)[源代码]

绘制实例的关键点,并按照关键点连接规则在适当的关键点之间绘制线条。线条颜色遵循颜色启发式规则。

Parameters

关键点 (张量) – 一个形状为 (K, 3) 的张量,其中 K 是关键点数量,最后一个维度对应 (x坐标, y坐标, 概率)。

Returns

output (VisImage) – 带有可视化效果的图像对象。

draw_text(text, position, *, font_size=None, color='g', horizontal_alignment='center', rotation=0)[源代码]
Parameters
  • text (str) - 类别标签

  • position (tuple) – 一个包含x和y坐标的元组,用于在图像上放置文本。

  • font_size (int, optional) – 文本字体大小。如果未提供,将根据图像宽度按比例计算并使用。

  • color – 文本颜色。完整支持的格式列表请参考matplotlib.colors

  • horizontal_alignment (str) – 参见 matplotlib.text.Text

  • rotation – 逆时针方向的旋转角度(单位:度)

Returns

output (VisImage) – 绘制了文本的图像对象。

draw_box(box_coord, alpha=0.5, edge_color='g', line_style='-')[源代码]
Parameters
  • box_coord (tuple) – 一个包含x0、y0、x1、y1坐标的元组,其中x0和y0是图像左上角的坐标。x1和y1是图像右下角的坐标。

  • alpha (float) - 混合效率。数值越小,遮罩越透明。

  • edge_color - 框线轮廓的颜色。有关所有可接受格式的完整列表,请参阅matplotlib.colors

  • line_style (string) - 用于创建框体轮廓的字符串。

Returns

output (VisImage) – 绘制了框的图像对象。

draw_rotated_box_with_label(rotated_box, alpha=0.5, edge_color='g', line_style='-', label=None)[源代码]

在左上角绘制一个带标签的旋转框。

Parameters
  • rotated_box (tuple) – 一个包含(cnt_x, cnt_y, w, h, angle)的元组, 其中cnt_x和cnt_y是框的中心坐标。 w和h是框的宽度和高度。angle表示该框相对于0度框逆时针旋转了多少度。

  • alpha (float) – 混合效率。数值越小,掩膜越透明。

  • edge_color – 框线轮廓的颜色。有关所有可接受格式的完整列表,请参阅matplotlib.colors

  • line_style (string) - 用于创建框体轮廓的字符串。

  • label (string) - 旋转框的标签。当设置为None时将不会渲染。

Returns

output (VisImage) – 绘制了边界框的图像对象。

draw_circle(circle_coord, color, radius=3)[源代码]
Parameters
  • circle_coord (list(int) or tuple(int)) – 包含圆心x和y坐标的列表或元组。

  • color – 多边形的颜色。有关所有可接受的格式,请参阅matplotlib.colors

  • radius (int) – 圆的半径。

Returns

output (VisImage) – 绘制了框的图像对象。

draw_line(x_data, y_data, color, linestyle='-', linewidth=None)[源代码]
Parameters
  • x_data (list[int]) – 包含所有绘制点x值的列表。列表长度应与y_data的长度匹配。

  • y_data (list[int]) – 包含所有绘制点y值的列表。列表长度应与x_data的长度匹配。

  • color – 线条的颜色。有关所有可接受格式的完整列表,请参阅matplotlib.colors

  • linestyle - 线条样式。完整可接受的格式列表请参考matplotlib.lines.Line2D

  • linewidth (floatNone) - 线条宽度。当值为None时,将计算并使用默认值。

Returns

output (VisImage) – 绘制了线条的图像对象。

draw_binary_mask(binary_mask, color=None, *, edge_color=None, text=None, alpha=0.5, area_threshold=10)[源代码]
Parameters
  • binary_mask (ndarray) – 形状为(H, W)的numpy数组,其中H表示图像高度,W表示图像宽度。数组中的每个值都是uint8类型的0或1值。

  • color – 遮罩的颜色。有关所有可接受格式的完整列表,请参阅matplotlib.colors。如果为None,将随机选择一种颜色。

  • edge_color – 多边形边缘的颜色。有关可接受格式的完整列表,请参阅matplotlib.colors

  • text (str) – 如果为None,将会绘制在对象上

  • alpha (float) – 混合效率。数值越小,掩码越透明。

  • area_threshold (float) - 面积小于此阈值的连通组件将不会显示。

Returns

output (VisImage) – 绘制了掩码的图像对象。

draw_soft_mask(soft_mask, color=None, *, text=None, alpha=0.5)[源代码]
Parameters
  • soft_mask (ndarray) – 形状为(H, W)的浮点数组,每个值在[0, 1]范围内。

  • color - 遮罩的颜色。有关所有可接受格式的完整列表,请参阅matplotlib.colors。如果为None,将随机选择一种颜色。

  • text (str) – 如果为None,将会绘制在对象上

  • alpha (float) – 混合效率。数值越小,掩码越透明。

Returns

output (VisImage) – 绘制了掩码的图像对象。

draw_polygon(segment, color, edge_color=None, alpha=0.5)[源代码]
Parameters
  • segment – 形状为Nx2的numpy数组,包含多边形中的所有点。

  • color – 多边形的颜色。有关所有可接受的格式,请参阅matplotlib.colors

  • edge_color - 多边形边缘的颜色。关于可接受的颜色格式完整列表,请参考matplotlib.colors。如果未提供,将使用多边形颜色的较深色调替代。

  • alpha (float) – 混合效率。数值越小,遮罩越透明。

Returns

output (VisImage) – 绘制了多边形的图像对象。

get_output()[源代码]
Returns

output (VisImage) - 包含添加到图像中的可视化效果的图像输出。

detectron2.utils.video_visualizer 模块

class detectron2.utils.video_visualizer.VideoVisualizer(metadata, instance_mode=<ColorMode.IMAGE: 0>)[源代码]

基类: object

__init__(metadata, instance_mode=<ColorMode.IMAGE: 0>)[源代码]
Parameters

metadata (MetadataCatalog) - 图像元数据。

draw_instance_predictions(frame, predictions)[源代码]

在图像上绘制实例级别的预测结果。

Parameters
  • frame (ndarray) - 一个形状为(H, W, C)的RGB图像,数值范围在[0, 255]之间。

  • predictions (Instances) - 实例检测/分割模型的输出结果。以下字段将用于绘制: "pred_boxes"、"pred_classes"、"scores"、"pred_masks"(或"pred_masks_rle")。

Returns

output (VisImage) – 带有可视化效果的图像对象。

draw_sem_seg(frame, sem_seg, area_threshold=None)[源代码]
Parameters
  • sem_seg (ndarrayTensor) - 形状为(H, W)的语义分割结果, 每个值都是整数标签。

  • area_threshold (可选[int]) - 仅绘制大于阈值的分割区域