Module contents
Lesson 20 of 25Advanced 105 min

Instance and panoptic segmentation: Mask R-CNN and mask classification

Study instance and panoptic segmentation, Mask R-CNN, panoptic quality and mask classification, with controlled practical comparisons.

After this lesson you can

  • Distinguish semantic, instance and panoptic segmentation.
  • Explain and implement a class-specific Mask R-CNN mask head.
  • Calculate panoptic quality and explain its matching and evaluation rules.
  • Compare mask classification and panoptic post-processing.
  • Evaluate instance masks and interpret qualitative comparisons under their protocols.

Before you start

From categories to individual objects

A semantic mask can label two adjacent people as “person” without separating them. To count them or grasp a particular object, instance segmentation also needs an identity for each object. Its masks can overlap. Panoptic segmentation combines countable classes, or things, with amorphous regions, or stuff, and produces a partition of the evaluated pixels; some pixels may lack a valid label.

InteractiveOne scene, three segmentations

This urban scene is an artificial 80 × 48 pixel geometric grid, not a photograph or network prediction. Every view starts from the same explicit partition.

  • Sky
  • Building
  • Road
  • Sidewalk
  • Tree
  • Car
  • Person

At (16, 32): class Car; instance 1. Position is measured from the top-left corner.

In semantic segmentation all pixels of a category share a label, even when two cars are distinct. In instance segmentation only masks of individual things are colored; faded regions have no instance mask. In panoptic segmentation each pixel has a class and things also have an identity; no pair of segments shares pixels.

Here car and person are things; sky, building, road, sidewalk and tree are stuff. The distinction depends on the dataset taxonomy. Scene rectangles and disks are rasterized in a fixed order: where they overlap, the last determines the visible label. Void and crowd regions are not modeled.

Segmentation view
16
32
Pixel (x, y)(16, 32)
SemanticCar
InstancesCar 1
PanopticCar 1 · thing
Compare categories, identities and panoptic segments in the same explicit geometric scene.

One architecture can produce outputs for all three tasks, but that does not imply the same post-processing or metric. In particular, overlaps must be resolved for the final panoptic partition even if the queries’ internal masks overlap.

Taxonomy depends on the dataset. COCO panoptic distinguishes 80 object categories and 53 amorphous-region categories; MaskFormer describes this split. Panoptic FPN also studies Cityscapes, with urban scenes and 19 evaluation categories, 8 with instance masks. A class or pixel ignored in one protocol does not automatically become background in another: compare only metrics calculated with the same category mapping and evaluation rules.

One mask for each region

Mask R-CNN adds a fully convolutional branch to Faster R-CNN that predicts fixed-size masks for each RoI. The classification branch determines the instance class; during training a per-pixel binary loss is used on the ground-truth class’s mask channel, with independent sigmoids. Mask channels are not required to compete via softmax: the aim is to delineate the object of the selected class, while classification is learned in another branch.

Targets are cropped and sampled in the region with a geometric convention consistent with RoIAlign. If interpolation produces fractional values, binary cross-entropy can accept targets between zero and one. The predicted mask is rescaled and placed in the box: a box that cuts off part of the object limits the region where the mask can appear.

For a positive RoI of ground-truth class kk, with logits zk,u,vz_{k,u,v} and cropped target yu,v∈[0,1]y_{u,v}\in[0,1], mask loss averages BCE over the m2m^2 pixels of channel kk:

Lmask=−1m2∑u,v[yu,vlog⁡σ(zk,u,v)+(1−yu,v)log⁡(1−σ(zk,u,v))].L_{\mathrm{mask}}=-\frac{1}{m^2}\sum_{u,v}\bigl[y_{u,v}\log\sigma(z_{k,u,v})+(1-y_{u,v})\log(1-\sigma(z_{k,u,v}))\bigr].

The other channels are not supervised as negatives for that RoI. The class branch does discriminate categories; separating both decisions lets the mask branch learn shape for the assigned class without requiring per-pixel competition between channels. Code uses stable BCE with logits to avoid calculating logarithms of probabilities rounded to zero or one.

In Table 2b of Mask R-CNN, with ResNet-50-C4 and COCO minival, the multinomial softmax variant achieved 24.8 mask AP versus 30.3 for decoupled sigmoids. That is 5.5 points for those configurations, not a promise of improvement on every task.

InteractiveThe 28×28 mask

The silhouette is an artificial geometric model of 112 × 112 pixels. These are not outputs of networks trained at 14, 28 or 56: all three grids are calculated from this same reference.

1. Reference

2. Coverage per cell: 14 × 14

3. Comparison after reconstruction

  • Correct object
  • False positive
  • False negative

Each cell stores the exact fraction of positive reference pixels it contains. A stronger shade indicates greater coverage. After upsampling to 112 × 112, a pixel belongs to the mask if its value is at least 0.50. IoU = intersection / (intersection + false positives + false negatives).

Reference blocks are averaged without overlap. Nearest neighbor replicates each cell value; bilinear interpolates between cell centers and replicates the edge. All errors are counted on the original grid. This illustrates detail loss and resampling, but coverage comes from the true mask and does not measure a learned model’s error or quality.

Grid resolution
Reconstruction
0.50
IoU0.7316
Intersection2072
False positives488
False negatives272

Now observe the region sampling. A synthetic 6 × 6 map feeds two operators with 2 × 2 output. The same bin is highlighted in both. RoIAlign averages four bilinear samples; RoIPool takes the maximum of the highlighted cells.

RoIAlign, aligned=True357681076810911810911131291113121416131214161517141615171918
  • RoI shifted −0.5
  • Bin
  • Bilinear samples

Four samples (x, y): (0.95, 1.02); (1.55, 1.02); (0.95, 1.67); (1.55, 1.67). Their values are interpolated and averaged.

RoIPool357681076810911810911131291113121416131214161517141615171918
  • Bin cells

Cells (x, y): (1, 1); (2, 1); (1, 2); (2, 2). The value is their maximum.

Outputs in row-major order: RoIAlign [7.660, 9.250, 10.861, 11.622]; RoIPool [10.000, 13.000, 14.000, 16.000]. Original RoI in the image: (18.40, 19.20, 56.80, 60.80) pixels, xyxy format.

The value at column x and row y of the map is (x + 1) + 2(y + 1) + ((x + 2y) mod 3), with x and y from 0 to 5. The RoI in map coordinates is (1.15, 1.20, 3.55, 3.80); to place it in the image, coordinates are multiplied by stride. This example does not measure a network or a real image.

RoIAlign subtracts 0.5 from all four map coordinates, as in torchvision aligned=True, and uses two samples per axis in each bin. RoIPool rounds both ends to the nearest integer, treats them as inclusive and uses floor/ceil for each bin; bins may share cells. Displayed shifts are (rounded endpoint − original endpoint) × stride, only for RoIPool’s initial corner; they do not measure error across the whole operator.

