使用預先訓練的 Mask R-CNN 進行分割
在這個練習中,你會使用預先訓練的 Mask R-CNN 模型,對下方的兩隻貓影像進行實例分割。

你要使用的模型已在 COCO 資料集上預先訓練。該資料集包含常見物體的影像,包括動物。因此,模型應該能直接辨識出貓,而不需要再微調。
你的任務是載入模型與兩隻貓的影像、完成影像前處理,並將其傳入模型以取得預測結果。PIL 的 Image、torch、torchvision 的 transforms,以及 maskrcnn_resnet50_fpn 都已為你匯入。
本練習屬於課程
使用 PyTorch 進行影像深度學習
練習說明
- 使用
maskrcnn_resnet50_fpn()載入pretrained的 Mask R-CNN 到model。 - 將兩隻貓的影像轉換成張量並執行 unsqueeze。
- 將影像傳入模型進行推論,並將輸出指定給
prediction。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Load a pre-trained Mask R-CNN model
model = ____(____)
model.eval()
# Load an image and convert to a tensor
image = Image.open("two_cats.jpg")
transform = transforms.Compose([transforms.ToTensor()])
image_tensor = transform(image).____
# Perform inference
with torch.no_grad():
prediction = ____
print(prediction)