detectron测试自己的数据

承接我的上一篇博文利用detectron训练自己的数据 ,训练好自己的模型文件后,总要进行应用吧,看看其他的数据库上检测的效果到底好不好撒,也就是测试。

1.测试数据存放

还是祭出这张图来,上一篇博文我们主要是训练模型,用到了训练数据和测试数据(一再强调这里测试数据的功能是评估验证模型,计算模型的mAP,称呼是测数据,代号书写是val),分别动用了下图中的两个数据接口voc_2007_train和voc_2007_val。

在真正要测试的时候就要动用voc_2007_test啦。看下图就应该知道测试数据图片应该放在哪了吧,就是自己创建的VOC2007/test_JPEGImages(detectron默认的test路径为VOC2007/JPEGImages,但是为了区别测试数据和训练验证数据,我将其改为test_JPEGImages)。因为前面已经创建了软链接(如果没有就根据下面的代码再生成一次呗),所以你把图片拷贝进VOC2007/JPEGImages,相应的软链接的另一端快捷方式中也会改变,这就很方便了。

2.制作测试数据的json文件

我使用的代码为:

"""
Created on Sun Jun 24 16:01:11 2018
对测试数据集生成coco格式
没有annotation
只有图片的信息和categories的信息
@author: wytwh
"""

import os
import json
import collections
import cv2 

coco = collections.OrderedDict()
coco['images'] = []
coco['type'] = 'instances'
coco['annotations'] = []
coco['categories'] = []

image_id = 2020000001 #对每张图片进行编号,初始编号
category_item_id = 1
classname = ['small-vehicle', 'large-vehicle', 'plane','harbor', 'ship', 
             'tennis-court', 'soccer-ball-field', 'ground-track-field',
             'baseball-diamond', 'swimming-pool', 'roundabout', 'basketball-court', 
             'storage-tank', 'bridge', 'helicopter']#更改为你自己的类别,与voc_2007_train中的一致


def GetFileFromThisRootDir(dir,ext = None):
  allfiles = []
  needExtFilter = (ext != None)
  for root,dirs,files in os.walk(dir):   #files是文件夹下所有文件的名称
    for filespath in files:            #依次取文件名
      filepath = os.path.join(root, filespath)    #构成绝对路径
      extension = os.path.splitext(filepath)[1][1:]  #os.path.splitext(path)  #分割路径,返回路径名和文件后缀 其中[1]为后缀.png,再取[1:]得到png
      if needExtFilter and extension in ext:
        allfiles.append(filepath)
      elif not needExtFilter:
        allfiles.append(filepath)
  return allfiles   #返回dir中所有文件的绝对路径


def addCatItem(name):
    '''
    增加json格式中的categories部分
    '''
    global category_item_id
    category_item = collections.OrderedDict()
    category_item['supercategory'] = 'none'
    category_item['id'] = category_item_id
    category_item['name'] = name
    coco['categories'].append(category_item)
    category_item_id += 1

def addImgItem(img_name, size):
    '''
    增加json格式中的images部分
    '''
    global image_id
    if img_name is None:
        raise Exception('Could not find Picture file.')
    if size['width'] is None:
        raise Exception('Could not find width.')
    if size['height'] is None:
        raise Exception('Could not find height.')
    #image_item = dict()    #按照一定的顺序,这里采用collections.OrderedDict()
    image_item = collections.OrderedDict()
    image_item['file_name'] = img_name  
    image_item['width'] = size['width']   
    image_item['height'] = size['height']
    image_item['id'] = image_id
    coco['images'].append(image_item) 
    image_id = image_id+1


def WriteCOCOFiles(pic_path):
    for idx,path in enumerate(pic_path):
        size = {}
        imgname = os.path.basename(path) #得到除去后缀的名字
        img = cv2.imread(path)
        size['height'] = img.shape[0] 
        size['width'] = img.shape[1]  
        addImgItem(imgname, size)
        print('add image with {} and {}'.format(imgname, size))
    for idx, obj in enumerate(classname):
        addCatItem(obj)          


if __name__ == '__main__':
    pic_dir = '/media/yantianwang/Elements/DOTA_biqi/Org_uncleaned/origin/testsplit/imagesSplit'    #图片存放的路径
    json_file = '/home/yantianwang/clone/VOC2007/Annotations/voc_2007_test.json'  #生成的coco路径
    pic_path = GetFileFromThisRootDir(pic_dir,ext = None)  #每一个图片的路径
    WriteCOCOFiles(pic_path)
json.dump(coco, open(json_file, 'w'))

还是看上面张图,应该知道生成的json文件名称应该为voc_2007_test.json,并且放置的位置是VOC2007/Annotations

3.生成软链接

DETECTRON=/home/yantianwang/clone/detectron
mkdir -p $DETECTRON/detectron/datasets/data/VOC2007
ln -s /home/yantianwang/clone/VOC2007/test_JPEGImages $DETECTRON/detectron/datasets/data/VOC2007/test_JPEGImages

如果你是训练完模型过来的,并且没有改变任何文件夹,这一步就可以略过了,因为你在训练模型的过程中已经创建软链接了。

4.修改yaml文件

修改你训练模型的yaml文件,因为要测试数据啊,自然要修改DATASETS为voc_2007_test,也就是调用voc_2007_test这个接口。同时修改检测输出的detection.pkl的路径。

5.运行测试命令

python2 tools/test_net.py \
    --cfg experiments/tutorial_1gpu_e2e_faster_rcnn_R-50-FPN.yaml \
    TEST.WEIGHTS experiments/org_train/train/voc_2007_train/generalized_rcnn/model_iter39999.pkl \
    NUM_GPUS 1

最后可能会报错说缺少test.txt,但其实是没有影响的,主要是因为我们前面生成的json文件中包含了category(类别)这个部分,因为我也尝试过json文件中不生成category,这时候运行测试命令则没有报错。

我个人猜测detectron在检测到json文件中存在category会默认地开启数据集的评估,通过下图我们也可以看到,报错的位置在voc_dataset_evaluator.py。但是尽管报错了,我们所需要的检测结果detection.pkl还是会生成的。

既然这样的话为什么还要生成catogary呢?因为我成生成detection.pkl后总需要可视化的呀,也要看看检测的结果噻。也就是需要运行tools/visualize_results.py,该文件需要json文件中catogary部分的支持。

6.可视化检测结果

python2 tools/visualize_results.py \
    --dataset voc_2007_test \
    --detections experiments/detections.pkl \
    --output-dir experiments \

经过上一篇博文的训练和现在的测试,你应该知道我们要做的就是把数据的形式变换成接口所要求的形式。然后通过yaml文件调用相应的接口。运行train_net.py调用voc_2007_train和voc_2007_val这两个接口。运行test_net.py可以调用voc_2007_val或者voc_2007_test,调用前者评估模型,调用后者对数据库进行检测生成detection.pkl

猜你喜欢

转载自blog.csdn.net/Mr_health/article/details/80817934
今日推荐