Real-Time实例分割
实例分割DeepSnake使用篇使用篇
《Deep Snake for Real-Time Instance Segmentation》
这篇文章旨在记录一下我是如何搭建环境DeepSnake的,以及如何使用COCO数据集和自己的数据集训练实例分割模型,并进行测试的过程,具体原理在我的另一篇博客中。
作者:Sida Peng, Wen Jiang, Huaijin Pi, Xiuli Li, Hujun Bao, Xiaowei Zhou
CVPR 2020
Subjects: Computer Vision and Pattern Recognition (cs.CV)
https://github.com/zju3dv/snake/
Agile Pioneer
文章目录Preliminary环境搭建环境搭建参考1环境搭建参考2遇到的问题COCO数据COCO 训练COCO 测试训练自己的数据集方式一方式二
文章目录
Preliminary
对于任何一个深度学习模型来说都需要以下四部分信息:dataset,network,trainer和evaluator,这也是我们设计一个模型工程的组成部分。
dataset: 提供用于训练和测试的数据(data和target的数据格式)。
network: 模型的网络结构。
trainer: 定义损失函数和优化器用于训练。
evaluator: 定义衡量方法用于模型估计。
环境搭建
环境搭建
环境搭建参考1
环境搭建参考
作者提供了一个环境搭建的文档:https://github.com/zju3dv/snake/blob/master/INSTALL.md但是我照着做一直没有编译成功,外部依赖的三个模块dcn_v2、extreme_utils和
roi_align_layer,和作者沟通,作者说他使用gcc5.4.0进行编译的,大家可以用gcc5.4.0参照作者给出的环境搭建文档进行环境搭建。
环境搭建参考2
环境搭建参考
由于按照作者提供的环境搭建过程中出现了问题,所以我自己搭建了一套环境,是可以成功运行的,具体的依赖list如下,和版本相关的我都注明了版本号,其余的运行如果缺少
哪些库自行pip install或conda install安装即可:
CUDA – 10.1
cudnn – 7.6.0
python – 3.6
gcc & g++ – 7.3.0
pytorch – 1.2.0
torchvision – 0.4.0
opencv
imgaug
imageio
pycocotools
tqdm
yaml
tensorboardx
遇到的问题
遇到的问题
环境问题:
Q: libbz2.so.1.0: cannot open shared object file: No such file or directory
A: 这个库在/usr/lib64下,如果你指定的版本和/usr/lib64下的软连接名称不一样,只需要在你能依赖的路径下再软连接一个你需要的名字即可。
Q: error trying to exec ‘cc1plus’: execvp
A:两种可能:1、你没有安装g++;2、你的gcc的版本和g++版本不相符合,检查一下。
COCO数据数据
COCO 训练训练
下载COCO 2017数据集,地址如下
– train –
1.1 http://images.cocodataset.org/zips/train2017.zip
1.2 http://images.cocodataset.org/annotations/annotations_trainval2017.zip
– va –
1.3 http://images.cocodataset.org/zips/val2017.zip
1.4 http://images.cocodataset.org/annotations/stuff_annotations_trainval2017.zip
– test –
1.5 http://images.cocodataset.org/zips/test2017.zip
1.6 http://images.cocodataset.org/annotations/image_info_test2017.zip
修改数据路径:
2.1 vi lib/datasets/dataset_catalog.py,把里面对应coco部分的数据和标注文件改为你自己的路径即可。
'CocoTrain': {
'id': 'coco',
'data_root': 'data/coco/train2017',
'ann_file': 'data/coco/annotations/instances_train2017.json',
'split': 'train'
},
'CocoVal': {
'id': 'coco',
'data_root': 'data/coco/val2017',
'ann_file': 'data/coco/annotations/instances_val2017.json',
'split': 'test'
},
'CocoMini': {
'id': 'coco',
'data_root': 'data/coco/val2017',
'ann_file': 'data/coco/annotations/instances_val2017.json',
'split': 'mini'
},
'CocoTest': {
'id': 'coco_test',
'data_root': 'data/coco/val2017',
'ann_file': 'data/coco/annotations/instances_val2017.json',
'split': 'test'
},
2.2 新建一个 train.sh,内容如下,然后sh train.sh执行即可:
#!/bin/sh
python -W ignore train_net.py --cfg_file ./configs/coco_snake.yaml
COCO 测试测试
mkdir test_result # 用于存储可视化结果
vi lib/visualizers/snake.py# 在该脚本前面加
import random
# 修改 86 行最右,把plt.show(),改为如下
#plt.show()
filename = random.randint(0, 100000)
# 以随机数为名字存储,只查看效果
plt.savefig("test_result/%s.png"%filename)
新建一个test.sh,内容如下:然后sh test.sh执行即可:#!/bin/sh
python -W ignore run.py --type visualize --cfg_file configs/coco_snake.yaml ct_score 0.3
效果图如下:
训练自己的数据集
训练自己的数据集
方式一方式一
把自己的数据的Annotations弄成一个json和coco的格式一样,参考脚本如下:
import sys
import os
import json
import xml.etree.ElementTree as ET
START_BOUNDING_BOX_ID = 1
PRE_DEFINE_CATEGORIES = {"foreground":1}
# If necessary, pre-define category and its id
# PRE_DEFINE_CATEGORIES = {"aeroplane": 1, "bicycle": 2, "bird": 3, "boat": 4,
# "bottle":5, "bus": 6, "car": 7, "cat": 8, "chair": 9,
# "cow": 10, "diningtable": 11, "dog": 12, "horse": 13,
# "motorbike": 14, "person": 15, "pottedplant": 16,
# "sheep": 17, "sofa": 18, "train": 19, "tvmonitor": 20}
def get(root, name):
vars = root.findall(name)
return vars
def get_and_check(root, name, length):
vars = root.findall(name)
if len(vars) == 0:
raise NotImplementedError('Can not find %s in %s.'%(name, root.tag))
if length > 0 and len(vars) != length:
raise NotImplementedError('The size of %s is supposed to be %d, but is %d.'%(name, length, len(vars)))
if length == 1:
vars = vars[0] return vars
def get_filename_as_int(filename):
try:
filename = os.path.splitext(filename)[0] return int(filename)
except:
raise NotImplementedError('Filename %s is supposed to be an integer.'%(filename))
def convert( xml_dir, json_file,imgs):
# list_fp = open(xml_list, 'r')
json_dict = {"images":[], "type": "instances", "annotations": [],
"categories": []}
categories = PRE_DEFINE_CATEGORIES
bnd_id = START_BOUNDING_BOX_ID
list_fp = os.listdir(xml_dir)
for line in list_fp:
line = line.strip()
print("Processing %s"%(line))
xml_f = os.path.join(xml_dir, line)
tree = ET.parse(xml_f)
root = tree.getroot()
path = get(root, 'path')
if len(path) == 1:
filename = os.path.basename(path[0].text)
elif len(path) == 0:
filename = get_and_check(root, 'filename', 1).text
else:
raise NotImplementedError('%d paths found in %s'%(len(path), line))
## The filename must be a number
# image_id = get_filename_as_int(filename)
# image_id = filename.rstrip(".jpg").rstrip(".png")
image_id = line.replace(".xml","")
filename = image_id + ".jpg"
if filename not in imgs:
print (line)
print(filename)
size = get_and_check(root, 'size', 1)
width = int(get_and_check(size, 'width', 1).text)
height = int(get_and_check(size, 'height', 1).text)
image = {'file_name': filename, 'height': height, 'width': width,
'id':image_id}
json_dict['images'].append(image)
## Cruuently we do not support segmentation
# segmented = get_and_check(root, 'segmented', 1).text
# assert segmented == '0'
for obj in get(root, 'object'):
category = get_and_check(obj, 'name', 1).text
if category not in categories:
new_id = len(categories)
categories[category] = new_id
category_id = categories[category] bndbox = get_and_check(obj, 'bndbox', 1)
xmin = int(get_and_check(bndbox, 'xmin', 1).text) - 1
ymin = int(get_and_check(bndbox, 'ymin', 1).text) - 1
xmax = int(get_and_check(bndbox, 'xmax', 1).text)
ymax = int(get_and_check(bndbox, 'ymax', 1).text)
assert(xmax > xmin)
assert(ymax > ymin)
o_width = abs(xmax - xmin)
o_height = abs(ymax - ymin)
ann = {'area': o_width*o_height, 'iscrowd': 0, 'image_id':
image_id, 'bbox':[xmin, ymin, o_width, o_height],
'category_id': category_id, 'id': bnd_id, 'ignore': 0,
'segmentation': []}
json_dict['annotations'].append(ann)
bnd_id = bnd_id + 1
for cate, cid in categories.items():
cat = {'supercategory': 'none', 'id': cid , 'name': cate} # no + 1
json_dict['categories'].append(cat)
json_fp = open(json_file, 'w')
json_str = json.dumps(json_dict)
json_fp.write(json_str)
json_fp.close()
if __name__ == '__main__':
labelxml = "Annotations"
imgpath = "JPEGImages"
imgs = os.listdir(imgpath)
destjson = "voc2coco.json"
# if len(sys.argv) <= 1:
# print('3 auguments are need.')
# print('Usage: %s XML_LIST.txt XML_DIR OUTPU_JSON.json'%(sys.argv[0]))
# exit(1)
convert(labelxml, destjson,imgs)
方式二方式二
修改dataLoader的方法
作者:秋夜魔法师