開源代碼: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文件。