我在视频上使用detectron2实现Mask-Rcnn,问题是在每一帧上,同一对象的分割颜色发生变化。
是否有任何参数可以让我为对象类保留单一颜色。 我已经尝试过 detectorron2.utils.visualizer.ColorMode(1) 但它不起作用
ColorMode(1)
的元数据定义了
Visualizer
时,
thing_colors
才有效。来自 ColorMode 的文档,
细分= 1
让同一类别的实例具有相似的颜色 (来自metadata.thing_colors),并用高不透明度覆盖它们。这 更加关注分割的质量。
因此,您需要将预定义颜色列表(每个类别一个)添加到您的元数据中。从这里,
(list[tuple(r, g, b)]):每个事物类别的预定义颜色(在 [0, 255] 中)。用于可视化。如果没有给出,将使用随机颜色。thing_colors
现在,实际使用的颜色可能与
thing_colors
中指定的颜色不完全相同。在 Visualizer.draw_instance_predictions()
中,每个指定的颜色都会通过添加随机值来抖动,因此叠加的颜色略有不同。使用随机值意味着您仍然会看到帧之间的类颜色发生变化。根据您指定的颜色,此更改可能在视觉上很明显,也可能不明显。
一个简单的解决方案可能是子类化
Visualizer
并重写 _jitter()
方法,以便它按原样返回颜色。
class MyVisualizer(Visualizer):
def _jitter(self, color):
return color
但是,
_jitter()
旨在成为一种内部方法,因此这是一个 hacky 解决方案,有时可能会崩溃。
更好的解决方案可能是覆盖
draw_instance_predictions()
并根据您的需要自定义绘图。
尝试添加以下行
from detectron2.utils.visualizer import Visualizer , GenericMask , ColorMode
MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).thing_classes = clss
MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).thing_colors = [(255,255,0),(0,0,255),(0,255,0),(255,0,255),(156,225,242)]
class MyVisualizer(Visualizer):
def _jitter(self, color ):
return color
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2,instance_mode=ColorMode.SEGMENTATION)
v = v.draw_instance_predictions(outputs["instances"].to("cpu"))
img = cv2.resize(v.get_image()[:, :, ::-1], (1220, 780))
这是我如何自定义可视化颜色及其工作原理的示例。
# Retrieve the validation dataset
metadata_valid = MetadataCatalog.get('data-valid')
# Add 'thing_colors' to metadata without setting its values
# Note: the 'thing_colors' field can be only set once and cannot be changed later
metadata_valid.set(thing_colors=None)
prediction_color = [0, 255, 0] # green for predctions
dataset_valid = DatasetCatalog.get(VALID_DATA_SET_NAME)
metadata = MetadataCatalog.get(VALID_DATA_SET_NAME)
### Run model on the validation dataset
for d in dataset_valid:
img = cv2.imread(d["file_name"])
outputs = predictor(img)
### Visualize predictions
visualizer_pred = Visualizer(
img[:, :, ::-1],
metadata=metadata,
scale=0.8,
instance_mode=ColorMode.SEGMENTATION
)
### Set a single color for all predictions
for cls in metadata.thing_classes:
visualizer_pred.metadata.thing_colors[metadata.thing_classes.index(cls)] = prediction_color
out_pred = visualizer_pred.draw_instance_predictions(outputs["instances"].to("cpu"))
希望有帮助!