Skip to content

Commit

Permalink
single image inference
Browse files Browse the repository at this point in the history
  • Loading branch information
czczup committed Jun 5, 2022
1 parent 3b12cbd commit cf10c91
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions segmentation/image_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser

import mmcv

import mmcv_custom # noqa: F401,F403
import mmseg_custom # noqa: F401,F403
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
from mmcv.runner import load_checkpoint
from mmseg.core import get_classes
import cv2
import os.path as osp


def main():
parser = ArgumentParser()
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument('img', help='Image file')
parser.add_argument('--out', type=str, default="demo", help='out dir')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
'--palette',
default='cityscapes',
help='Color palette used for segmentation map')
parser.add_argument(
'--opacity',
type=float,
default=0.5,
help='Opacity of painted segmentation map. In (0, 1] range.')
args = parser.parse_args()

# build the model from a config file and a checkpoint file

model = init_segmentor(args.config, checkpoint=None, device=args.device)
checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')
if 'CLASSES' in checkpoint.get('meta', {}):
model.CLASSES = checkpoint['meta']['CLASSES']
else:
model.CLASSES = get_classes(args.palette)

# test a single image
result = inference_segmentor(model, args.img)
# show the results
if hasattr(model, 'module'):
model = model.module
img = model.show_result(args.img, result,
palette=get_palette(args.palette),
show=False, opacity=args.opacity)
mmcv.mkdir_or_exist(args.out)
out_path = osp.join(args.out, osp.basename(args.img))
cv2.imwrite(out_path, img)
print(f"Result is save at {out_path}")

if __name__ == '__main__':
main()

0 comments on commit cf10c91

Please sign in to comment.