detectron2:object detection 目標檢測

下面是整理后的代碼,將各個步驟清晰地分段處理,并更新了模型權(quán)重的路徑為本地文件路徑:

# Import required libraries
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog
import cv2

# Load the image
im = cv2.imread("./tmp/input.jpg")

# Configure the model
cfg = get_cfg()
cfg.merge_from_file("configs/COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # Set the threshold for object detection
cfg.MODEL.WEIGHTS = "models/model_final_f6e8b1.pkl"  # Path to the local model file

# Create predictor
predictor = DefaultPredictor(cfg)

# Make prediction
outputs = predictor(im)

# Visualize the output (optional)
# Uncomment the following lines if you want to visualize and save the result
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# cv2.imshow("Predictions", out.get_image()[:, :, ::-1])
# cv2.waitKey(0)  # Display until a key is pressed
cv2.imwrite("./tmp/output.ObjectDetection.jpg", out.get_image()[:, :, ::-1])  # Save the output

說明

  • cfg.MODEL.WEIGHTS 已更新為 models/model_final_f6e8b1.pkl,請確保此路徑和文件名與本地文件匹配。
  • 如果需要可視化預(yù)測結(jié)果,可取消最后幾行的注釋。
  • 確保在代碼運行時已安裝并配置好 detectron2 環(huán)境。

識別效果:


output.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容