test_dataset = build_dataset(cfg.data.test, dict(test_mode=True))

build_dataset 是一个函数,它接受两个参数:cfg.data.test 和 dict(test_mode=True)。它返回一个名为 test_dataset 的数据集对象。

根据函数的命名和参数推测,build_dataset 函数用于构建测试数据集。它使用 cfg.data.test 参数来配置测试数据集的相关设置,并使用 dict(test_mode=True) 参数来设置测试模式为真(True)。

具体的数据集构建过程和返回的数据集对象的类型会根据实际实现而有所不同。通常情况下,数据集对象可能是一个自定义的数据集类的实例,该类继承自 PyTorch 中的 torch.utils.data.Dataset 类,或者是其他类似的数据集对象。

通过执行提供的代码,将使用相应的参数配置构建测试数据集,并将结果存储在 test_dataset 变量中,以供后续使用。

这行代码定义了一个名为 test 的字典,包含了一些用于测试的配置信息。这些配置信息包括:

  • type:数据集类型,存储在变量 dataset_type 中。
  • ann_file:注释文件的路径,存储在变量 ann_file 中。
  • split:数据集的划分方式,这里设置为 'xsub_val'
  • data_prefix:数据集文件的前缀路径,存储在变量 data_root 中。
  • pipeline:数据处理的管道,存储在变量 test_pipeline 中。

这些配置信息通常用于指定要使用的数据集、注释文件以及数据处理的方式。具体的数据集类型、注释文件路径、数据集划分、数据前缀路径和数据处理管道的内容将根据实际设置进行相应的配置。

通过将这些配置信息放在 test 字典中,可以方便地将其传递给其他函数或方法,以便构建和处理测试数据集。

 

逐行解释:

  1. tmpdir = cfg.get('evaluation', {}).get('tmpdir', osp.join(cfg.work_dir, 'tmp'))
    从配置文件 cfg 中获取 evaluation 对应的字典,然后获取其中的 tmpdir 键对应的值。如果没有找到该键,则使用默认值 osp.join(cfg.work_dir, 'tmp'),即将工作目录路径与 'tmp' 字符串拼接作为临时目录的路径,并将结果存储在 tmpdir 变量中。

  2. dataloader_setting = dict(videos_per_gpu=cfg.data.get('videos_per_gpu', 1), workers_per_gpu=cfg.data.get('workers_per_gpu', 1), persistent_workers=cfg.data.get('persistent_workers', False), shuffle=False)
    创建一个字典 dataloader_setting,包含用于配置数据加载器的设置。这些设置包括:

    • videos_per_gpu:每个GPU加载的视频数量,默认为1。
    • workers_per_gpu:每个GPU分配的数据加载器线程数,默认为1。
    • persistent_workers:是否持续使用加载器线程,默认为False。
    • shuffle:是否对数据进行洗牌,默认为False(即不洗牌)。
  3. dataloader_setting = dict(dataloader_setting, **cfg.data.get('test_dataloader', {}))
    从配置文件 cfg 的 data 字典中获取 test_dataloader 对应的字典,将其与 dataloader_setting 合并为一个新的字典,并将结果重新赋值给 dataloader_setting。这样可以通过配置文件覆盖默认的数据加载器设置。

  4. test_dataloader = build_dataloader(test_dataset, **dataloader_setting)
    使用 build_dataloader 函数构建测试数据加载器。它接受一个数据集对象 test_dataset 和一系列关键字参数 dataloader_setting,这些参数将被传递给数据加载器构造函数。最终,构建的数据加载器将存储在 test_dataloader 变量中。

通过执行上述代码,根据配置文件中的设置和默认值,构建了用于测试的数据加载器,并将其存储在 test_dataloader 变量中,以供后续使用。

 

videos_per_gpu=cfg.data.get('videos_per_gpu', 1),发现data字典,里面videos_per_gpu键的值是6

videos_per_gpu 的值是从配置文件的 data 字典中获取的,如果该键不存在,则默认值为 1。然而,你提到在 data 字典中,videos_per_gpu 键的值为 6。

因此,在这段代码中,videos_per_gpu 的值将是 6,因为它是从配置文件的 data 字典中获取的。这意味着每个 GPU 将加载并处理 6 个视频。

这种配置方式允许你在配置文件中灵活地调整每个 GPU 处理的视频数量,以适应你的计算资源和模型训练需求。在这种情况下,使用了配置文件中的值 6 来覆盖默认值 1。

 https://github.com/kennymckormick/pyskl/blob/main/pyskl/apis/train.py

