首先,是官方自己覺得很好的colab教程,我啥也運行不了,不說了,但是colab的教程告訴我一件事情,這個東西運行inference真的很簡單。
cfg = get_cfg() #有一個叫cfg的模型配置文件 # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
# cfg 獲取mask-rcnn的配置,我猜是這個意思
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
# 媽的這個閾值我不知道是啥意思。。。。。。 cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
# 給模型上參數,這個yaml文件里應該存了不少東西,存了模型結構,還存了網址?
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
#這里就是個坑了,defaultpredictor似乎是cuda的,我cpu predictor = DefaultPredictor(cfg) outputs = predictor(im)
outputs["instances"].pred_classes
outputs["instances"].pred_boxes
ok, 這個colab到此為止,我們回去看文檔,1.怎么在cpu下運行,2.怎么本地加載模型參數,3.怎么輸出我需要的信息,mask的結果,每個像素所屬的類別
https://detectron2.readthedocs.io/tutorials/models.html
#這三個輸出是比較有用的
- “scores”:
Tensor
, a vector of N scores. - “pred_classes”:
Tensor
, a vector of N labels in range [0, num_categories).
- “pred_masks”: a
Tensor
of shape (N, H, W), masks for each detected instance.
Another small thing to remember: detectron2 models do not support model.to(device)
or model.cpu()
. The device is defined in cfg.MODEL.DEVICE
and cannot be changed afterwards.#在cfg里面定義使用cpu
同志們,我算是看懂了,想用它的推理模型一共三步,先配置一個cfgnode
cfg = get_cfg() cfg.merge_from_file("../configs/COCO-InstanceSegmentatio/mask_rcnn_R_50_FPN_3x.yaml") cfg.merge_from_list(["MODEL.WEIGHTS", "../pre_train_model/model_final_f10217.pkl","MODEL.DEVICE","cpu"])#cfg加配置,用cpu一定要在這里寫cpu
predictor = DefaultPredictor(cfg) #用predictor包裝一下
output = predictor(im) #輸入圖片,output就是推理結果了
如果不想用predictor,要寫成
model = build_model(cfg)
output = model(input)
但是這種情況下,要按照API要求把input改成一個字典,我改成字典了還是運行不了,是不是一次輸入的圖片不足一個batch的原因呢?還不知道
反正predictor這個方法是可行的吧。
要看輸出也很簡單,
output["instances"].pred_classes 打印為每一個instance預測的類別,一張圖最后給了我48個instance,有點離譜.
類別不為0的有17個,大概為0的都是背景了
這篇先到這里,下一篇研究下,這個輸出到底咋回事,還有模型的選取問題。
真的要仔細,臨走發現個bug,忘了設置閾值,
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
加上了之后才和colab的結果一樣。