前言
B站講解視頻
我的研究生畢業論文方向就是時空行為檢測,所以,slowfast和ava是我重點搞的,我的博客主頁也有很多這些相關內容。
終于,到了標注數據這一塊了,為了更簡單的標注數據,我要做的這部分的數據包含大量的人,每張圖片有30到40個人,如果要手動框人,再做行為標注,那是非常大的工作量,為了減小工作量,先使用faster rcnn把人的坐標算出來,然后倒入via中,實現算法的自動框人。
1 準備
1.1 detectron2安裝及faster rcnn運行
1.1.1 detectron2官方網站
- detectron2項目地址
- detectron2文檔
1.1.2 安裝步驟
安裝:
pip install -U torch torchvision cython
pip install -U 'git+https://github.com/facebookresearch/fvcore.git' 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'
git clone https://github.com/facebookresearch/detectron2 detectron2_repo
pip install -e detectron2_repo
1.1.3 Faster RCNN目標檢測
在終端輸入:
python3 demo.py --config-file ../configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml \--input ../img/1.jpg \--output ../img/1_1.jpg \--opts MODEL.WEIGHTS detectron2://COCO-Detection/faster_rcnn_R_50_FPN_3x/137849458/model_final_280758.pkl
1.1.4 參考
【Faster RCNN & detectron2】detectron2實現Faster RCNN目標檢測
1.2 via的安裝及使用
安裝很簡單,下載下來后,點開via.html就可以了
下載及使用指南:via官網
我下載的是2.0的版本,如下
2 faster rcnn 算法導出人類候選框為via格式
2.1 新建python腳本
在目錄/detectron2_repo/demo/下新建一個python腳本,名字為:myvia.py
將下面的代碼復制到myvia.py中
#Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import glob
import multiprocessing as mp
import os
import time
import cv2
import tqdm
import osfrom detectron2.config import get_cfg
from detectron2.data.detection_utils import read_image
from detectron2.utils.logger import setup_loggerfrom predictor import VisualizationDemoimport csv
import pandas as pd #導入pandas包
import re# constants
WINDOW_NAME = "COCO detections"def setup_cfg(args):# load config from file and command-line argumentscfg = get_cfg()# To use demo for Panoptic-DeepLab, please uncomment the following two lines.# from detectron2.projects.panoptic_deeplab import add_panoptic_deeplab_config # noqa# add_panoptic_deeplab_config(cfg)cfg.merge_from_file(args.config_file)cfg.merge_from_list(args.opts)# Set score_threshold for builtin modelscfg.MODEL.RETINANET.SCORE_THRESH_TEST = args.confidence_thresholdcfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = args.confidence_thresholdcfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = args.confidence_thresholdcfg.freeze()return cfgdef get_parser():parser = argparse.ArgumentParser(description="Detectron2 demo for builtin configs")parser.add_argument("--config-file",default="configs/quick_schedules/mask_rcnn_R_50_FPN_inference_acc_test.yaml",metavar="FILE",help="path to config file",)parser.add_argument("--webcam", action="store_true", help="Take inputs from webcam.")parser.add_argument("--video-input", help="Path to video file.")parser.add_argument("--input",nargs="+",help="A list of space separated input images; ""or a single glob pattern such as 'directory/*.jpg'",)parser.add_argument("--output",help="A file or directory to save output visualizations. ""If not given, will show output in an OpenCV window.",)parser.add_argument("--confidence-threshold",type=float,default=0.5,help="Minimum score for instance predictions to be shown",)parser.add_argument("--opts",help="Modify config options using the command-line 'KEY VALUE' pairs",default=[],nargs=argparse.REMAINDER,)return parserif __name__ == "__main__":mp.set_start_method("spawn", force=True)args = get_parser().parse_args()setup_logger(name="fvcore")logger = setup_logger()logger.info("Arguments: " + str(args))#圖片的輸入和輸出文件夾imgOriginalPath = './img/original/'imgDetectionPath= './img/detection'# 讀取文件下的圖片名字for i,j,k in os.walk(imgOriginalPath):# k 存儲了圖片的名字#imgInputPaths用于存儲圖片完整地址imgInputPaths = kcountI=0for namek in k:#循環將圖片的完整地址加入imgInputPaths中imgInputPath = imgOriginalPath + namekimgInputPaths[countI]=imgInputPathcountI = countI + 1break#修改args里輸入圖片的里路徑args.input = imgInputPaths#修改args里輸出圖片的路徑args.output = imgDetectionPathcfg = setup_cfg(args)demo = VisualizationDemo(cfg)#創建csvcsvFile = open("./img/detection.csv", "w+",encoding="gbk") #創建寫的對象CSVwriter = csv.writer(csvFile) #先寫入columns_name #寫入列的名稱CSVwriter.writerow(["filename","file_size","file_attributes","region_count","region_id","region_shape_attributes","region_attributes"]) #寫入多行用CSVwriter#寫入多行#CSVwriter.writerows([[1,a,b],[2,c,d],[3,d,e]])#csvFile.close()#https://blog.csdn.net/xz1308579340/article/details/81106310?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-3.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-3.controlif args.input:if len(args.input) == 1:args.input = glob.glob(os.path.expanduser(args.input[0]))assert args.input, "The input path(s) was not found"for path in tqdm.tqdm(args.input, disable=not args.output):# use PIL, to be consistent with evaluationimg = read_image(path, format="BGR")start_time = time.time()predictions,visualized_output = demo.run_on_image(img)#只要檢測結果是人的目標結果mask = predictions["instances"].pred_classes == 0pred_boxes = predictions["instances"].pred_boxes.tensor[mask]#在路徑中正則匹配圖片的名稱ImgNameT = re.findall(r'[^\\/:*?"<>|\r\n]+$', path)ImgName = ImgNameT[0]#獲取圖片大小(字節)ImgSize = os.path.getsize(path)#下面的為空(屬性不管)img_file_attributes="{"+"}"#每張圖片檢測出多少人img_region_count = len(pred_boxes)#region_id表示在這張圖中,這是第幾個人,從0開始數region_id = 0#region_attributes 為空img_region_attributes = "{"+"}"#循環圖中檢測出的人的坐標,然后做修改,以適應viafor i in pred_boxes:#將i中的數據類型轉化為可以用的數據類型(list)iList = i.cpu().numpy().tolist()#數據取整,并將坐標數據放入到img_region_shape_attributes = {"\"name\"" : "\"rect\"" , "\"x\"" : int(iList[0]) , "\"y\"" : int(iList[1]) ,"\"width\"" : int(iList[2]-iList[0]) , "\"height\"" : int(iList[3]-iList[1]) }#將信息寫入csv中CSVwriter.writerow([ImgName,ImgSize,'"{}"',img_region_count,region_id,str(img_region_shape_attributes),'"{}"'])region_id = region_id + 1logger.info("{}: {} in {:.2f}s".format(path,"detected {} instances".format(len(predictions["instances"]))if "instances" in predictionselse "finished",time.time() - start_time,))if args.output:if os.path.isdir(args.output):assert os.path.isdir(args.output), args.outputout_filename = os.path.join(args.output, os.path.basename(path))else:assert len(args.input) == 1, "Please specify a directory with args.output"out_filename = args.outputvisualized_output.save(out_filename)else:cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)cv2.imshow(WINDOW_NAME, visualized_output.get_image()[:, :, ::-1])if cv2.waitKey(0) == 27:break # esc to quit#關閉csv csvFile.close()
2.2 相關文件
2.2.1 img
在detectron2_repo/目錄下新建img文件,這個文件用來存儲輸入和輸出圖片
2.2.2 original、detection、detection.csv
在img文件夾下創建original、detection、detection.csv
original用于存放輸入的圖片
detection用于存放檢測后的圖片
detection.csv是faster rcnn算法計算出來的人的坐標數據,然后轉換為via可是別的csv文檔
2.3 圖片上傳
在original文件夾中上傳圖片,注意順序,這個順序要和后面via圖片順序一致
2.4 運行
準備好上面的后,在終端進入/detectron2_repo的目錄,輸入下面的命令:
python3 ./demo/myvia.py --config-file configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml --opts MODEL.WEIGHTS detectron2://COCO-Detection/faster_rcnn_R_50_FPN_3x/137849458/model_final_280758.pkl
2.5 查看detection.csv
接下來查看csv文件,結果如下:
3 via自動標注
3.1 進入via
首先進入到via的界面
下圖是從從官網下載的2.0版本的via,點開via.html
下圖是進入via后的樣子
3.2 導入圖片
點擊下圖顯示的 Add Files
選擇多個圖片
導入圖片后的樣子
3.4 修改detection.csv
使用notpad++(其它編譯器也可以)打開detection.csv,如下圖
使用替換功能,把全文的單引號全部刪除(我使用替換功能,把 ’ 替換為 空),如下圖所示
3.3 導入detection.csv
在Annotation中選擇 Import Annotations (from csv),在這里把detection.csv添加
導入csv后,就應該出現如下結果:
這些人就被自動框出來了。
總結
以上是生活随笔為你收集整理的【faster rcnn 实现via的自动框人】使用detectron2中faster rcnn 算法生成人的坐标,将坐标导入via(VGG Image Annotator)中,实现自动框选出人的区域的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。