class PrototypicalCalibrationBlock: def __init__(self, cfg): super().__init__() self.cfg = cfg self.device = torch.device(cfg.MODEL.DEVICE) self.alpha = self.cfg.TEST.PCB_ALPHA self.imagenet_model = self.build_model() self.dataloader = build_detection_test_loader(self.cfg, self.cfg.DATASETS.TRAIN[0]) self.roi_pooler = ROIPooler(output_size=(1, 1), scales=(1 / 32,), sampling_ratio=(0), pooler_type="ROIAlignV2") self.prototypes = self.build_prototypes() self.exclude_cls = self.clsid_filter() def build_model(self): logger.info("Loading ImageNet Pre-train Model from {}".format(self.cfg.TEST.PCB_MODELPATH)) if self.cfg.TEST.PCB_MODELTYPE == 'resnet': imagenet_model = resnet101() else: raise NotImplementedError state_dict = torch.load(self.cfg.TEST.PCB_MODELPATH) imagenet_model.load_state_dict(state_dict) imagenet_model = imagenet_model.to(self.device) imagenet_model.eval() return imagenet_model def build_prototypes(self): all_features, all_labels = [], [] for index in range(len(self.dataloader.dataset)): inputs = [self.dataloader.dataset[index]] assert len(inputs) == 1 # load support images and gt-boxes img = cv2.imread(inputs[0]['file_name']) # BGR img_h, img_w = img.shape[0], img.shape[1] ratio = img_h / inputs[0]['instances'].image_size[0] inputs[0]['instances'].gt_boxes.tensor = inputs[0]['instances'].gt_boxes.tensor * ratio boxes = [x["instances"].gt_boxes.to(self.device) for x in inputs] # extract roi features features = self.extract_roi_features(img, boxes) all_features.append(features.cpu().data) gt_classes = [x['instances'].gt_classes for x in inputs] all_labels.append(gt_classes[0].cpu().data)
06-09
dataset_type = 'PascalVOCDataset' data_root = 'data/VOCdevkit/VOC2012' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (512, 512) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations'), dict(type='Resize', img_scale=(2048, 512), ratio_range=(0.5, 2.0)), dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75), dict(type='RandomFlip', prob=0.5), dict(type='PhotoMetricDistortion'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_semantic_seg']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(2048, 512), # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75], flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict( type=dataset_type, data_root=data_root, img_dir='JPEGImages', ann_dir='SegmentationClass', split='ImageSets/Segmentation/train.txt', pipeline=train_pipeline), val=dict( type=dataset_type, data_root=data_root, img_dir='JPEGImages', ann_dir='SegmentationClass', split='ImageSets/Segmentation/val.txt', pipeline=test_pipeline), test=dict( type=dataset_type, data_root=data_root, img_dir='JPEGImages', ann_dir='SegmentationClass', split='ImageSets/Segmentation/val.txt', pipeline=test_pipeline)) 解释一下这个代码
07-13
import torch, os, cv2 from model.model import parsingNet from utils.common import merge_config from utils.dist_utils import dist_print import torch import scipy.special, tqdm import numpy as np import torchvision.transforms as transforms from data.dataset import LaneTestDataset from data.constant import culane_row_anchor, tusimple_row_anchor if __name__ == "__main__": torch.backends.cudnn.benchmark = True args, cfg = merge_config() dist_print('start testing...') assert cfg.backbone in ['18','34','50','101','152','50next','101next','50wide','101wide'] if cfg.dataset == 'CULane': cls_num_per_lane = 18 elif cfg.dataset == 'Tusimple': cls_num_per_lane = 56 else: raise NotImplementedError net = parsingNet(pretrained = False, backbone=cfg.backbone,cls_dim = (cfg.griding_num+1,cls_num_per_lane,4), use_aux=False).cuda() # we dont need auxiliary segmentation in testing state_dict = torch.load(cfg.test_model, map_location='cpu')['model'] compatible_state_dict = {} for k, v in state_dict.items(): if 'module.' in k: compatible_state_dict[k[7:]] = v else: compatible_state_dict[k] = v net.load_state_dict(compatible_state_dict, strict=False) net.eval() img_transforms = transforms.Compose([ transforms.Resize((288, 800)), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) if cfg.dataset == 'CULane': splits = ['test0_normal.txt', 'test1_crowd.txt', 'test2_hlight.txt', 'test3_shadow.txt', 'test4_noline.txt', 'test5_arrow.txt', 'test6_curve.txt', 'test7_cross.txt', 'test8_night.txt'] datasets = [LaneTestDataset(cfg.data_root,os.path.join(cfg.data_root, 'list/test_split/'+split),img_transform = img_transforms) for split in splits] img_w, img_h = 1640, 590 row_anchor = culane_row_anchor elif cfg.dataset == 'Tusimple': splits = ['test.txt'] datasets = [LaneTestDataset(cfg.data_root,os.path.join(cfg.data_root, split),img_transform = img_transforms) for split in splits] img_w, img_h = 1280, 720 row_anchor = tusimple_row_anchor else: raise NotImplementedError for split, dataset in zip(splits, datasets): loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle = False, num_workers=1) fourcc = cv2.VideoWriter_fourcc(*'MJPG') print(split[:-3]+'avi') vout = cv2.VideoWriter(split[:-3]+'avi', fourcc , 30.0, (img_w, img_h)) for i, data in enumerate(tqdm.tqdm(loader)): imgs, names = data imgs = imgs.cuda() with torch.no_grad(): out = net(imgs) col_sample = np.linspace(0, 800 - 1, cfg.griding_num) col_sample_w = col_sample[1] - col_sample[0] out_j = out[0].data.cpu().numpy() out_j = out_j[:, ::-1, :] prob = scipy.special.softmax(out_j[:-1, :, :], axis=0) idx = np.arange(cfg.griding_num) + 1 idx = idx.reshape(-1, 1, 1) loc = np.sum(prob * idx, axis=0) out_j = np.argmax(out_j, axis=0) loc[out_j == cfg.griding_num] = 0 out_j = loc # import pdb; pdb.set_trace() vis = cv2.imread(os.path.join(cfg.data_root,names[0])) for i in range(out_j.shape[1]): if np.sum(out_j[:, i] != 0) > 2: for k in range(out_j.shape[0]): if out_j[k, i] > 0: ppp = (int(out_j[k, i] * col_sample_w * img_w / 800) - 1, int(img_h * (row_anchor[cls_num_per_lane-1-k]/288)) - 1 ) cv2.circle(vis,ppp,5,(0,255,0),-1) vout.write(vis) vout.release()
04-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值