我想利用mmsegmentation跑demo文件请问我的命令是什么呢

생성일: 2025년 4월 15일

답변에 사용된 모델 O1 by Chat01

질문

我想利用mmsegmentation跑demo文件请问我的命令是什么呢

사고

Reasoned about mmsegmentation demo command for 7 seconds

답변

下面给出一个常见的用 MMSegmentation 跑 demo(推理单张图像)的命令示例,供你参考。假设你已经安装好 mmsegmentation,并且有对应的配置文件和权重文件,可执行命令如下:

bash
python demo/image_demo.py \ demo/demo.png \ configs/segmentor/fcn/fcn_r50-d8_512x512_160k_ade20k.py \ checkpoints/fcn_r50-d8_512x512_160k_ade20k_20200614_215451-9fdf08ef.pth \ --device cuda:0 \ --palette ade20k \ --out-file result.png
  • demo/demo.png:这是你要进行推理的输入图像路径。
  • configs/segmentor/fcn/fcn_r50-d8_512x512_160k_ade20k.py:这是 mmsegmentation 的配置文件路径,你可以根据你使用的模型找到对应的配置文件。
  • checkpoints/fcn_r50-d8_512x512_160k_ade20k_20200614_215451-9fdf08ef.pth:这是与配置文件对应的模型权重文件。
  • --device cuda:0:指定使用 GPU(如若没有 GPU,可以改成 cpu)。
  • --palette ade20k:指定可视化结果的调色板,可选值视任务和数据集而定,例如 cityscapesade20k 等。
  • --out-file result.png:推理完成后保存的结果图像文件名。

如果你想要在命令行快速查看或者进行可视化选项,可以添加更多参数,例如:

  • --opacity 0.5:设置分割结果与原图混合的透明度。
  • --save-dir results/:设置保存可视化图片的目录(如果你想保存到固定文件夹,而不是单一结果文件)。

根据你的实际情况(模型、数据集、配置等)修改命令中相关路径即可。

질문

请根据他的img_demo.py的内容:# Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser

from mmengine.model import revert_sync_batchnorm

from mmseg.apis import inference_model, init_model, show_result_pyplot

def main():
parser = ArgumentParser()
parser.add_argument('img', help='Image file')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument('--out-file', default=None, help='Path to output file')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
'--opacity',
type=float,
default=0.5,
help='Opacity of painted segmentation map. In (0, 1] range.')
parser.add_argument(
'--with-labels',
action='store_true',
default=False,
help='Whether to display the class labels.')
parser.add_argument(
'--title', default='result', help='The image identifier.')
args = parser.parse_args()

text
# build the model from a config file and a checkpoint file model = init_model(args.config, args.checkpoint, device=args.device) if args.device == 'cpu': model = revert_sync_batchnorm(model) # test a single image result = inference_model(model, args.img) # show the results show_result_pyplot( model, args.img, result, title=args.title, opacity=args.opacity, with_labels=args.with_labels, draw_gt=False, show=False if args.out_file is not None else True, out_file=args.out_file)

if name == 'main':
main()
告诉我他的报错如何解决:(mmsegmentation) a@fuwuqi:/media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation$ python demo/image_demo.py /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/demo/000000.png /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/configs/pidnet/xuanguashi-s_2xb6-120k_1024x1024-cityscapes.py /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/work_dirs/xuanguashi-s_2xb6-120k_1024x1024-cityscapes/iter_120000.pth /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/outputs/1.jpg
usage: image_demo.py [-h] [--out-file OUT_FILE] [--device DEVICE] [--opacity OPACITY] [--with-labels] [--title TITLE] img config checkpoint
image_demo.py: error: unrecognized arguments: /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/outputs/1.jpg

사고

Adjusting positional arguments

I’m noticing an incorrect positional argument for out-file. It should be --out-file. The correct syntax is python demo/image_demo.py /path/to/img /path/to/config /path/to/checkpoint --out-file /path/to/save_img.jpg.

Reasoned about script argument error for 7 seconds

답변

从报错信息可以看出,脚本 image_demo.py 只接受 3 个位置参数img, config, checkpoint),而你传入了 4 个位置参数,导致第 4 个路径(输出文件路径)被错误地识别为了未知参数。

根据你的 img_demo.py 源码:

plaintext
usage: image_demo.py [-h] [--out-file OUT_FILE] [--device DEVICE] ... [--opacity OPACITY] [--with-labels] [--title TITLE] img config checkpoint
  • 第 1 个位置参数:img
  • 第 2 个位置参数:config
  • 第 3 个位置参数:checkpoint
  • 其中输出文件是通过可选参数 --out-file 指定的。

因此,你的命令需要改为在后面加上 --out-file,而不是直接放在位置参数中。例如:

bash
python demo/image_demo.py \ /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/demo/000000.png \ /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/configs/pidnet/xuanguashi-s_2xb6-120k_1024x1024-cityscapes.py \ /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/work_dirs/xuanguashi-s_2xb6-120k_1024x1024-cityscapes/iter_120000.pth \ --out-file /media/a/7E66D8986C7B8B6A/liwei23/mmsegmentation/outputs/1.jpg

这样即可解决“unrecognized arguments”的错误。

질문

我现在只有两个类别,轨道区域个非轨道区域,在标注数据时我只标注了轨道,其余按照空白进行训练,但是现在跑demo后,我的轨道区域颜色我不想要现在的紫色,我要红色,而且我不想让他标注除了轨道的空白,怎么处理呢

사고

Addressing region coloring

User's goal is to uniquely color the track region while omitting the background in "轨道" and "非轨道" classes, using a custom color palette in segmentation.

Mapping out classes

I'm thinking about how to control the display of track regions using a specific color palette in the config and the mmseg library.

Ensuring background transparency

I’m considering making the background transparent or black to avoid conflict with the raw image. Alternatively, setting opacity to 0% could be an effective solution.

Hiding background

I'm focusing on hiding the background using thresholding and overlaying only the track region, potentially specifying "with_labels = True" in the config to achieve this effect.

Focusing on track visualization

By setting the background to black and using alpha transparency or opacity settings, the emphasis is on the track region. This method ensures the track remains foregrounded.

Focusing the track

Using a palette with a single color for the track and a transparent background, achieved through custom scripting or configuration, ensures a clear emphasis on the track.

Configuring visuals

By setting the track as red and the background as black, and using img_demo.py, the desired visual effect is achieved through effective configuration.

Ensuring visual clarity

It's interesting to see that setting ignore_index=255 keeps the background uncolored or unlabeled, preventing confusion and maintaining a clear focus.

Ensuring clarity

Using custom scripting to make the background transparent in the final mask ensures clarity, preventing mix-up and focusing on the main track.

Crafting the solution

The custom script, incorporating a specified palette to differentiate non-rail and rail classes, offers a straightforward and clear method for data segmentation.

Highlighting key elements

Overlaying the track in red with partial transparency showcasing the original background creates a well-balanced, clear, and informative visual representation.

Reasoned about segmentation color and labeling for 40 seconds

답변

在 MMSegmentation 中,如果你只有两个类别(例如:0 表示背景、1 表示轨道),而且想要在可视化时只显示“轨道”这个类,且将其渲染为红色(背景不再渲染成默认的紫色),一般可以从以下两个层面来处理


1. 在配置文件里自定义调色板

在你的配置文件(如 xxx.py)中,通常会有一个关于元信息的字段(在最新版本中常常叫 metainfo 或者写在 dataset_meta 里),其中可以定义数据集的 类别名称(classes)和 调色板(palette)。比如你有两个类别:

  • 类别 0:背景
  • 类别 1:轨道

可以像下面这样做(仅示例,具体写法请对应你自己的 config 结构):

