目錄
- 背景說明
- COCOeval 計算mAP
- txt文件轉換為coco json 格式
- 自定義數據集標注
背景說明
在完成YOLOv5模型移植,運行在板端后,通常需要衡量板端運行的mAP。
一般需要兩個步驟
步驟一:在板端批量運行得到目標檢測結果,可保存為yolo的txt格式也可保存為json格式;
目標檢測任務中常用的數據集格式(voc、coco、yolo)
步驟二:計算預測結果 和 標注結果的mAP,本文重點介紹該步驟。
探索歷程(可略過):如果想基于預測的txt計算mAP,推薦 Cartucho/mAP, 由于開發時間有限,最終還是決定基于json 格式進行計算。
COCOeval 計算mAP
經驗證該腳本不局限coco 80分類,只要滿足json數據集格式,即可使用該腳本進行計算
# get_map.py
import argparse
import glob
import jsonif __name__ == "__main__":import argparseimport globimport jsonif __name__ == "__main__":parser = argparse.ArgumentParser(description='')parser.add_argument('--result-json', type=str, help='Json of inference results.')parser.add_argument('--benchmark-json', type=str, help='Json of labels.')args = parser.parse_args()result_json = args.result_jsoninstances_train2017_json = args.benchmark_jsonwith open(result_json, 'r') as r:result = json.load(r)def get_img_id(item):return item["image_id"]imgIds = set(map(get_img_id, result))try:from pycocotools.coco import COCOfrom pycocotools.cocoeval import COCOevalcocoGt = COCO(glob.glob(instances_train2017_json)[0]) # initialize coco ground truth apicocoDt = cocoGt.loadRes(result_json) # initialize coco pred apicocoEval = COCOeval(cocoGt, cocoDt, 'bbox')cocoEval.params.imgIds = list(imgIds) # image IDs to evaluatecocoEval.evaluate()cocoEval.accumulate()cocoEval.summarize()map, map50 = cocoEval.stats[:2] # update results(mAP@0.5:0.95, mAP@0.5)except Exception as e:print('ERROR: pycocotools unable to run:%s' % e)
執行的命令行腳本如下
python get_map.py --result-json yolov5s_predictions.json --benchmark-json instances_val2017.json
輸出截圖如下,和官方的效果一致
- instances_val2017.json為COCO標準數據集,下載命令如下
# 下載標注文件(2017 Annotations)
wget http://images.cocodataset.org/annotations/annotations_trainval2017.zip
- yolov5s_predictions.json為yolov5 預測的數據集
執行YOLOv5源碼中的驗證腳本val.txt即可得到,需要注意,在運行時需要指定–save-json保存輸出結果的json文件,指定–save-conf在json文件中會保存預測框置信度。
python val.py --save-json --save-conf
數據格式如下
鏈接: https://pan.baidu.com/s/1udt4iPGEL0glxojS3OmklQ 提取碼: asdc
txt文件轉換為coco json 格式
- 訓練的txt文件,數據格式如下
58 0.389578 0.416103 0.038594 0.163146
62 0.127641 0.505153 0.233313 0.2227
對應【標簽 x y w h】
模型直接預測得到的txt文件,數據格式如下
46 0.0451243 0.215648 0.0848332 0.431296 0.725234
46 0.102373 0.546547 0.198804 0.326551 0.70208
對應【標簽 conf x y w h】
- json文件中數據格式如下
{
“image_id”: 5,
“category_id”: 0,
“bbox”: [
280.697,
41.816,
218.932,
349.688
],
“score”: 0.94485
},
其中bbbox為映射到原始圖片的值,同樣需要score分數
將預測的txt文件轉換為json格式
自定義數據集標注
1)準備圖片
2)使用LableImg標注工具
對目標進行標注
標注結果保存為VOC格式。
可將VOC格式轉換為JSON