行人属性识别一:训练PA100k数据集
序言
最近在做行人屬性識別相關的任務,本文用于記錄訓練過程,供以后復習查閱。
目前網上可用的行人屬性識別倉庫還是比較多的,比如前段時間百度開源的PP-Human屬性識別、PULC 人體屬性識別,以及京東的JDAI-CV/fast-reid都是比較優秀的工作,但是這里不打算用以上的項目,追述到源頭,發現百度和京東的行人屬性識別都是基于Rethinking_of_PAR該項目進行,所以我直接研究此項目即可,本文也將基于這個項目進行訓練,以及后續的修改模型和訓練自己的數據集。
行人屬性識別數據集最新指標 :https://paperswithcode.com/task/pedestrian-attribute-recognition/
其他相關項目:
- https://github.com/chufengt/ALM-pedestrian-attribute
- https://github.com/hyk1996/Person-Attribute-Recognition-MarketDuke
- https://github.com/xh-liu/HydraPlus-Net
一、數據集準備
訓練基于PA100k數據集,PA-100K數據集是迄今為止用于行人屬性識別的最大數據集,其中包含從室外監控攝像頭收集的總共100000張行人圖像,每張圖像都有26個常用屬性。根據官方設置,整個數據集隨機分為80000個訓練圖像、10000個驗證圖像和10000個測試圖像。
這里我將數據集打包放在我的百度云盤中供需要下載,鏈接: https://pan.baidu.com/s/1WLWCZujhENVAL0Iz0BXnQQ 密碼: iulh,下載下來后解壓得到圖片和.mat標簽文件,將release_data文件夾重命名為data,先放置一邊。
clone訓練倉庫下來:
git clone https://github.com/valencebond/Rethinking_of_PAR.git cd Rethinking_of_PAR這個倉庫提供了很多行人屬性數據集的訓練方式,各個數據集訓練的精度指標如下:
這里我只針對PA100k進行訓練,其他數據集準備方式大同小異,因為作者沒有提供預訓練好的模型(谷歌云盤失效了),所以如果你想測試的話,需要自己先跑一遍訓練,訓練時間并沒有很長。
因為該項目讀取的是.pkl格式的標注文件,所以需要解析上面下載的.mat,并保存為.pkl文件,幸運的是作者也把準備的腳本提供了,在dataset/pedes_attr/preprocess/format_pa100k.py中,在使用format_pa100k.py腳本文件之前,需要先閱讀一下dataset/pedes_attr/annotation.md,該文件的大致內容簡單來說就是,需要將數據集的各個屬性按照如下標準從頭到腳排序一下,統一的屬性順序為:
對于pa100k,26個屬性排序后的新順序為:
num_in_group = [2, 6, 6, 1, 4, 7]
‘Hat’,‘Glasses’, [7,8] 2
‘ShortSleeve’,‘LongSleeve’,‘UpperStride’,‘UpperLogo’,‘UpperPlaid’,‘UpperSplice’, [13,14,15,16,17,18] 6
‘LowerStripe’,‘LowerPattern’,‘LongCoat’,‘Trousers’,‘Shorts’,‘Skirt&Dress’, [19,20,21,22,23,24] 6
‘boots’ [25] 1
‘HandBag’,‘ShoulderBag’,‘Backpack’,‘HoldObjectsInFront’, [9,10,11,12] 4
‘AgeOver60’,‘Age18-60’,‘AgeLess18’, [1,2,3] 3
‘Female’ [0] 1
‘Front’,‘Side’,‘Back’, [4,5,6] 3
permutation = [7,8,13,14,15,16,17,18,19,20,21,22,23,24,25,9,10,11,12,1,2,3,0,4,5,6]
所以再去閱讀format_pa100k.py文件就清晰多了,根據剛才下載的數據集路徑,修改相關配置,然后運行后得到dataset_all.pkl文件,需要注意的是,如果沒有將數據集存放在./data/PA100k下的話,而是存放外部文件夾的話,加載數據集時會報錯,需要修改此處tools/function.py:
改成你的數據集路徑,不然默認加載./data里的,看著修改就好了。
二、開始訓練
修改configs/pedes_baseline/pa100k.yaml配置文件中的相關配置,批次大小、長寬、backbone等,修改完直接在終端中運行:
python train.py --cfg ./configs/pedes_baseline/pa100k.yaml出現如下界面,即訓練開始:
如果覺得打印的間隔太長,可以修改文件中的打印間隔:
訓練結束后模型保存在exp_result文件夾中的pa100k/img_model,只有一個模型,因為該模型的名字在訓練時由時間戳確定,所以后面以更優精度保存下來的模型都會覆蓋該模型,如果想修改模型保存的名字,可以修改該行代碼:
保存下來的模型名字帶有最優的epoch和最優精度信息,看起來更加簡單明了一點。
訓練得到的最優精度為:
三、模型測試
因為作者沒有提供單獨測試某張圖片的代碼,所以我基于infer.py文件進行修改,得到demo.py文件,用于測試單張或者文件夾內多張圖片功能:
import argparse import json import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import picklefrom dataset.augmentation import get_transform from dataset.multi_label.coco import COCO14 from metrics.pedestrian_metrics import get_pedestrian_metrics from models.model_factory import build_backbone, build_classifierimport numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm from PIL import Image from configs import cfg, update_config from dataset.pedes_attr.pedes import PedesAttr from metrics.ml_metrics import get_map_metrics, get_multilabel_metrics from models.base_block import FeatClassifier # from models.model_factory import model_dict, classifier_dictfrom tools.function import get_model_log_path, get_reload_weight from tools.utils import set_seed, str2bool, time_str from models.backbone import swin_transformer, resnet, bninception,repvggset_seed(605)clas_name = ['Hat','Glasses','ShortSleeve','LongSleeve','UpperStride','UpperLogo','UpperPlaid','UpperSplice','LowerStripe','LowerPattern','LongCoat','Trousers','Shorts','Skirt&Dress','boots','HandBag','ShoulderBag','Backpack',,'HoldObjectsInFront','AgeOver60','Age18-60','AgeLess18','Female','Front','Side','Back']def main(cfg, args):exp_dir = os.path.join('exp_result', cfg.DATASET.NAME)model_dir, log_dir = get_model_log_path(exp_dir, cfg.NAME)train_tsfm, valid_tsfm = get_transform(cfg)print(valid_tsfm)backbone, c_output = build_backbone(cfg.BACKBONE.TYPE, cfg.BACKBONE.MULTISCALE)classifier = build_classifier(cfg.CLASSIFIER.NAME)(nattr=26,c_in=c_output,bn=cfg.CLASSIFIER.BN,pool=cfg.CLASSIFIER.POOLING,scale =cfg.CLASSIFIER.SCALE)model = FeatClassifier(backbone, classifier)if torch.cuda.is_available():model = torch.nn.DataParallel(model).cuda()model = get_reload_weight(model_dir, model, pth='best_11_0.8044.pth') # 修改此處的模型名字model.eval()with torch.no_grad():for name in os.listdir(args.test_img):print(name)img = Image.open(os.path.join(args.test_img,name))img = valid_tsfm(img).cuda()img = img.view(1, *img.size())valid_logits, attns = model(img)valid_probs = torch.sigmoid(valid_logits[0]).cpu().numpy()valid_probs = valid_probs[0]>0.5res = []for i,val in enumerate(valid_probs):if val:res.append(clas_name[i])if i ==14 and val==False:res.append("male")print(res)print()def argument_parser():parser = argparse.ArgumentParser(description="attribute recognition",formatter_class=argparse.ArgumentDefaultsHelpFormatter)parser.add_argument("--test_img", help="test images", type=str,default="./test_imgs",)parser.add_argument("--cfg", help="decide which cfg to use", type=str,)parser.add_argument("--debug", type=str2bool, default="true")args = parser.parse_args()return argsif __name__ == '__main__':args = argument_parser()update_config(cfg, args)main(cfg, args)運行命令:python demo.py --cfg ./configs/pedes_baseline/pa100k.yaml --test_img ./test_imgs,得到類似如下結果:
我這里的結果是將列表里的英文翻譯成中文顯示處理,至此訓練結束,下一篇將寫如何修改添加新的網絡進行訓練。
總結
以上是生活随笔為你收集整理的行人属性识别一:训练PA100k数据集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 目前开源数据集整理
- 下一篇: 华南理工提出多模态ReID新数据集,语义