For this tutorial, we will be finetuning a pre-trained Mask
R-CNN model on the Penn-Fudan
Database for Pedestrian Detection and
Segmentation. It contains
170 images with 345 instances of pedestrians, and we will use it to
illustrate how to use the new features in torchvision in order to train
an object detection and instance segmentation model on a custom dataset.
Note
This tutorial works only with torchvision version >=0.16 or nightly.
If you’re using torchvision<=0.15, please follow
this tutorial instead.
Defining the Dataset
The reference scripts for training object detection, instance
segmentation and person keypoint detection allows for easily supporting
adding new custom datasets. The dataset should inherit from the standard
torch.utils.data.Dataset class, and implement __len__ and
__getitem__.
The only specificity that we require is that the dataset __getitem__
should return a tuple:
boxes, torchvision.tv_tensors.BoundingBoxes of shape [N,4]:
the coordinates of the N bounding boxes in [x0,y0,x1,y1] format, ranging from 0
to W and 0 to H
, integer of shape : the label for each bounding box.
represents always the background class.
If your dataset is compliant with above requirements then it will work for both
training and evaluation codes from the reference script. Evaluation code will use scripts from
pycocotools which can be installed with pipinstallpycocotools.
One note on the labels. The model considers class 0 as background. If your dataset does not contain the background class,
you should not have 0 in your labels. For example, assuming you have just two classes, cat and dog, you can
define 1 (not 0) to represent cats and 2 to represent dogs. So, for instance, if one of the images has both
classes, your labels tensor should look like [1,2].
Additionally, if you want to use aspect ratio grouping during training
(so that each batch only contains images with similar aspect ratios),
then it is recommended to also implement a get_height_and_width
method, which returns the height and the width of the image. If this
method is not provided, we query all elements of the dataset via
__getitem__ , which loads the image in memory and is slower than if
a custom method is provided.
Writing a custom dataset for PennFudan
Let’s write a dataset for the PennFudan dataset. First, let’s download the dataset and
extract the zip file:
In this tutorial, we will be using Mask
R-CNN, which is based on top of
Faster R-CNN. Faster R-CNN is a
model that predicts both bounding boxes and class scores for potential
objects in the image.
Mask R-CNN adds an extra branch
into Faster R-CNN, which also predicts segmentation masks for each
instance.
There are two common
situations where one might want
to modify one of the available models in TorchVision Model Zoo. The first
is when we want to start from a pre-trained model, and just finetune the
last layer. The other is when we want to replace the backbone of the
model with a different one (for faster predictions, for example).
Let’s go see how we would do one or another in the following sections.
1 - Finetuning from a pretrained model
Let’s suppose that you want to start from a model pre-trained on COCO
and want to finetune it for your particular classes. Here is a possible
way of doing it:
importtorchvisionfromtorchvision.models.detection.faster_rcnnimportFastRCNNPredictor# load a model pre-trained on COCOmodel=torchvision.models.detection.fasterrcnn_resnet50_fpn(weights="DEFAULT")# replace the classifier with a new one, that has# num_classes which is user-definednum_classes=2# 1 class (person) + background# get number of input features for the classifierin_features=model.roi_heads.box_predictor.cls_score.in_features# replace the pre-trained head with a new onemodel.roi_heads.box_predictor=FastRCNNPredictor(in_features,num_classes)
2 - Modifying the model to add a different backbone
importtorchvisionfromtorchvision.models.detectionimportFasterRCNNfromtorchvision.models.detection.rpnimportAnchorGenerator# load a pre-trained model for classification and return# only the featuresbackbone=
Object detection and instance segmentation model for PennFudan Dataset
In our case, we want to finetune from a pre-trained model, given that
our dataset is very small, so we will be following approach number 1.
Here we want to also compute the instance segmentation masks, so we will
be using Mask R-CNN:
In references/detection/, we have a number of helper functions to
simplify training and evaluating detection models. Here, we will use
references/detection/engine.py and references/detection/utils.py.
Just download everything under references/detection to your folder and use them here.
On Linux if you have wget, you can download them using below commands:
We want to be able to train our model on an accelerator
such as CUDA, MPS, MTIA, or XPU. Let’s now write the main function which performs the training and the validation:
<matplotlib.image.AxesImage object at 0x7f12c58bf650>
The results look good!
Wrapping up
In this tutorial, you have learned how to create your own training
pipeline for object detection models on a custom dataset. For
that, you wrote a torch.utils.data.Dataset class that returns the
images and the ground truth boxes and segmentation masks. You also
leveraged a Mask R-CNN model pre-trained on COCO train2017 in order to
perform transfer learning on this new dataset.
For a more complete example, which includes multi-machine / multi-GPU
training, check references/detection/train.py, which is present in
the torchvision repository.
Total running time of the script: (0 minutes 51.827 seconds)
image_id, int: an image identifier. It should be
unique between all the images in the dataset, and is used during
evaluation
area, float torch.Tensor of shape [N]: the area of the bounding box. This is used
during evaluation with the COCO metric, to separate the metric
scores between small, medium and large boxes.
iscrowd, uint8 torch.Tensor of shape [N]: instances with iscrowd=True will be
ignored during evaluation.
(optionally) masks, torchvision.tv_tensors.Mask of shape [N,H,W]: the segmentation
masks for each one of the objects
importosimporttorchfromtorchvision.ioimportread_imagefromtorchvision.ops.boxesimportmasks_to_boxesfromtorchvisionimporttv_tensorsfromtorchvision.transforms.v2importfunctionalasFclassPennFudanDataset(torch.utils.data.Dataset):def__init__(self,root,transforms):self.root=rootself.transforms=transforms# load all image files, sorting them to# ensure that they are alignedself.imgs=list(sorted(os.listdir(os.path.join(root,"PNGImages"))))self.masks=list(sorted(os.listdir(os.path.join(root,"PedMasks"))))def__getitem__(self,idx):# load images and masksimg_path=os.path.join(self.root,"PNGImages",self.imgs[idx])mask_path=os.path.join(self.root,"PedMasks",self.masks[idx])img=read_image(img_path)mask=read_image(mask_path)# instances are encoded as different colorsobj_ids=torch.unique(mask)# first id is the background, so remove itobj_ids=obj_ids[1:]num_objs=len(obj_ids)# split the color-encoded mask into a set# of binary masksmasks=(mask==obj_ids[:,None,None]).to(dtype=torch.uint8)# get bounding box coordinates for each maskboxes=masks_to_boxes(masks)# there is only one classlabels=torch.ones((num_objs,),dtype=torch.int64)image_id=idxarea=(boxes[:,3]-boxes[:,1])*(boxes[:,2]-boxes[:,0])# suppose all instances are not crowdiscrowd=torch.zeros((num_objs,),dtype=torch.int64)# Wrap sample and targets into torchvision tv_tensors:img=tv_tensors.Image(img)target={}target["boxes"]=tv_tensors.BoundingBoxes(boxes,format="XYXY",canvas_size=F.get_size(img))target["masks"]=tv_tensors.Mask(masks)target["labels"]=labelstarget["image_id"]=image_idtarget["area"]=areatarget["iscrowd"]=iscrowdifself.transformsisnotNone:img,target=self.transforms(img,target)returnimg,targetdef__len__(self):returnlen(self.imgs)
That’s all for the dataset. Now let’s define a model that can perform
predictions on this dataset.
torchvision
.
models
.
mobilenet_v2
(
weights
=
"DEFAULT"
)
.
features
# ``FasterRCNN`` needs to know the number of
# output channels in a backbone. For mobilenet_v2, it's 1280
/__w/tutorials/tutorials/pytorch/tutorials/intermediate_source/engine.py:30:FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated.Please use `torch.amp.autocast('cuda', args...)` instead.
with torch.cuda.amp.autocast(enabled=scaler isnotNone):