Outputs also differ because here RoIPool uses a maximum and RoIAlign averages. Do not attribute the entire numerical difference to rounding. The half-pixel adjustment defines a coordinate convention and does not by itself imply a fault in every implementation.

1.15
1.20
Stride, pixels per map unit
0
Bin, zero-based row and column0, 0
RoIAlign, bilinear average7.660
RoIPool, maximum10.000
Initial corner x rounding−2.40 px
Initial corner y rounding−3.20 px
Explore sampling a geometric silhouette and compare RoIPool with RoIAlign under the figure's explicit conventions.

Mask AP uses IoU between masks, scores and the chosen matching protocol. It is not box AP and is not necessarily always lower: a comparison must identify IoU type and dataset. For binary masks, RLE stores run lengths. COCO traverses by columns and the uncompressed list starts with the run of zeros, which can have zero length. The compressed pycocotools format additionally encodes those lengths; a list of integers is not automatically its compressed representation. COCO crowd regions require additional rules.

A mask requires getting the silhouette right, not just its bounding rectangle: two predictions with the same box can have different mask IoUs. That geometric requirement does not numerically order the two AP values, since intersections and unions with their respective targets change.

Panoptic quality and its denominator

Panoptic segmentation evaluates segments of the same category and requires IoU strictly greater than 0.5 to match them. If masks are disjoint within each partition, this rule makes matching unique: for a ground-truth segment gg and two disjoint predictions p1,p2p_1,p_2,

IoU⁡(p1,g)+IoU⁡(p2,g)≤∣p1∩g∣+∣p2∩g∣∣g∣≤1.\operatorname{IoU}(p_1,g)+\operatorname{IoU}(p_2,g)\le\frac{|p_1\cap g|+|p_2\cap g|}{|g|}\le1.

Therefore both IoUs cannot exceed 0.5. Swapping roles proves uniqueness in the other direction. The strict inequality matters: two disjoint halves of an object can each have IoU exactly 0.5. Under these assumptions there is no need to solve a Hungarian assignment to decide the pairs.

For each category accumulate true positives TPTP, false positives FPFP, false negatives FNFN and the sum of matched-pair IoUs. Then

PQ=∑(p,g)IoU⁡(p,g)TP+12FP+12FN,RQ=TPTP+12FP+12FN,SQ=∑IoU⁡TP.PQ=\frac{\sum_{(p,g)}\operatorname{IoU}(p,g)}{TP+\frac12FP+\frac12FN},\quad RQ=\frac{TP}{TP+\frac12FP+\frac12FN},\quad SQ=\frac{\sum\operatorname{IoU}}{TP}.

If TP>0TP>0, PQ=SQ⋅RQPQ=SQ\cdot RQ for that category. If TP=0TP=0 with errors, PQ and RQ are zero and SQ is mathematically undefined; the official evaluator records zero by convention. A category with no TP, FP or FN is excluded from the mean. The product of macro-averaged SQ and RQ need not equal macro-averaged PQ.

InteractiveCalculate panoptic quality

The two 64 × 40 grids are artificial geometric partitions. Each segment has an identifier. P1 moves pixel by pixel; the remaining rectangles stay fixed.

Reference

ABCT

Prediction: move P1

P1P2P3P4
  • Person A / P1
  • Person B / P2
  • Person C / P3
  • Tree T / P4

A versus P1: intersection 48, union 48, IoU 1.000. It exceeds the strict 0.5 threshold. Try horizontal shift 2 and vertical 0 to reach exactly 0.5.

Person matches: A ↔ P1 (IoU 1.000, 48/48); B ↔ P2 (IoU 0.714, 40/56). Unmatched predictions: P3. Unmatched references: C.

Only segments of the same category with IoU > 0.5 are matched. SQ = sum of IoU / TP; RQ = TP / (TP + FP/2 + FN/2); PQ = sum of IoU / (TP + FP/2 + FN/2). Without TP, SQ is undefined. If there are errors but no matches, PQ and RQ are zero.

If predictions overlap, the pixel belongs to the first in order P1, P2, P3, P4; segments with no pixels disappear from the count. The rest is a background category excluded from these metrics. Void and crowd regions, which require additional treatment in full evaluation, are not represented.

Evaluated category
0
0
TP2
FP1
FN1
SQ0.857
RQ0.667
PQ0.571
Move segments in an explicit geometric partition and observe matches and components by category.

Void pixels and crowds require care. The official panoptic evaluator subtracts the part of a prediction that falls in void from the union and does not match crowd GT. For an unmatched prediction, it adds intersections with void and same-class crowd; it ignores the prediction if that sum exceeds half its area. The threshold is strictly greater than 0.5. A teaching implementation without these cases does not reproduce the full protocol; state its limits. Also report things and stuff PQ separately so an average does not hide failures in one family.

Classifying masks

Panoptic FPN combines semantic and instance branches on a shared pyramid. On COCO test-dev, its Table 4(a) reports 40.9 overall PQ, 48.3 for things and 29.7 for stuff for the specified ResNet-101 configuration. These are not results measured by this lesson’s lab.

MaskFormer predicts a set of class-and-mask pairs, with a no-object class, and uses bipartite assignment during training. Semantic output can combine class probabilities and masks; panoptic output must also resolve conflicts and filter candidates. The learned mask and class are not necessarily an independent label for every pixel.

For example, if query ii assigns probability pi(c)p_i(c) to class cc and mask value mi(x)m_i(x) to pixel xx, a semantic rule in the paper selects the class maximizing ∑ipi(c)mi(x)\sum_i p_i(c)m_i(x). This sum is a score for deciding the class, not necessarily a normalized distribution over classes. In panoptic output each pixel is assigned to an eligible query, unreliable predictions are removed and same-class amorphous regions are merged according to post-processing; this yields a partition even if query masks overlap.

Mask2Former restricts a query’s cross-attention using its mask, resized to the feature level: it allows positions inside and blocks those outside with an additive bias. If a row blocked every position, softmax of all negative-infinity logits would be undefined; the official implementation opens that row. The internal attention mask is not the final panoptic partition.

In Mask2Former’s Table 1, on COCO panoptic val2017 with ResNet-50, MaskFormer achieved 46.5 PQ versus 51.9 for Mask2Former in the published configurations; training and features also change, so this is not an isolated intervention on attention. Promptable segmentation changes the interface: a point or phrase specifies the desired region, as studied later.

Labs

RLE, AP and PQ from scratch

The cell implements uncompressed column-wise RLE and mask IoU. AP adapts the detection lesson’s logic to masks, with ten thresholds and 101 levels, but limits that part to full area without iscrowd or ignored items. It preserves the supplied image order when resolving score ties between images; use sorted identifiers to reproduce the previous lesson’s order. The PQ implementation supports void and up to one crowd region per category and image; its tests check specific rules and edge cases. Keep these restrictions visible when comparing against official evaluators.

[ ]RLE, mask AP and PQBrowser
"""IoU/RLE, AP de máscaras y PQ sobre ejemplos mínimos: solo NumPy.

RLE no comprimido: recorrido por columnas, primer bloque de ceros. AP:
101 niveles de recall, IoU .50:.05:.95, áreas all y maxDet por imagen y
categoría; NO implementa ignore, crowd ni rangos de área para AP. PQ admite
void=0 y como máximo un segmento crowd por categoría e imagen, coherente
con la hipótesis del evaluador panopticapi; clases agregadas antes de media.
"""
import numpy as np


def rle_encode(mask):
    mask = np.asarray(mask)
    if mask.ndim != 2 or not np.isin(mask, (0, 1)).all():
        raise ValueError('Máscara binaria de dos dimensiones')
    flat = mask.astype(np.uint8).ravel(order='F')
    counts, bit, run = [], 0, 0
    for value in flat:
        if int(value) == bit:
            run += 1
        else:
            counts.append(run)
            run, bit = 1, int(value)
    counts.append(run)
    return {'size': tuple(mask.shape), 'counts': counts}


def rle_decode(rle):
    h, w = rle['size']
    counts = rle['counts']
    if h < 0 or w < 0 or any(not isinstance(n, (int, np.integer)) or n < 0 for n in counts) or sum(counts) != h*w:
        raise ValueError('RLE inválido')
    if not counts:
        raise ValueError('El RLE requiere al menos un bloque')
    flat = np.repeat(np.arange(len(counts)) % 2, counts).astype(np.uint8)
    return flat.reshape((h, w), order='F')


def rle_iou(a, b):
    """Intersección y unión con bloques, sin descomprimir las máscaras."""
    if tuple(a['size']) != tuple(b['size']):
        raise ValueError('Tamaños diferentes')
    # También comprueba bloques y longitud total sin reservar máscaras.
    for rle in (a, b):
        h, w = rle['size']
        if h < 0 or w < 0 or not rle['counts'] or any(not isinstance(n, (int, np.integer)) or n < 0 for n in rle['counts']) or sum(rle['counts']) != h*w:
            raise ValueError('RLE inválido')
    ac, bc = a['counts'], b['counts']
    ia = ib = 0
    ra, rb = ac[0], bc[0]
    inter = union = 0
    while ia < len(ac) and ib < len(bc):
        if ra == 0:
            ia += 1
            if ia < len(ac): ra = ac[ia]
            continue
        if rb == 0:
            ib += 1
            if ib < len(bc): rb = bc[ib]
            continue
        take = min(ra, rb)
        if ia % 2 and ib % 2: inter += take
        if ia % 2 or ib % 2: union += take
        ra -= take
        rb -= take
    return inter / union if union else np.nan


def mask_ap(predictions, targets, thresholds=None, max_dets=100):
    """Adaptación de la AP all de m16-l16 a máscaras: sin crowd ni ignore.

    Una imagen es una lista de detecciones {class, score, rle} y de GT
    {class, rle}. Se ordena estable por confianza por imagen y categoría,
    y después se agregan imágenes en el orden de entrada. Matching ávido
    con GT de mayor IoU no usado, umbral inclusivo. Devuelve AP por umbral.
    """
    if len(predictions) != len(targets) or max_dets <= 0:
        raise ValueError('Imágenes incompatibles o max_dets inválido')
    if thresholds is None:
        thresholds = np.linspace(.5, .95, 10)
    thresholds = np.asarray(thresholds, dtype=float)
    if thresholds.ndim != 1 or not len(thresholds) or np.any(~np.isfinite(thresholds)) or np.any((thresholds < 0) | (thresholds > 1)):
        raise ValueError('Umbrales inválidos')
    categories = sorted({item['class'] for image in targets for item in image})
    result = []
    for threshold in thresholds:
        per_class = []
        for category in categories:
            events, count = [], 0
            for detections, ground_truth in zip(predictions, targets):
                gt = [g for g in ground_truth if g['class'] == category]
                count += len(gt)
                dt = [d for d in detections if d['class'] == category]
                if any(not np.isfinite(d['score']) for d in dt):
                    raise ValueError('Confianza no finita')
                dt = sorted(dt, key=lambda d: -d['score'])[:max_dets]
                used = set()
                for d in dt:
                    best, best_iou = None, float(threshold)
                    for j, g in enumerate(gt):
                        if j in used: continue
                        overlap = rle_iou(d['rle'], g['rle'])
                        if np.isfinite(overlap) and overlap >= best_iou:
                            best, best_iou = j, overlap
                    if best is not None: used.add(best)
                    events.append((float(d['score']), int(best is not None)))
            events.sort(key=lambda event: -event[0])
            if not events:
                per_class.append(0.)
                continue
            tp = np.cumsum([event[1] for event in events])
            fp = np.cumsum([1-event[1] for event in events])
            recall = tp / count
            precision = tp / (tp + fp)
            envelope = np.maximum.accumulate(precision[::-1])[::-1]
            indices = np.searchsorted(recall, np.linspace(0, 1, 101), side='left')
            values = np.zeros(101)
            valid = indices < len(envelope)
            values[valid] = envelope[indices[valid]]
            per_class.append(float(values.mean()))
        result.append(float(np.mean(per_class)) if per_class else np.nan)
    return {'classes':categories, 'thresholds':thresholds, 'ap':np.asarray(result),
            'map':float(np.mean(result)) if categories else np.nan}


def panoptic_quality(images, categories):
    """PQ por dataset con IDs 2D disjuntos, void y hasta un crowd por clase.

    Cada imagen es (gt_map, pred_map, gt_info, pred_info). Cada info mapea
    ID no nulo a {'class': categoría, 'crowd': bool}; pred_info no usa crowd.
    El área se calcula del mapa, no se acepta área externa desactualizada.
    Se devuelven detalles por clase y medias macro de clases activas.
    """
    cats = list(categories)
    if len(set(cats)) != len(cats): raise ValueError('Categorías repetidas')
    stats = {c:{'tp':0, 'fp':0, 'fn':0, 'iou':0.} for c in cats}
    for gt_map, pred_map, gt_info, pred_info in images:
        gt_map, pred_map = np.asarray(gt_map), np.asarray(pred_map)
        if gt_map.ndim != 2 or gt_map.shape != pred_map.shape:
            raise ValueError('Mapas 2D de igual tamaño')
        if gt_map.dtype.kind not in 'iu' or pred_map.dtype.kind not in 'iu' or np.any(gt_map < 0) or np.any(pred_map < 0):
            raise ValueError('IDs enteros no negativos')
        for ids, info in ((gt_map,gt_info),(pred_map,pred_info)):
            if set(np.unique(ids)) - {0} != set(info) or 0 in info:
                raise ValueError('IDs del mapa y de las anotaciones no coinciden')
            if any(segment['class'] not in stats for segment in info.values()):
                raise ValueError('Categoría desconocida')
        crowd = {}
        for gid, g in gt_info.items():
            if g.get('crowd',False):
                if g['class'] in crowd: raise ValueError('Más de un crowd por clase')
                crowd[g['class']] = gid
        matched_gt, matched_pred = set(), set()
        for gid, g in gt_info.items():
            if g.get('crowd',False): continue
            gm = gt_map == gid
            ga = int(gm.sum())
            for pid, p in pred_info.items():
                if p['class'] != g['class']: continue
                pm = pred_map == pid
                inter = int((gm & pm).sum())
                if not inter: continue
                union = int(pm.sum()) + ga - inter - int((pm & (gt_map == 0)).sum())
                value = inter / union
                if value > .5:
                    if gid in matched_gt or pid in matched_pred:
                        raise AssertionError('La partición debería producir matching único')
                    matched_gt.add(gid); matched_pred.add(pid)
                    stats[g['class']]['tp'] += 1
                    stats[g['class']]['iou'] += value
        for gid, g in gt_info.items():
            if not g.get('crowd',False) and gid not in matched_gt:
                stats[g['class']]['fn'] += 1
        for pid, p in pred_info.items():
            if pid in matched_pred: continue
            pm = pred_map == pid
            ignored = int((pm & (gt_map == 0)).sum())
            if p['class'] in crowd:
                ignored += int((pm & (gt_map == crowd[p['class']])).sum())
            if ignored / int(pm.sum()) <= .5:
                stats[p['class']]['fp'] += 1
    active = []
    for s in stats.values():
        tp, fp, fn = s['tp'], s['fp'], s['fn']
        if tp + fp + fn == 0:
            s.update(pq=None, sq=None, rq=None)
            continue
        denominator = tp + (fp + fn) / 2
        s.update(pq=s['iou']/denominator, sq=s['iou']/tp if tp else 0., rq=tp/denominator)
        active.append(s)
    means = {metric:float(np.mean([s[metric] for s in active])) if active else None for metric in ('pq','sq','rq')}
    return {'per_class':stats, 'macro':means, 'active_classes':len(active)}


def main():
    a = np.array([[1,0,0],[1,1,0]], dtype=np.uint8)
    b = np.array([[1,0,1],[0,1,0]], dtype=np.uint8)
    ra, rb = rle_encode(a), rle_encode(b)
    assert ra['counts'] == [0,2,1,1,2] and np.array_equal(rle_decode(ra),a)
    assert np.isclose(rle_iou(ra,rb),2/4)
    zero = rle_encode(np.zeros((2,3),dtype=np.uint8))
    assert np.isnan(rle_iou(zero,zero))
    gt = [[{'class':1,'rle':ra}]]
    duplicate = [[{'class':1,'score':.9,'rle':ra},{'class':1,'score':.8,'rle':ra}]]
    false_first = [[{'class':1,'score':.9,'rle':zero},{'class':1,'score':.8,'rle':ra}]]
    assert mask_ap(duplicate,gt)['map'] == 1.
    assert mask_ap(false_first,gt)['map'] == .5
    tied = [[{'class':1,'score':.5,'rle':zero},{'class':1,'score':.5,'rle':ra}]]
    assert mask_ap(tied,gt)['map'] == .5
    one_detection = [[{'class':1,'score':.9,'rle':rb}]]
    np.testing.assert_allclose(mask_ap(one_detection,gt,thresholds=[.5,.5001])['ap'],[1.,0.])
    two_gt = [[{'class':1,'rle':ra},{'class':1,'rle':rb}]]
    assert np.isclose(mask_ap(duplicate[:1],two_gt,thresholds=[.5],max_dets=1)['map'],51/101)
    assert np.isnan(mask_ap([[]],[[]])['map'])

    # Un TP con IoU 2/3 y un FN. El segmento 2 predicho cubre solo void.
    gm = np.array([[1,1,1,0],[2,2,0,0]])
    pm = np.array([[1,1,0,2],[0,0,2,2]])
    result = panoptic_quality([(gm,pm,{1:{'class':1},2:{'class':1}},{1:{'class':1},2:{'class':1}})],[1,2])
    stats = result['per_class'][1]
    assert (stats['tp'],stats['fp'],stats['fn']) == (1,0,1)
    assert np.isclose(stats['sq'],2/3) and np.isclose(stats['rq'],2/3) and np.isclose(stats['pq'],4/9)
    assert result['per_class'][2]['pq'] is None
    # Coincidencia exacta .5 no es TP y exactamente mitad void no ignora FP.
    gm2 = np.array([[1,1,0,0]])
    pm2 = np.array([[1,0,1,0]])
    stat2 = panoptic_quality([(gm2,pm2,{1:{'class':1}},{1:{'class':1}})],[1])['per_class'][1]
    assert (stat2['tp'],stat2['fp'],stat2['fn']) == (0,1,1)
    # Un crowd de la misma clase más void suma más de la mitad: se ignora.
    gm3 = np.array([[1,2,0,0]])
    pm3 = np.array([[0,1,1,0]])
    stat3 = panoptic_quality([(gm3,pm3,{1:{'class':1},2:{'class':1,'crowd':True}},{1:{'class':1}})],[1])['per_class'][1]
    assert (stat3['tp'],stat3['fp'],stat3['fn']) == (0,0,1)
    print('RLE por columnas:',ra['counts'],'IoU:',rle_iou(ra,rb))
    print('AP duplicado:',mask_ap(duplicate,gt)['map'],'AP FP primero:',mask_ap(false_first,gt)['map'])
    print('PQ caso con void:',stats)
    print('Bordes IoU=0,5 y void=0,5:',stat2)
    print('Crowd y void:',stat3)


if __name__ == '__main__':
    main()

Fine-tune Mask R-CNN on Penn-Fudan

Before fine-tuning a complete detector, build a minimal head for positive RoIs. Four 3×33\times3 convolutions, a transposed convolution and a projection produce one channel per class. Targets are sampled from the corresponding masks; the loss uses only the ground-truth class channel for each RoI. The following inputs are an explicit synthetic example, not results from real images.

[ ]A decoupled mask headLocal GPU
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.ops import roi_align

torch.manual_seed(1620)
head = nn.Sequential(
    nn.Conv2d(4, 8, 3, padding=1), nn.ReLU(),
    nn.Conv2d(8, 8, 3, padding=1), nn.ReLU(),
    nn.Conv2d(8, 8, 3, padding=1), nn.ReLU(),
    nn.Conv2d(8, 8, 3, padding=1), nn.ReLU(),
    nn.ConvTranspose2d(8, 8, 2, stride=2), nn.ReLU(),
    nn.Conv2d(8, 3, 1),
)
features = torch.randn(2, 4, 14, 14)
gt_masks = torch.zeros(2, 1, 32, 32)
gt_masks[0, 0, 4:24, 3:22] = 1
gt_masks[1, 0, 8:28, 10:30] = 1
rois = torch.tensor([[0., 3., 4., 22., 24.], [1., 10., 8., 30., 28.]])
target = roi_align(gt_masks, rois, (28, 28), spatial_scale=1., sampling_ratio=2, aligned=True)[:, 0]
classes = torch.tensor([1, 2])
logits = head(features)
chosen = logits[torch.arange(len(classes)), classes]
loss = F.binary_cross_entropy_with_logits(chosen, target)
loss.backward()
assert logits.shape == (2, 3, 28, 28) and target.shape == (2, 28, 28)
assert torch.isfinite(loss) and all(p.grad is not None and torch.isfinite(p.grad).all() for p in head.parameters())
print('Forma de logits:', tuple(logits.shape), 'pérdida:', float(loss.detach()))
print('Objetivos entre 0 y 1:', bool(((target >= 0) & (target <= 1)).all()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The local cell splits Penn-Fudan images into training, validation and test, checks hashes and fine-tunes a box head and a mask head. It selects a checkpoint by validation mask AP and evaluates boxes and masks separately on test. Predictions reach the metric after TorchVision’s default score threshold and detection limit: that AP also depends on this filtering. To visualize the scene, it keeps up to 20 predictions with confidence at least 0.05, the detector’s default threshold; each confidence is shown and masks are binarized at 0.5. Some people may appear in several images, so splitting by image does not guarantee separation by identity. Short mode reduces data and steps to verify the pipeline; it is not a representative benchmark.

[ ]Fine-tune Mask R-CNN on Penn-FudanLocal GPU
"""Ajuste de Mask R-CNN en Penn-Fudan; requiere torch, torchvision y torchmetrics[detection].

Fuente de datos y receta: https://docs.pytorch.org/tutorials/intermediate/torchvision_tutorial.html
ORYON_VERIFY_SHORT=1 reduce imágenes y actualizaciones para verificar el recorrido. Los
resultados breves no son un benchmark. ORYON_DATA_DIR y ORYON_OUTPUT_DIR permiten elegir
la caché y los resultados; los pesos oficiales usan la caché de torch.
"""
import hashlib
import json
import os
from pathlib import Path
import random
import shutil
import urllib.request
import zipfile

import numpy as np
from PIL import Image
import torch
import torchvision
from torch.utils.data import DataLoader, Dataset
from torchmetrics.detection.mean_ap import MeanAveragePrecision
from torchvision.models.detection import maskrcnn_resnet50_fpn, MaskRCNN_ResNet50_FPN_Weights
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from torchvision.transforms.functional import pil_to_tensor

SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
ROOT = Path(os.environ.get('ORYON_DATA_DIR', Path.home() / '.cache' / 'oryon' / 'pennfudan'))
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', 'oryon_maskrcnn'))
URL = 'https://www.cis.upenn.edu/~jshi/ped_html/PennFudanPed.zip'
SEED = 16200
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')


def data_dir():
    folder = ROOT / 'PennFudanPed'
    if (folder / 'PNGImages').is_dir() and (folder / 'PedMasks').is_dir():
        return folder
    ROOT.mkdir(parents=True, exist_ok=True)
    archive = ROOT / 'PennFudanPed.zip'
    if not archive.exists():
        temporary = archive.with_suffix('.part')
        try:
            urllib.request.urlretrieve(URL, temporary)
            temporary.replace(archive)
        finally:
            temporary.unlink(missing_ok=True)
    # Evita extraer nombres absolutos o con .. de un archivo manipulado.
    with zipfile.ZipFile(archive) as z:
        for info in z.infolist():
            name = Path(info.filename)
            if name.is_absolute() or '..' in name.parts or ':' in info.filename:
                raise ValueError('Ruta insegura en el archivo ZIP')
        z.extractall(ROOT)
    if not (folder / 'PNGImages').is_dir() or not (folder / 'PedMasks').is_dir():
        raise ValueError('El ZIP no contiene la estructura Penn-Fudan esperada')
    print('SHA256 ZIP:', hashlib.sha256(archive.read_bytes()).hexdigest())
    return folder


def make_splits(folder):
    images = sorted((folder / 'PNGImages').glob('*.png'))
    if len(images) != 170:
        raise ValueError(f'Se esperaban 170 imágenes, aparecen {len(images)}')
    hashes = {}
    for image in images:
        if not (folder / 'PedMasks' / (image.stem + '_mask.png')).exists():
            raise ValueError(f'Falta máscara: {image.name}')
        digest = hashlib.sha256(image.read_bytes()).hexdigest()
        if digest in hashes:
            raise ValueError(f'Imágenes con bytes duplicados: {image.name} y {hashes[digest]}')
        hashes[digest] = image.name
    random.Random(SEED).shuffle(images)
    return images[:120], images[120:145], images[145:]


class Pedestrians(Dataset):
    def __init__(self, folder, paths, augment=False):
        self.folder, self.paths, self.augment = folder, paths, augment

    def __len__(self):
        return len(self.paths)

    def __getitem__(self, index):
        path = self.paths[index]
        image = pil_to_tensor(Image.open(path).convert('RGB')).float() / 255
        mask_path = self.folder / 'PedMasks' / (path.stem + '_mask.png')
        ids = np.asarray(Image.open(mask_path)).copy()
        if ids.ndim != 2 or tuple(ids.shape) != tuple(image.shape[-2:]):
            raise ValueError(f'Máscara incompatible: {mask_path}')
        masks = torch.from_numpy(np.stack([ids == x for x in np.unique(ids) if x != 0]))
        if self.augment and torch.rand(()) < 0.5:
            image, masks = image.flip(-1), masks.flip(-1)
        boxes = []
        for mask in masks:
            yy, xx = torch.where(mask)
            boxes.append([int(xx.min()), int(yy.min()), int(xx.max()) + 1, int(yy.max()) + 1])
        boxes = torch.tensor(boxes, dtype=torch.float32)
        n = len(boxes)
        target = {'boxes': boxes, 'labels': torch.ones(n, dtype=torch.int64),
                  'masks': masks.to(torch.uint8), 'image_id': torch.tensor(index),
                  'area': (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]),
                  'iscrowd': torch.zeros(n, dtype=torch.int64)}
        return image, target


def collate(batch):
    return tuple(map(list, zip(*batch)))


def model_for_person():
    model = maskrcnn_resnet50_fpn(weights=MaskRCNN_ResNet50_FPN_Weights.DEFAULT,
                                  min_size=256 if SHORT else 512,
                                  max_size=384 if SHORT else 768)
    box_features = model.roi_heads.box_predictor.cls_score.in_features
    model.roi_heads.box_predictor = FastRCNNPredictor(box_features, 2)
    mask_features = model.roi_heads.mask_predictor.conv5_mask.in_channels
    model.roi_heads.mask_predictor = MaskRCNNPredictor(mask_features, 256, 2)
    return model.to(DEVICE)


@torch.no_grad()
def evaluate(model, loader):
    model.eval()
    metric = MeanAveragePrecision(iou_type=('bbox', 'segm'))
    for images, targets in loader:
        outputs = model([x.to(DEVICE) for x in images])
        preds = [{'boxes': p['boxes'].cpu(), 'scores': p['scores'].cpu(),
                  'labels': p['labels'].cpu(), 'masks': (p['masks'][:, 0].cpu() >= .5)}
                 for p in outputs]
        truth = [{'boxes': t['boxes'], 'labels': t['labels'], 'masks': t['masks'].bool()}
                 for t in targets]
        metric.update(preds, truth)
    result = metric.compute()
    answer = {key: float(result[key]) for key in ('bbox_map', 'bbox_map_50', 'segm_map', 'segm_map_50')}
    if not all(np.isfinite(x) and 0 <= x <= 1 for x in answer.values()):
        raise ValueError(f'Métricas de evaluación inválidas: {answer}')
    return answer


def run():
    folder = data_dir()
    train, valid, test = make_splits(folder)
    if SHORT:
        train, valid, test = train[:4], valid[:2], test[:2]
    random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED)
    if DEVICE.type == 'cuda':
        torch.cuda.manual_seed_all(SEED)
    train_set = Pedestrians(folder, train, augment=True)
    train_loader = DataLoader(train_set, batch_size=1 if SHORT else 2, shuffle=True,
                              num_workers=0, collate_fn=collate,
                              generator=torch.Generator().manual_seed(SEED + 1))
    val_loader = DataLoader(Pedestrians(folder, valid), batch_size=1, collate_fn=collate)
    test_loader = DataLoader(Pedestrians(folder, test), batch_size=1, collate_fn=collate)
    model = model_for_person()
    optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad],
                                lr=0.001, momentum=0.9, weight_decay=0.0005)
    epochs = 1 if SHORT else 10
    best, best_state, history = -1., None, []
    for epoch in range(epochs):
        model.train()
        losses = []
        for images, targets in train_loader:
            targets = [{k: v.to(DEVICE) for k, v in t.items()} for t in targets]
            loss_parts = model([x.to(DEVICE) for x in images], targets)
            loss = sum(loss_parts.values())
            if not torch.isfinite(loss):
                raise FloatingPointError(f'Pérdida no finita: {loss_parts}')
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
                raise FloatingPointError('Gradiente no finito; no se aplica la actualización')
            optimizer.step()
            losses.append(float(loss.detach().cpu()))
        val = evaluate(model, val_loader)
        history.append({'epoch': epoch + 1, 'loss': float(np.mean(losses)), 'validation': val})
        print('Época', epoch + 1, 'pérdida', round(history[-1]['loss'], 4), 'validación', val)
        if val['segm_map'] > best:
            best = val['segm_map']
            best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
    model.load_state_dict(best_state)
    test_metrics = evaluate(model, test_loader)
    OUT.mkdir(parents=True, exist_ok=True)
    torch.save(best_state, OUT / 'maskrcnn-person.pt')
    # La primera escena del test con dos personas se elige por las etiquetas,
    # antes de mirar las predicciones; si no existe se usa la primera.
    scene = next((path for path in test if len(np.unique(np.asarray(Image.open(
        folder / 'PedMasks' / (path.stem + '_mask.png'))))) - 1 >= 2), test[0])
    shutil.copyfile(scene, OUT / 'scene.png')
    image, target = Pedestrians(folder, [scene])[0]
    ground_truth = []
    for j, mask in enumerate(target['masks']):
        name = f'truth-{j:02d}.png'
        Image.fromarray(mask.numpy() * 255).save(OUT / name)
        ground_truth.append({'file': name, 'box_xyxy': target['boxes'][j].tolist()})
    model.eval()
    with torch.no_grad():
        prediction = model([image.to(DEVICE)])[0]
    keep = torch.where(prediction['scores'] >= .05)[0][:20]
    # PNG binarios sin solapamientos impuestos: corresponden a cada máscara real del modelo.
    detections = []
    for j, i in enumerate(keep.tolist()):
        mask = (prediction['masks'][i, 0].cpu().numpy() >= .5).astype(np.uint8) * 255
        name = f'maskrcnn-{j:02d}.png'
        Image.fromarray(mask).save(OUT / name)
        detections.append({'file': name, 'score': float(prediction['scores'][i]),
                           'box_xyxy': prediction['boxes'][i].cpu().tolist()})
    meta = {'short': SHORT, 'seed': SEED, 'split': {'train': [p.name for p in train],
            'valid': [p.name for p in valid], 'test': [p.name for p in test]},
            'history': history, 'test_exploratory': test_metrics, 'scene': scene.name,
            'scene_sha256': hashlib.sha256(scene.read_bytes()).hexdigest(),
            'scene_ground_truth_instances': ground_truth, 'mask_threshold': .5,
            'score_threshold': .05, 'detections': detections,
            'note': 'La partición por imagen no garantiza personas distintas entre conjuntos.'}
    (OUT / 'maskrcnn-results.json').write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Test exploratorio:', test_metrics, 'salida:', OUT.resolve())
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Compare panoptic output

The second cell receives an image exported by the first and runs pretrained Mask2Former at a pinned revision. It saves semantic, instance and panoptic outputs with their metadata. Penn-Fudan does not provide panoptic stuff GT: the comparison on this scene is qualitative and is not a PQ comparison against Mask R-CNN.

[ ]Inspect Mask2FormerLocal GPU
"""Tres salidas reales sobre la escena exportada por maskrcnn_pennfudan.py.

Requiere torch, transformers, Pillow y safetensors. Descarga los pesos en la caché
normal de Hugging Face. La revisión usa el commit oficial de la variante safetensors.
El punto de entrada ORYON_IMAGE acepta otra imagen; ORYON_OUTPUT_DIR elige salida.
En COCO panoptic de este checkpoint los ID contiguos 0..79 son things y 80..132
son stuff. Los posprocesados de una misma red no son ground truth independiente.
"""
import hashlib
import json
import os
from pathlib import Path
from types import SimpleNamespace

import numpy as np
from PIL import Image
import torch
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation

MODEL = 'facebook/mask2former-swin-tiny-coco-panoptic'
REVISION = 'df6b114'
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', 'oryon_maskrcnn'))
IMAGE = Path(os.environ.get('ORYON_IMAGE', OUT / 'scene.png'))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')


def save_map(path, value):
    arr = value.detach().cpu().numpy().astype(np.int64)
    if arr.ndim != 2 or arr.max(initial=-1) >= 65535 or arr.min(initial=0) < -1:
        raise ValueError('Mapa de IDs fuera del intervalo permitido')
    Image.fromarray(np.where(arr < 0, 65535, arr).astype(np.uint16)).save(path)


