簡體   English   中英

如何為detectron2內置模型做輸入?

[英]How to do input for detectron2 builtinmodel?

我訓練了一個 model,現在我想用它來檢測圖像中的物體。 使用 DefaultDetector 僅返回 boundyboxes,我需要掩碼。 我看到你也可以用這個方法進行推理:

model.eval()
with torch.no_grad():
    outputs = model(inputs)

我認為這是他應該使用的。 問題是我不知道如何設置輸入,從圖像開始。

import torch
import glob
cfg = get_cfg()

cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/"
                                              "mask_rcnn_R_101_FPN_3x.yaml"))
cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
cfg.SOLVER.IMS_PER_BATCH = 1
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1 # only has one class
cfg.INPUT.FORMAT = "BGR"
#Just run these lines if you have the trained model im memory
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7 # set the testing threshold for this model
#build model
model = build_model(cfg)

DetectionCheckpointer(model).load("output/model_final.pth")

model.eval()#make sure its in eval mode

image = cv2.imread("/kaggle/working/detectron2/images/73-ab1.jpg")
height, width = image.shape[:2]
image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
image = ImageList.from_tensors([image])

with torch.no_grad():
    inputs = image
    outputs = model(inputs)

但是,不幸的是,我認為我錯了,有人可以啟發我嗎?

有關內置模型,請參閱Model 輸入格式

基本上,代碼中的 model 不需要ImageList object,而是一個dict list ,其中每個dict需要提供有關一個圖像的特定信息,如上面鏈接的文檔中所述。

因此,您的推理代碼需要更正為以下內容。

image = cv2.imread("/kaggle/working/detectron2/images/73-ab1.jpg")
height, width = image.shape[:2]
image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
inputs = [{"image": image, "height": height, "width": width}]

with torch.no_grad():
    outputs = model(inputs)

您還可以在代碼中看到這一點 - GeneralizedRCNN class 的forward方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM