下面是整理后的代码,将各个步骤清晰地分段处理,并更新了模型权重的路径为本地文件路径:
# 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-PanopticSegmentation/panoptic_fpn_R_50_3x.yaml")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model
cfg.MODEL.WEIGHTS = "models/model_final_c10459.pkl" # Path to the local model file
predictor = DefaultPredictor(cfg)
outputs = predictor(im)
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2.imshow(v.get_image()[:, :, ::-1])
cv2.imwrite("./tmp/output.PanopticSegmentation.jpg", out.get_image()[:, :, ::-1]) # Save the output
分割效果: