Classification, detection and segmentation with deep networks

Pretrained networks through torchvision and the OpenCV DNN module — what each output means, and how boxes are cleaned up with IoU and non-maximum suppression.

What you'll learn
  • Preprocess an image for an ImageNet classifier and read its top-5 output
  • Interpret detector outputs (boxes, labels, scores) and compute IoU
  • Explain non-maximum suppression and the difference between semantic and instance segmentation

Everything so far was designed by hand: kernels, corner scores, matching rules. Deep networks learn the features instead. The repository uses pretrained models three ways, each from torchvision and from OpenCV’s DNN module.

Classification

001_classification_using_pretrained_model.ipynb runs AlexNet and ResNet-50 on a photo. The preprocessing must match training exactly:

transform = transforms.Compose([
    transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
batch_t = torch.unsqueeze(transform(img), 0)
out = alexnet(batch_t)                                   # (1, 1000) logits
percentage = torch.nn.functional.softmax(out, dim=1)[0] * 100

The mean and standard deviation are ImageNet’s per-channel statistics. The class names are read with [line.strip() for line in f.readlines] — without the parentheses after readlines, which raises TypeError: 'builtin_function_or_method' object is not iterable; it should be f.readlines().

14_app_02.py does the same with a Caffe DenseNet-121 through cv2.dnn.readNet and cv2.dnn.blobFromImage(image, scalefactor, size, mean), then applies softmax to the 1000 outputs itself.

Detection

A detector returns, for each object, a box, a class and a score. The notebook uses Faster R-CNN (fasterrcnn_resnet50_fpn) and keeps the predictions above a score threshold:

pred_score = list(pred[0]['scores'].detach().numpy())
pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1]
pred_boxes = pred_boxes[:pred_t + 1]

This relies on torchvision returning scores sorted from high to low, which it does. But if no score exceeds the threshold, the list is empty and [-1] raises an IndexError; pred_t = sum(s > threshold for s in pred_score) - 1 handles that case and returns nothing.

14_app_03.py runs SSD-MobileNet v2 through OpenCV. Its output has shape (1, 1, 100, 7), one row per detection: [image_id, class_id, confidence, x_min, y_min, x_max, y_max], coordinates as fractions of the image size. The comment in the script calls the last two values “width and height” and names the variables accordingly, but they are the bottom-right corner — which is why passing them straight to cv2.rectangle as the second corner draws correct boxes.

Overlap: IoU and non-maximum suppression

Detectors fire many times around each object. The standard measure of overlap is intersection over union,

\[\mathrm{IoU}(A, B) = \frac{\vert A \cap B\vert}{\vert A \cup B\vert},\]

1 for identical boxes and 0 for disjoint ones. Non-maximum suppression keeps the highest-scoring box, deletes every box overlapping it by more than a threshold, and repeats with what is left:

Eight raw detections of two cars and a cyclist. Each round keeps the best remaining box and drops those with IoU above the threshold. At 0.5 three boxes survive; raise the threshold to 0.7 and duplicates start to survive (five boxes).

Faster R-CNN and SSD both run NMS internally; it matters when combining detectors, tiling a large image, or writing a detector head yourself (torchvision.ops.nms(boxes, scores, 0.5) does it in one call).

Segmentation

Semantic segmentation labels every pixel with a class. In 001_semantic_segmentation.ipynb, FCN-ResNet101 and DeepLabv3 return a tensor of shape (1, 21, H, W) — one score map per Pascal VOC class — and torch.argmax(out.squeeze(), dim=0) picks each pixel’s class; decode_segmap colours the result.

Instance segmentation separates objects of the same class. Mask R-CNN (002_instance_segmentation.ipynb) adds a mask branch to Faster R-CNN: each detection carries a soft mask, thresholded at 0.5, so two people get two separate masks. The same empty-list [-1] pattern as above appears in its get_prediction.

These notebooks were not re-run for this page: they need PyTorch, pretrained weights of several hundred megabytes, and images from Google Drive. The code was reviewed against the torchvision and OpenCV documentation.

Try it yourself. Write iou(a, b) for boxes in (x1, y1, x2, y2) form and check it against torchvision.ops.box_iou. Then implement NMS in ten lines and compare with torchvision.ops.nms on the detections of any image, at thresholds 0.3, 0.5 and 0.7.

View source on GitHub →