def format_segments(segments, labels):
    rows = []
    for item in segments:
        cls = int(item['label_id'])
        rows.append({'id': int(item['id']), 'label_id': cls,
                     'name': labels[cls], 'kind': 'thing' if cls < 80 else 'stuff',
                     'score': float(item['score']), 'was_fused': bool(item.get('was_fused', False))})
    return rows


def run():
    if not IMAGE.is_file():
        raise FileNotFoundError(f'No existe {IMAGE}; ejecuta primero la celda de Mask R-CNN o indica ORYON_IMAGE')
    original = Image.open(IMAGE).convert('RGB')
    size = (original.height, original.width)
    processor = AutoImageProcessor.from_pretrained(MODEL, revision=REVISION)
    model = Mask2FormerForUniversalSegmentation.from_pretrained(MODEL, revision=REVISION).to(DEVICE).eval()
    labels = {int(k): v for k, v in model.config.id2label.items()}
    if len(labels) != 133 or labels.get(0) != 'person' or labels.get(80) != 'banner':
        raise ValueError('Las clases no coinciden con el orden COCO panoptic fijado')
    inputs = {key: val.to(DEVICE) for key, val in processor(images=original, return_tensors='pt').items()}
    with torch.no_grad():
        output = model(**inputs)
        # El posprocesador de instancias de Transformers 5.20.2 crea en CPU
        # el mapa de salida; usar los mismos logits en CPU evita indexarlo
        # con máscaras CUDA. No se alteran logits ni umbrales.
        output = SimpleNamespace(class_queries_logits=output.class_queries_logits.cpu(),
                                 masks_queries_logits=output.masks_queries_logits.cpu())
        semantic = processor.post_process_semantic_segmentation(output, target_sizes=[size])[0]
        instances = processor.post_process_instance_segmentation(output, threshold=.5, mask_threshold=.5,
                                                                  target_sizes=[size])[0]
        panoptic = processor.post_process_panoptic_segmentation(output, threshold=.5, mask_threshold=.5,
                         label_ids_to_fuse=set(range(80, 133)), target_sizes=[size])[0]
    OUT.mkdir(parents=True, exist_ok=True)
    save_map(OUT / 'semantic.png', semantic)
    data = {'image': str(IMAGE), 'image_sha256': hashlib.sha256(IMAGE.read_bytes()).hexdigest(),
            'model': MODEL, 'revision': REVISION, 'image_size_hw': list(size),
            'score_threshold': .5, 'mask_threshold': .5, 'void_id': 65535,
            'semantic': {'file': 'semantic.png', 'labels': labels},
            'note': 'Predicciones, no anotaciones. La salida por instancias omite stuff; '
                    'la panóptica fusiona las clases stuff. Las máscaras de Mask R-CNN '
                    'pueden solaparse y estas son particiones producidas por el posprocesado.'}
    for name, result in [('instances', instances), ('panoptic', panoptic)]:
        seg = result['segmentation']
        if seg is None:
            data[name] = {'file': None, 'segments': []}
            continue
        rows = format_segments(result['segments_info'], labels)
        # Panóptica reserva 0 para vacío; en instancias, 0 es un ID válido
        # y el fondo ya es -1 en la versión inspeccionada de Transformers.
        seg = seg.clone()
        if name == 'panoptic':
            seg[seg == 0] = -1
        if name == 'instances':
            # Una tarea de instancias solo muestra things; los píxeles stuff pasan a vacío.
            removed = [row['id'] for row in rows if row['kind'] == 'stuff']
            for segment_id in removed:
                seg[seg == segment_id] = -1
            rows = [row for row in rows if row['kind'] == 'thing']
        save_map(OUT / f'{name}.png', seg)
        data[name] = {'file': f'{name}.png', 'segments': rows}
    (OUT / 'mask2former-results.json').write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Escena', IMAGE, 'salida', OUT.resolve())
    print('Segmentos de instancias:', len(data['instances']['segments']),
          'y panópticos:', len(data['panoptic']['segments']))
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell brings both labs’ outputs together in a visual comparison with legends. Colors represent segments, not uncertainty, and overlaying masks can hide overlaps. Mask R-CNN has just been fine-tuned with the chosen recipe, while Mask2Former retains its pretrained weights: the figure illustrates their outputs and does not compare methods under equivalent conditions. In short mode, the first network can produce many false detections.

[ ]Compare both networks’ outputsLocal GPU
"""Visualiza las dos salidas reales de las celdas locales de la lección.

Ejecuta antes ambas celdas y usa el mismo ORYON_OUTPUT_DIR. La figura compara
predicciones cualitativamente: la primera muestra personas y puede solaparlas;
la segunda es una partición panóptica con cosas y regiones amorfas.
Requiere numpy, Pillow y matplotlib, no carga modelos ni usa GPU.
"""
import hashlib
import json
import os
from pathlib import Path

import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb
import numpy as np
from PIL import Image

OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', 'oryon_maskrcnn'))


def read_json(name):
    path = OUT / name
    if not path.is_file():
        raise FileNotFoundError(f'Falta {path}. Ejecuta primero las dos celdas de modelos.')
    return json.loads(path.read_text(encoding='utf-8'))


def rgb_color(index):
    # Paleta determinista: el color identifica un segmento, no representa su score.
    return hsv_to_rgb(((index * 0.618033988749895) % 1, 0.72, 0.95))


def read_mask(name, shape):
    path = OUT / name
    if not path.is_file():
        raise FileNotFoundError(f'Falta la máscara {path}.')
    mask = np.asarray(Image.open(path))
    if mask.shape != shape:
        raise ValueError(f'Dimensiones incorrectas en {path}: {mask.shape}; esperadas {shape}')
    return mask


