Converting batches to the required input of object detection models.
/home/user/jupyter/env/lib/python3.7/site-packages/torch/cuda/__init__.py:52: UserWarning: CUDA initialization: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx (Triggered internally at  /pytorch/c10/cuda/CUDAFunctions.cpp:100.)
  return torch._C._cuda_getDeviceCount() > 0

class ObjDetAdapter[source]

ObjDetAdapter(pad_idx=0) :: Callback

Callback to convert batches from fastai's dataloader to the expected input of object detection and instance segmentation models

from fastai_object_detection.dataloaders import ObjectDetectionDataLoaders
from fastai_object_detection.datasets import CocoData
from fastai.vision.all import *

path,df = CocoData.get_path_df("ds-cats-dogs")
dls = ObjectDetectionDataLoaders.from_df(df, bs=9, item_tfms=[Resize(600)])
b = dls.one_batch()
dls.show_batch(b, figsize=(10,10))
[(t.shape, type(t)) for t in b]
[(torch.Size([9, 3, 600, 600]), fastai.torch_core.TensorImage),
 (torch.Size([9, 2, 600, 600]), fastai.torch_core.TensorMask),
 (torch.Size([9, 2, 4]), fastai.vision.core.TensorBBox),
 (torch.Size([9, 2]), fastai.torch_core.TensorMultiCategory)]
adapter = ObjDetAdapter()
xb,yb = adapter.transform_batch(b[0], *b[1:])
num_objs = [t.item() for t in b[1].sum((-2,-1)).gt(0).sum(1)]
num_objs
[2, 1, 1, 1, 1, 2, 1, 1, 1]
for i,d in enumerate(yb[0]):
    n1 = len(d["labels"])
    n2,_ = d["boxes"].shape
    n3,_,_ = d["masks"].shape
    test_eq(n1,n2)
    test_eq(n2,n3)
    test_eq(n3,num_objs[i])
    
    bbs = d["boxes"]
    area = (bbs[:,2]-bbs[:,0])*(bbs[:,3]-bbs[:,1])
    test_eq((area<=0).any(), False)
    
for i,b in enumerate(dls.train):
    xb,yb = adapter.transform_batch(b[0], *b[1:])
    num_objs = [t.item() for t in b[1].sum((-2,-1)).gt(0).sum(1)]
    for i,d in enumerate(yb[0]):
        n1 = len(d["labels"])
        n2,_ = d["boxes"].shape
        n3,_,_ = d["masks"].shape
        test_eq(n1,n2)
        test_eq(n2,n3)
        test_eq(n1,num_objs[i])
        bbs = d["boxes"]
        area = (bbs[:,2]-bbs[:,0])*(bbs[:,3]-bbs[:,1])
        test_eq((area<=0).any(), False)