博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mmdetectionv1.0.0-inference代码--修改config-batch图像数目,学习率下降等--训练期间测试开启-训练灰度
阅读量:2051 次
发布时间:2019-04-28

本文共 4592 字,大约阅读时间需要 15 分钟。

inference代码 

import mmcvimport osfrom mmdet.apis import init_detector, inference_detector, show_resultconfig_file = 'configs/mask_rcnn_r50_fpn_1x.py'checkpoint_file = 'checkpoint/epoch_200.pth'model = init_detector(config_file, checkpoint_file, device='cuda:0')path = "data/box_for_label"imgs = []trainimg = os.listdir("data/box_for_label")for lab in range(len(trainimg)):    subname = trainimg[lab]    name = os.path.join(path, subname)    imgs.append(name)import numpy as npimport cv2import pycocotools.mask as maskUtilsscore_thr=0.3for lab in range(len(imgs)):    img = imgs[lab]    result = inference_detector(model, img)    img = mmcv.imread(img)    img = img.copy()    oriimg = img.copy()    if isinstance(result, tuple):        bbox_result, segm_result = result    else:        bbox_result, segm_result = result, None    bboxes = np.vstack(bbox_result)    # draw segmentation masks    if segm_result is not None:        segms = mmcv.concat_list(segm_result)        inds = np.where(bboxes[:, -1] > score_thr)[0]        np.random.seed(42)        color_masks = np.random.randint(0, 256, (1, 3), dtype=np.uint8)        for i in inds:            i = int(i)            mask = maskUtils.decode(segms[i]).astype(np.bool)            img[mask] = img[mask] * 0.5 + color_masks * 0.5    h1, w1 = oriimg.shape[:2]    h2, w2 = img.shape[:2]    vis = np.zeros((max(h1, h2), w1 + w2, 3), np.uint8)    vis[:h1, :w1, :] = oriimg    vis[:h2, w1:w1 + w2, :] = img    out_file = 'result_{}.jpg'.format(lab)    cv2.imwrite(out_file, vis)

 

训练灰度

如果你想训练灰度图,在这个版本,你应该:

mmdetection/mmdet/datasets/pipelines/loading.py

@PIPELINES.register_moduleclass LoadImageFromFile(object):    def __init__(self, to_float32=False, color_type='color'):        self.to_float32 = to_float32        self.color_type = color_type    def __call__(self, results):        if results['img_prefix'] is not None:            filename = osp.join(results['img_prefix'],                                results['img_info']['filename'])        else:            filename = results['img_info']['filename']        img = mmcv.imread(filename, self.color_type)        if self.to_float32:            img = img.astype(np.float32)        results['filename'] = filename        results['img'] = img        results['img_shape'] = img.shape        results['ori_shape'] = img.shape        return results    def __repr__(self):        return '{} (to_float32={}, color_type={})'.format(            self.__class__.__name__, self.to_float32, self.color_type)

 

img = mmcv.imread(filename, self.color_type)  后面接一段代码:

import cv2

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)



训练期间测试开启

--validate

#!/usr/bin/env bashPYTHON=/home/apple/anaconda3/envs/py36_mmdetection/bin/pythonCONFIG=$1GPUS=$2GPUNAME=$3PORT=${PORT:-29500}$PYTHON -m torch.distributed.launch --nproc_per_node=$GPUS --master_port=$PORT \    $(dirname "$0")/train.py $CONFIG --gpus $GPUNAME --validate --launcher pytorch ${@:4}

修改多少次进行一次测试:

configs/mask_rcnn_r50_fpn_1x.py

# yapf:enable

evaluation = dict(interval=50)



修改config-batch图像数目,学习率下降等

修改:

train_pipeline = [

    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
    dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
    dict(type='RandomFlip', flip_ratio=0.5),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='Pad', size_divisor=32),
    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']),
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=(1333, 800),
        flip=False,
        transforms=[
            dict(type='Resize', keep_ratio=True),
            dict(type='RandomFlip'),
            dict(type='Normalize', **img_norm_cfg),
            dict(type='Pad', size_divisor=32),
            dict(type='ImageToTensor', keys=['img']),
            dict(type='Collect', keys=['img']),
        ])
]

..............................

data = dict(

    imgs_per_gpu=4,
    workers_per_gpu=2,
    train=dict(
        type=dataset_type,
        ann_file=data_root + 'annotations/instances_train2017.json',
        img_prefix=data_root + 'train2017/',
        pipeline=train_pipeline),
    val=dict(
        type=dataset_type,
        ann_file=data_root + 'annotations/instances_val2017.json',
        img_prefix=data_root + 'val2017/',
        pipeline=test_pipeline),
    test=dict(
        type=dataset_type,
        ann_file=data_root + 'annotations/instances_val2017.json',
        img_prefix=data_root + 'val2017/',
        pipeline=test_pipeline))
..............................

# learning policy

lr_config = dict(
    policy='step',
    warmup='linear',
    warmup_iters=500,
    warmup_ratio=1.0 / 3,
    step=[40, 80, 120])

52%   71C    P2   185W / 250W |  10227MiB / 11019MiB |     72%      Default 

显存刚好利用上,再大一点就不行了



 

 

 

转载地址:http://awwlf.baihongyu.com/

你可能感兴趣的文章
【Loadrunner】性能测试:通过服务器日志获取性能需求
查看>>
【python】BeautifulSoup的应用
查看>>
【Python】接口自动化测试-Fidder的使用(未完待续……)
查看>>
【Python】自动化测试框架-共通方法汇总
查看>>
【Python】if相关知识点
查看>>
【Python】xpath中为什么粘贴进去代码后老报错?如何在定位元素的时候准确找到定位切入点?...
查看>>
Loadrunner解决启动浏览器后页面显示空白
查看>>
【Python】唯品会购买商品
查看>>
【JMeter】如何录制创建及得到曲线图
查看>>
【English】【托业】【四六级】写译高频词汇
查看>>
【托业】【新东方全真模拟】01~02-----P5~6
查看>>
【托业】【新东方全真模拟】03~04-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST05~06-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST09~10-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST07~08-----P5~6
查看>>
solver及其配置
查看>>
JAVA多线程之volatile 与 synchronized 的比较
查看>>
Java集合框架知识梳理
查看>>
笔试题(一)—— java基础
查看>>
Redis学习笔记(二)— 在linux下搭建redis服务器
查看>>