python
# 在 config 中,比如最上方或 model / dataset 下 metainfo = dict( classes=('background', 'track'), # 或者你想要的类别名 # palette 的顺序要和 classes 的顺序一一对应 # 这里将背景指定为 [0, 0, 0] (黑色),轨道指定为 [255, 0, 0] (红色) palette=[[0, 0, 0], [255, 0, 0]] )

这样训练好后,你在推理阶段调用官方自带的可视化接口(例如 show_result_pyplot)时,就会使用你在 config 中定义的调色板来渲染结果:

  • 背景会是黑色(索引 0)。
  • 轨道会是红色(索引 1)。

如果你不想“可视化背景”,通常有两种思路:

  1. 让背景显示为透明,这在官方脚本中并没有直接的“透明”调色板概念,而是通过 opacity 参数设置将预测结果与原图叠加的透明度。如果想让背景完全不显现,可将背景定义成跟原图一样的“无差别”,但这需要做一些后处理(见下文第 2 种方法)。
  2. 把背景颜色设置成与原图一致,并使用 opacity 来叠加,这样人眼看上去就不会觉得背景被涂上别的颜色。

如果你只需要简易地 “轨道区域是红色,其它地方保持原图”,可配合 --opacity 使用。例如:

bash
python demo/image_demo.py \ /path/to/img.jpg \ /path/to/config.py \ /path/to/weight.pth \ --device cuda:0 \ --out-file /path/to/result.jpg \ --opacity 0.5

这样轨道区域会有一个半透明红色的叠加,背景会保留半透明的原图信息。你可通过调节 opacity(0~1)来控制轨道区域叠加效果的强弱。


2. 在推理脚本中自定义后处理逻辑

如果你需要更灵活地“只涂轨道,完全不涂其它区域”——也就是背景在可视化时直接看原图、不覆盖任何颜色,那么可以自己改写一下推理脚本,比如:

  1. 用官方接口 inference_model(model, img) 得到语义分割结果 result
  2. 手动将 result 转成一个 mask(背景=0,轨道=1),然后只对 mask == 1 的像素做红色叠加,背景位置保持原图不变。

示例(简化版逻辑):

python
import cv2 import numpy as np from mmseg.apis import init_model, inference_model model = init_model(config='xxx.py', checkpoint='xxx.pth', device='cuda:0') result = inference_model(model, 'test.jpg') # 获取预测的分割掩码 (一般会在 result.pred_sem_seg 里) pred_mask = result.pred_sem_seg.data[0].cpu().numpy() # shape = [H, W] img = cv2.imread('test.jpg') # BGR img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 如需 RGB 操作 # 想要红色 [255, 0, 0] (注意在 RGB 里是红色) red_color = np.array([255, 0, 0], dtype=np.uint8) # 只对 pred_mask == 1 位置涂红 # 举例:简单叠加 50% 透明度 alpha = 0.5 indices = np.where(pred_mask == 1) img[indices] = img[indices] * (1 - alpha) + red_color * alpha # 保存结果 cv2.imwrite('result.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR))

这样就可以只在“轨道”区域上色,背景区域完全是原图,而且可以自定义任何颜色、任何透明度。

如果你想完全把轨道涂满红色,不需要与原图混合,可以去掉透明度操作,直接:

python
img[indices] = red_color

总结

  1. 最方便的方法

    • 在配置文件中正确写好 classespalette,并使用官方命令行参数 --out-file--opacity 等就能生成半透明可视化结果。此时只要把背景对应的颜色改成你想要的(如黑色 [0, 0, 0]),轨道对应的颜色改成 [255, 0, 0] 即可。
  2. 高级自定义方法

    • 若需要只保留原图 + 轨道(红色),完全不画背景,可以自己在脚本中对推理结果做后处理,灵活定制可视化效果。

这样便能实现“轨道区域是红色,且对背景不进行额外着色或显示”。

이 Q&A 공유하기