开源代码:https://www.aiuai.cn/aifarm778.html
环境需要:
- NumPy
- sklearn
- OpenCV
一、训练cosine_metric_learning
1、训练模型,得到.ckpt文件
python3 train_mars.py --dataset_dir=./resources/MARS-evaluation-master --loss_mode=cosine-softmax --log_dir=./output/mars/ --run_id=cosine-softmax
1)需要准备数据集,将dataset_dir中的数据调整到正确格式,与下载的bbox_train相同
修改图片文件名:[0:4]与图片上一级目录同,[4:6]相机ID,[6:11]跟踪ID,[11-15]图片序号
注意:将图片改成128宽成256高
车辆re-ID数据下载:https://download.csdn.net/download/chen_yuazzy/10601135
自定义脚本:image_rename.py 参考https://blog.csdn.net/m0_37592397/article/details/80372009
# -*- coding:utf8 -*-
import os
from PIL import Image
#定义创建目录函数
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\\")
# 判断路径是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
# 判断结果
if not isExists:
# 如果不存在则创建目录
# 创建目录操作函数
os.makedirs(path)
print(path + ' 创建成功')
return True
else:
# 如果目录存在则不创建,并提示目录已存在
print(path + ' 目录已存在')
return False
class BatchRename():
'''
批量重命名文件夹中的图片文件
'''
def __init__(self):
self.path = './resources/MARS-evaluation-master/dataset' #表示需要命名处理的文件夹
#修改图像尺寸
def resize(self):
for aroot, dirs, files in os.walk(self.path):
#aroot是self.path目录下的所有子目录(含self.path),dir是self.path下所有的文件夹的列表.
filelist = files #注意此处仅是该路径下的其中一个列表
#print('list', list)
#filelist = os.listdir(self.path) #获取文件路径
total_num = len(filelist) #获取文件长度(个数)
for item in filelist:
if item.endswith('.jpg'): #初始的图片的格式为jpg格式的(或者源文件是png格式及其他格式,后面的转换格式就可以调整为自己需要的格式即可)
src = os.path.join(os.path.abspath(aroot), item)
#修改图片尺寸到128宽*256高
im = Image.open(src)
out = im.resize((128, 256), Image.ANTIALIAS) # resize image with high-quality
out.save(src) #原路径保存
def rename(self):
for aroot, dirs, files in os.walk(self.path):
#aroot是self.path目录下的所有子目录(含self.path),dir是self.path下所有的文件夹的列表.
filelist = files #注意此处仅是该路径下的其中一个列表
#print('list', list)
#filelist = os.listdir(self.path) #获取文件路径
total_num = len(filelist) #获取文件长度(个数)
i = 1 #表示文件的命名是从1开始的
for item in filelist:
if item.endswith('.jpg'): #初始的图片的格式为jpg格式的(或者源文件是png格式及其他格式,后面的转换格式就可以调整为自己需要的格式即可)
src = os.path.join(os.path.abspath(aroot), item)
#根据图片名创建图片目录
dirname = str(item.split('_')[0])
#为相同车辆创建目录
new_dir = os.path.join(self.path,'..', 'bbox_train', dirname)
mkdir(new_dir)
#获得new_dir中的图片数
num_pic = len(os.listdir(new_dir))
dst = os.path.join(os.path.abspath(new_dir),
dirname + 'C1T0001F'+str(num_pic + 1) + '.jpg')
#处理后的格式也为jpg格式的,当然这里可以改成png格式 C1T0001F见mars.py filenames 相机ID,跟踪指数
#dst = os.path.join(os.path.abspath(self.path), '0000' + format(str(i), '0>3s') + '.jpg') 这种情况下的命名格式为0000000.jpg形式,可以自主定义想要的格式
try:
os.rename(src, dst)
print ('converting %s to %s ...' % (src, dst))
i = i + 1
except:
continue
print ('total %d to rename & converted %d jpgs' % (total_num, i))
if __name__ == '__main__':
demo = BatchRename()
demo.resize()
demo.rename()
2、查看训练结果
tensorboard --logdir ./output/mars/cosine-softmax --port 7006
3、输出训练好的模型,得到mars.pb文件
python train_mars.py --mode=freeze --restore_path=./output/mars/cosine-softmax/model.ckpt-11679
#restore_path是checkpoint文件的路径,需要精确到文件
二、运行yolo_v3:
python yolo_video.py --image
1、输入输出
输入的图片文件放在./image目录下
输出的det文件位置:./image/det/det.txt
2、需要安装keras
https://blog.csdn.net/qq_32329377/article/details/53008019
conda install -n my-py-env2 keras
The following packages will be downloaded:
package | build
---------------------------|-----------------
keras-2.2.4 | 0 5 KB https://mirrors.ustc.edu.cn/anaconda/pkgs/main
pyyaml-5.1.1 | py36h7b6447c_0 188 KB https://mirrors.ustc.edu.cn/anaconda/pkgs/main
yaml-0.1.7 | had09818_2 85 KB https://mirrors.ustc.edu.cn/anaconda/pkgs/main
keras-base-2.2.4 | py36_0 457 KB https://mirrors.ustc.edu.cn/anaconda/pkgs/main
------------------------------------------------------------
Total: 735 KB
Downloading and Extracting Packages
keras-2.2.4 | 5 KB | ####################################### | 100%
pyyaml-5.1.1 | 188 KB | ####################################### | 100%
yaml-0.1.7 | 85 KB | ####################################### | 100%
keras-base-2.2.4 | 457 KB | ####################################### | 100%
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
3、修改yolo_video.py,yolo.py文件,实现如下功能:
1)多图片输入
2)输出符合re-ID输入的det.txt文件
det.txt文件的格式:https://www.cnblogs.com/wemo/p/10600454.html bbox座标(x, y, w, h)
注意:yolov3中box的格式为top, left, bottom, right,而det文件中是left, top, width, height,需要转换一下
#yolo_video.py中修改
def detect_img(yolo):
path = "./image"
outdir = "./output"
#while True:
for jpgfile in glob.glob(os.path.join(path, '*.jpg')):
img = Image.open(jpgfile)
#接收输出结果,输出det.txt文件,保存检测结果
(img, out_boxes, out_scores) = yolo.detect_image(img)
f = open(os.path.join(path, 'det', 'det.txt'), 'a')
barename = os.path.splitext(os.path.basename(jpgfile))[0]
for i in range(len(out_boxes)):
box = out_boxes[i]
top, left, bottom, right = box
top = max(0, np.floor(top + 0.5).astype('int32'))
left = max(0, np.floor(left + 0.5).astype('int32'))
bottom = min(img.size[1], np.floor(bottom + 0.5).astype('int32'))
right = min(img.size[0], np.floor(right + 0.5).astype('int32'))
width = right - left
height = bottom - top
f.write(barename + ',')
f.write('-1' + ',' + str(left) + ',' + str(top) + ','
+ str(width) + ',' + str(height) + ','
+ str(out_scores[i]) + ',-1,-1,-1')
f.write('\n')
f.close()
img.save(os.path.join(outdir, os.path.basename(jpgfile)))
#yolo.py中168行,修改返回值
return (image,out_boxes,out_scores)
4、报错及环境配置
报错:could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
执行 :sudo rm -rf ~/.nv/ 未解决https://blog.csdn.net/xianqin_ma/article/details/79525519
安装了各种版本的tensorflow和cuda,最终1.12的tensorflow解决:https://www.cnblogs.com/aoru45/p/10811428.html
在conda虚拟环境中安装tensorflow1.12:
https://blog.csdn.net/qq_42412214/article/details/94917609
conda install tensorflow-gpu==1.12
安装sklearn库:
sudo pip install sklearn -i https://pypi.douban.com/simple
5、根据自己要识别的物体训练yolov3,没有进行,导致识别准确度较低
三、人员re-ID:
python3 tools/generate_detections.py --model=resources/networks/mars-small128.pb --mot_dir=./MOT16/train --output_dir=./resources/detections/MOT16_train
python3 tools/generate_detections.py --model=resources/networks/mars.pb --mot_dir=./MOT_exp/train --output_dir=./resources/detections/MOT16_train
1、用到的输入:
a)mars.pb文件(cos_metric训练得到)
b)img1图片(原始测试数据)
c) det.txt文件(不含轨迹信息,yolo检测得到)
2、输出:.npy文件
四、运行deep_sort:
python3 deep_sort_app.py --sequence_dir=./MOT16/test/MOT16-06 --detection_file=./resources/detections/MOT16_POI_test/MOT16-06.npy --min_confidence=0.3 --nn_budget=100 --display=True
python3 deep_sort_app.py --sequence_dir=./MOT_exp/train/mot_exp --detection_file=./resources/detections/MOT16_train/mot_exp.npy --min_confidence=0.3 --nn_budget=100 --display=True
1、用到的输入只有
a)图片:image_dir = os.path.join(sequence_dir, "img1")
b)序列信息文件:info_filename = os.path.join(sequence_dir, "seqinfo.ini")
修改其中的数据目录名name、图片数量seqLength、图片尺寸imWidth imHeight
c)检测的重识别文件.npy:if detection_file is not None:
detections = np.load(detection_file)
2、没有用到ground_truth文件gt.txt,因为test路径下没有这个文件,也没有用到det.txt文件。