def print_legend(axis, entries, empty_message):
    axis.axis('off')
    if not entries:
        axis.text(0, 1, empty_message, va='top', fontsize=9, transform=axis.transAxes)
        return
    for i, (color, label) in enumerate(entries):
        y = 1 - (i + .5) / len(entries)
        axis.scatter([.012], [y], c=[color], marker='s', s=55, transform=axis.transAxes)
        axis.text(.04, y, label, va='center', fontsize=9, transform=axis.transAxes)


def run():
    detection = read_json('maskrcnn-results.json')
    panoptic = read_json('mask2former-results.json')
    scene_path = OUT / 'scene.png'
    if not scene_path.is_file():
        raise FileNotFoundError(f'Falta la imagen {scene_path}.')
    digest = hashlib.sha256(scene_path.read_bytes()).hexdigest()
    if digest != detection['scene_sha256'] or digest != panoptic['image_sha256']:
        raise ValueError('Los resultados no corresponden a la misma imagen. Vuelve a ejecutar ambas celdas.')
    image = np.asarray(Image.open(scene_path).convert('RGB'))
    height, width = image.shape[:2]
    if list((height, width)) != panoptic['image_size_hw']:
        raise ValueError('La forma de la imagen no coincide con los metadatos panópticos.')

    masks = []
    for idx, item in enumerate(detection['detections']):
        mask = read_mask(item['file'], (height, width)) > 0
        masks.append((mask, rgb_color(idx), item))

    segments = panoptic['panoptic']['segments']
    map_name = panoptic['panoptic']['file']
    ids = None if map_name is None else read_mask(map_name, (height, width))
    by_id = {}
    for segment in segments:
        segment_id = int(segment['id'])
        if segment_id in by_id:
            previous = by_id[segment_id]
            if (previous['label_id'], previous['kind']) != (segment['label_id'], segment['kind']):
                raise ValueError(f'El segmento fusionado {segment_id} tiene etiquetas incompatibles.')
        else:
            by_id[segment_id] = segment
    if ids is not None:
        present = set(map(int, np.unique(ids))) - {int(panoptic['void_id'])}
        if not present.issubset(by_id):
            raise ValueError(f'Faltan etiquetas para los segmentos: {sorted(present - set(by_id))}')
    else:
        present = set()

    left_entries = [(color, f"Predicción de persona {i + 1}: confianza {item['score']:.3f}")
                    for i, (_, color, item) in enumerate(masks)]
    right_entries = []
    for i, segment_id in enumerate(sorted(present)):
        item = by_id[segment_id]
        kind = 'objeto' if item['kind'] == 'thing' else 'región amorfa'
        right_entries.append((rgb_color(i), f"{segment_id}: {item['name']} ({kind})"))
    count = max(len(left_entries), len(right_entries), 1)
    legend_height = max(.7, .23 * count)
    fig, axes = plt.subplots(2, 2, figsize=(13, 5.8 + legend_height),
                             gridspec_kw={'height_ratios': [5, legend_height]})
    left, right = axes[0]
    left.imshow(image)
    for mask, color, _ in masks:
        rgba = np.zeros((height, width, 4), dtype=np.float32)
        rgba[..., :3] = color
        rgba[..., 3] = mask * .48
        left.imshow(rgba)
    right.imshow(image)
    if ids is not None:
        overlay = np.zeros((height, width, 4), dtype=np.float32)
        for i, segment_id in enumerate(sorted(present)):
            selected = ids == segment_id
            overlay[selected, :3] = rgb_color(i)
            overlay[selected, 3] = .48
        right.imshow(overlay)
    left.set_title(f"Mask R-CNN: predicciones de persona\nscore ≥ {detection['score_threshold']}; máscara ≥ {detection['mask_threshold']}")
    right.set_title(f"Mask2Former: salida panóptica\nscore ≥ {panoptic['score_threshold']}; máscara ≥ {panoptic['mask_threshold']}")
    for ax in (left, right):
        ax.axis('off')
    print_legend(axes[1, 0], left_entries, 'Ninguna persona superó el umbral.')
    print_legend(axes[1, 1], right_entries, 'No se generaron segmentos panópticos.')
    mode = 'prueba corta' if detection['short'] else 'receta completa'
    fig.suptitle(f"Penn-Fudan: {detection['scene']} | Mask R-CNN ({mode}) | {panoptic['model']}@{panoptic['revision']}",
                 fontsize=11)
    fig.text(.5, .015, 'Colores = IDs de segmento. Mask R-CNN permite solapes; el mapa panóptico no. '
             'La imagen no tiene anotación panóptica de referencia.', ha='center', fontsize=9)
    fig.tight_layout(rect=(0, .04, 1, .96))
    destination = OUT / 'comparacion-modelos.png'
    fig.savefig(destination, dpi=150, bbox_inches='tight')
    print('Imagen de test:', detection['scene'], '| SHA256:', digest)
    print('Figura guardada en', destination.resolve())
    print('Las máscaras son predicciones, no una comparación de PQ ni de AP entre modelos.')
    plt.show()


if __name__ == '__main__':
    run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe strict threshold
Prove: Show that, if each partition contains disjoint segments and all have positive area, one ground-truth segment cannot match two predictions with IoU strictly greater than 0.5.
0
Use same-class segments and no void for this proof; call the ground-truth segment g and the disjoint predictions p₁,p₂.

Step 1 of 3. How is IoU(pᵢ,g) bounded?

NumericSeparate quality and recognition
A category accumulates 8 matches with mean IoU 0.8, 2 false positives and 3 false negatives. What is PQ?
NumericSegment recognition
With 8 true positives, 2 false positives and 3 false negatives, what is RQ?
NumericMatched-pair quality
For the eight previous pairs, the IoU sum is 6.4. What is SQ?
CodeMask targets per region
Implement mask_targets(gt_masks, rois, size) with NumPy. gt_masks has shape G×H×W and binary values; rois has K rows (GT index, x1, y1, x2, y2) in image coordinates, with positive area. Return K×size×size in floating point. For each RoI apply scale 1 and aligned=True: subtract 0.5 from endpoints, divide into size×size bins and average 2×2 samples per bin using bilinear interpolation. Boundary convention: a sample with x<−1, x>W, y<−1 or y>H is zero; within that interval clamp coordinates to the edge before interpolation. Support K=0. Fractional targets are valid; do not threshold them.
import numpy as np


def mask_targets(gt_masks, rois, size):
  pass
Shift+Enter to run
QuizMask and class
What is the conceptual advantage of independent sigmoids for the Mask R-CNN mask branch and supervising the ground-truth class channel?
QuizA resource-limited robot
You need to separate a few known objects on a limited GPU. What comparison guides the choice between Mask R-CNN and Mask2Former?
Key idea
Semantic, instance and panoptic segmentation answer different questions. A mask must be evaluated under its own protocol, and PQ uniqueness depends on disjoint partitions and a strict threshold.