Back to paper library
Paper notesarXiv 2016IEEE SPL 2016

MTCNN

Three Heads Are Better Than One

Original paper

Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks

Paper authors

Kaipeng Zhang · Zhanpeng Zhang · Zhifeng Li · Yu Qiao

First submitted to arXiv
arXiv:1604.02878
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{objectdetectionmtcnn2016,
  title = {{Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks}},
  author = {Kaipeng Zhang and Zhanpeng Zhang and Zhifeng Li and Yu Qiao},
  year = {2016},
  eprint = {1604.02878},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1604.02878}
}
On this page

Open a face recognition paper from 2016 to 2018, and the first paragraph of the implementation details often looks much the same.

Center Loss says the faces in the images and their landmarks are detected with the recently proposed algorithms, five points (two eyes, nose tip, two mouth corners) are used for a similarity transform, the faces are cropped to 112×96112\times96 RGB images, and every pixel has 127.5 subtracted and is then divided by 128. CosFace says almost exactly the same thing. SphereFace's official preprocessing code is even more direct. It adds a folder called MTCNNv1 to the Matlab path, and after detection it aligns the five points to fixed coordinates on an image 96 wide and 112 tall, the left eye to (30.29,51.70)(30.29, 51.70) and the right eye to (65.53,51.50)(65.53, 51.50).

Those "recently proposed algorithms" are this paper, MTCNN.

It takes a photo and spits out each face's box, confidence score and five points. Inside is a cascade of three very small convolutional networks, the smallest of which has just over six thousand parameters. Taken one at a time, none of them is particularly strong; chained together, they lift the score on the hardest subset of WIDER FACE from 0.400, the best among the paper's baselines, to 0.607.

Defining the Problem

Detection and alignment

Face recognition wants a face that has already been straightened and cropped as its input. Getting from the raw photo to that face takes two steps. Face detection finds each face's box; face alignment finds landmarks inside the box and uses them to straighten the face. The two steps are usually handled by different models.

On the detection side, the Viola–Jones cascade classifier uses Haar features plus AdaBoost. It's fast, but it clearly degrades on profiles, occlusion and extreme lighting. DPM (deformable part models) is more accurate but expensive to compute, and training it needs extra part annotations. When CNNs first came in, there were two typical designs as well. Faceness first trains networks to recognize facial attributes such as hair, eyes and nose, then finds faces from the attribute response maps; the structure is complicated and slow. Li et al.'s CascadeCNN filters from coarse to fine with three detection networks (12-net, 24-net, 48-net), each followed by a network dedicated to calibrating the box position, for six networks in all.

On the alignment side, there are regression methods (such as ERT and SDM), template-fitting methods, and TCDCN, which uses facial attributes as auxiliary tasks.

The authors argue that these two tasks had always been handled separately, ignoring how they relate. Knowing where the facial features are should make the box easier to draw accurately; in turn, an accurate box makes the features easier to find. Some had tried to put the two together. Chen et al.'s JDA does detection and alignment jointly with random forests and pixel-difference features, but hand-crafted features cap its performance; Zhang et al. used a multi-task CNN to improve multi-view detection, but its accuracy was held back by the candidate windows from the weak detector in front of it.

Training a detector comes with another nuisance. Background samples are endless, and most of them can be told apart from a face at a glance; the useful ones are the hard negatives that look like faces. The traditional approach is to train one round, scan the training set with the model, pick out what it got wrong and train another round. This offline mining takes several rounds of manual work.

So this paper sets out to answer two questions. Can a set of small networks do detection and five-point alignment well at the same time, and run fast enough? And can hard samples be picked automatically during training?

Three exams

The paper evaluates on three datasets.

  • FDDB: 2,845 images and 5,171 faces. Scoring draws an ROC curve, with the total number of false positives (non-faces that get boxed) on the horizontal axis and the fraction of faces found (the true positive rate) on the vertical axis. The paper reports the true positive rate at 2,000 false positives.
  • WIDER FACE: 32,203 images and 393,703 boxes, split 40% training, 10% validation and 50% test, and divided by difficulty into Easy, Medium and Hard subsets, with Hard containing lots of small faces only a dozen or so pixels wide. Scoring uses AP. A detection counts as correct if its IoU (intersection over union) with a labeled box exceeds 0.5, and AP is the area under the precision–recall curve. The test-set annotations aren't public, so results have to be submitted to the organizers for scoring.
  • AFLW: 24,386 faces, each with up to 21 landmarks. The paper evaluates only five points (two eyes, nose tip, two mouth corners) and reuses TCDCN's test split (the TCDCN journal version says 3,000 faces were picked at random). The error is the distance from each predicted point to the ground truth divided by the inter-ocular distance, then averaged.

Solving the Problem

The overall pipeline

Original Fig. 1: a flowchart in four rows. The first row scales the test image to several sizes and stacks them into an image pyramid. The second row, Stage 1 P-Net: dozens of white boxes of all sizes cover the same face, and a dozen or so are still left after NMS and box regression, some covering only the eyes or the mouth. The third row, Stage 2 R-Net: the few remaining boxes gather on the face, and the output has only one large box and one small box around the eyes. The fourth row, Stage 3 O-Net: a single face box is left, with five white dots marked on the face.
Original Fig. 1, Zhang et al., from PDF page 2, arXiv license, scholarly quotation.

Read it from top to bottom. The photo is first scaled into a stack of images of different sizes, called an image pyramid.

In Stage 1, P-Net (Proposal Network) sweeps the whole image at every level of the pyramid, asking at each position "is there a 12×1212\times12 face here?" and also predicting how the box should be adjusted. Positions with high enough scores are kept, and after box-regression calibration and NMS (non-maximum suppression, which merges heavily overlapping boxes into one), you get the cluster of candidate boxes on the right of the second row. Some cover only the eyes; some are so big they spill past the face.

In Stage 2, R-Net (Refine Network) crops out each candidate box, shrinks it to 24×2424\times24 and judges it again. Most of the false ones are thrown out here, and the rest go through another round of box regression and NMS. On the right of the third row there's still one big box, plus a small box around the eyes.

In Stage 3, O-Net (Output Network) shrinks the candidates to 48×4848\times48, takes one more look, and outputs the final boxes along with five landmarks.

The later the network, the bigger it is and the more closely it looks, but the fewer boxes it handles. The cheapest network covers the most positions, and the most expensive one sees only a handful of candidates.

How many times a 640×480 photo gets scanned

Two parameters decide how many levels the pyramid has. minsize is the smallest face you want to find, 20 pixels in the official example; factor is the scale ratio between adjacent levels, set to 0.709.

P-Net's window is 12×1212\times12. For a 20-pixel face to come out at exactly 12 pixels, the first level has to shrink the photo to 12/20=0.612/20 = 0.6 of its size. Every level after that multiplies by 0.709 again, until the short side drops below 12 pixels. 0.709≈1/20.709 \approx 1/\sqrt2, so every two levels down the image shrinks by half, and the face size the window catches doubles.

Here are the numbers for a 640×480640\times480 photo:

LevelScaleResizedFace width
10.600384×28820
20.425273×20528
30.302194×14540
40.214137×10356
50.15298×7379
60.10769×52112
70.07649×37157
80.05435×26222
90.03825×19313
100.02718×14442

Computed for this note from the pyramid rule in the official detect_face.m; face widths are in pixels of the original image.

Across the ten levels, P-Net has to judge about 50,000 windows, half of them on the first level (this note's estimate). Change minsize from 20 to 40 and the first level shrinks to 0.3, cutting the total to about 12,000; change it to 10 and set factor to 0.79 (the setting the authors use to reproduce the WIDER FACE results), and the total becomes about 280,000. These two parameters alone can make the same model's speed differ by a factor of more than twenty.

P-Net: a fully convolutional sliding window

Original Fig. 2: three dashed boxes for P-Net, R-Net and O-Net. P-Net: a 12×12×3 input goes through a 3×3 convolution and 3×3 max pooling to 5×5×10, then two 3×3 convolutions to 3×3×16 and 1×1×32, and finally splits into three 1×1 outputs, face classification 1×1×2, box regression 1×1×4 and landmarks 1×1×10. R-Net: a 24×24×3 input, two convolutions with pooling to 11×11×28 and 4×4×48, a 2×2 convolution to 3×3×64, a 128-unit fully connected layer, and outputs of 2, 4 and 10. O-Net: a 48×48×3 input, three convolutions with pooling to 23×23×32, 10×10×64 and 4×4×64, a 2×2 convolution to 3×3×128, a 256-unit fully connected layer, and outputs of 2, 4 and 10.
Original Fig. 2, Zhang et al., from PDF page 3, arXiv license, scholarly quotation.

Start with P-Net at the top left. The 12×12×312\times12\times3 input goes through three 3×33\times3 convolutions and one stride-2 pooling and shrinks to exactly 1×1×321\times1\times32; 1×11\times1 convolutions then split off two outputs, 2 numbers for whether it's a face and 4 numbers for how to adjust the box.

The figure also draws a 10-dimensional landmark output for P-Net. P-Net does have a landmark loss during training (with a weight of 0.5), but the officially released P-Net and R-Net models keep only the classification and box outputs; only O-Net outputs the five points.

The network has no fully connected layer, so it can take a whole 384×288384\times288 image directly. The output becomes a 187×139187\times139 score map, where each position corresponds to a 12×1212\times12 window on the image and neighboring positions are 2 pixels apart (the stride of that one pooling). The result is the same as sliding a 12×1212\times12 window every 2 pixels and feeding each one into the network, but the convolutions over the overlapping parts are computed only once.

How does a position on the score map map back to the original image? The output at column jj, row ii (counting from 0) corresponds to a window on the shrunken image with its top-left corner at (2j,2i)(2j, 2i) and a side of 12, which is then divided by the scale. Suppose that on the first level (0.6×), the score at column 49, row 29 clears the threshold. The window on the shrunken image starts at (98,58)(98, 58) and is 12 pixels across; mapped back to the original, it starts at (163,97)(163, 97) and is 20 pixels across.

Windows scoring above the threshold (0.6 in the official example) are kept. NMS runs once within each level with an IoU of 0.5, and once more with 0.7 after the ten levels are merged.

Then box regression adjusts them. The paper says it regresses the box's top-left corner, width and height; the official code actually regresses separate offsets for the top-left and bottom-right corners, in units of the box's width and height. If the four numbers are (−0.1,0,0.2,0)(-0.1, 0, 0.2, 0), the top-left corner moves left by 0.1 box widths and the bottom-right corner moves right by 0.2 box widths, so a box 20 pixels wide becomes 26 pixels wide. After that the box is padded into a square (taking the longer side), because the next stage's input is square.

R-Net and O-Net

Candidate boxes are cropped from the original image (with zeros filling whatever falls outside the image), shrunk to 24×2424\times24 and fed into R-Net. R-Net has three convolutional layers followed by a 128-dimensional fully connected layer, so it looks at the whole 24×2424\times24 field. Boxes scoring above 0.7 are kept, followed by NMS, box regression and squaring.

O-Net is one size bigger, with a 48×4848\times48 input, four convolutional layers and a 256-dimensional fully connected layer, and it outputs the score, the box and five points. The paper doesn't say how the point coordinates are represented; in the official code they are relative positions within the box, between 0 and 1. For a face whose box has its top-left corner at (100,50)(100, 50) and a side of 180, a left-eye output of (0.30,0.40)(0.30, 0.40) maps back to (100+0.30×180, 50+0.40×180)=(154,122)(100 + 0.30\times180,\ 50 + 0.40\times180) = (154, 122) in the original image.

The NMS after O-Net uses a different measure. The first two stages measure overlap with IoU (intersection over union); the last stage uses the intersection divided by the area of the smaller box. The difference shows up with boxes like the one around the eyes. Inside a 100×100100\times100 face box, a 30×3030\times30 eye box that sits entirely within it has an IoU of only 900/10000=0.09900/10000 = 0.09, so ordinary NMS keeps both; with the smaller box as the denominator, the overlap is 900/900=1900/900 = 1, and the eye box gets removed. The small box still hanging around in the third row of Fig. 1 is gone by the fourth row.

Why the networks look like this

The authors take CascadeCNN's three detection networks as the point of comparison. They argue that some of the filter weights in those networks lack diversity, and that face detection, being only binary classification, doesn't need that many filters; what it needs is filters that are each more discriminative. So they cut the number of filters, replaced 5×55\times5 convolutions with 3×33\times3 ones, and spent the saved computation on making the networks deeper.

Network300 forward passesVal. accuracy
12-Net0.038 s94.4%
P-Net0.031 s94.6%
24-Net0.738 s95.1%
R-Net0.458 s95.4%
48-Net3.577 s93.2%
O-Net1.347 s95.4%

Compiled from Table I of the paper; the two networks in each pair use the same training and validation data.

In every pair, MTCNN's network is both faster and more accurate. The gap is widest in the third pair, where O-Net takes less than 40% of 48-Net's time and scores 2.2 percentage points higher.

How small are these three networks? Counting from the officially released model definitions, P-Net has 6,632 parameters, R-Net about 100,000 and O-Net about 390,000, under 500,000 for all three together (this note's estimate). The three caffemodel files are 28 KB, 408 KB and 1.56 MB, which matches those parameter counts stored as 32-bit floats. Every convolutional and fully connected layer is followed by a PReLU.

One loss, three tasks

All three networks share the same training objective; only the weights differ.

Face classification uses binary cross-entropy, where pip_i is the probability the network gives that sample xix_i is a face and yidet∈{0,1}y_i^{det}\in\{0,1\} is the label:

Lidet=−(yidetlog⁡pi+(1−yidet)log⁡(1−pi))\begin{aligned} L_i^{det} = -\Big(&y_i^{det}\log p_i\\ &+ \left(1 - y_i^{det}\right)\log\left(1 - p_i\right)\Big) \end{aligned}

Box regression and landmark regression both use squared error:

Libox=∥y^ibox−yibox∥22Lilandmark=∥y^ilandmark−yilandmark∥22\begin{aligned} L_i^{box} &= \left\| \hat y_i^{box} - y_i^{box} \right\|_2^2\\ L_i^{landmark} &= \left\| \hat y_i^{landmark} - y_i^{landmark} \right\|_2^2 \end{aligned}

y^\hat y is the network's output and yy is the ground truth. A box is 4 numbers, yibox∈R4y_i^{box}\in\mathbb R^4; each of the five points has its own x,yx, y, so yilandmark∈R10y_i^{landmark}\in\mathbb R^{10}.

A training image doesn't necessarily have all three kinds of labels. A background patch has neither a box nor landmarks, so only classification applies; faces from CelebA (about 200,000 celebrity photos, each labeled with five points) have landmarks but aren't used to train classification. The paper uses an indicator variable βij∈{0,1}\beta_i^j\in\{0,1\} to decide which terms sample ii contributes:

min⁡∑i=1N ∑j∈{det, box, landmark}αj βij Lij\min \sum_{i=1}^{N}\ \sum_{j\in\{det,\,box,\,landmark\}} \alpha_j\,\beta_i^j\,L_i^j

αj\alpha_j is the task weight. P-Net and R-Net use (αdet,αbox,αlandmark)=(1,0.5,0.5)(\alpha_{det}, \alpha_{box}, \alpha_{landmark}) = (1, 0.5, 0.5); O-Net has to output accurate five points, so its landmark weight goes up to 1.

Samples are sorted into four types by their IoU with the ground-truth box:

TypeConditionClassBoxPoints
NegativeIoU < 0.3✓
PositiveIoU > 0.65✓✓
Part face0.4 ~ 0.65✓
Landmark faceFive points labeled✓

Compiled from Section III-A of the paper.

Take O-Net as an example. A crop with an IoU of 0.5 against the ground-truth box is a part face. It isn't a complete face, and it isn't background either, so it isn't used to train classification; but how far it is from the ground-truth box is perfectly clear, so it contributes only 0.5 Lbox0.5\,L^{box}. A positive with an IoU of 0.7 contributes Ldet+0.5 LboxL^{det} + 0.5\,L^{box}. A face from CelebA contributes only 1×Llandmark1\times L^{landmark}.

Crops with an IoU between 0.3 and 0.4 aren't used at all. The journal version of the paper, which the authors put in the official repo, adds the reason. The line between part faces and negatives is blurry to begin with, and boxes drawn by different annotators vary, so a gap from 0.3 to 0.4 is left between the two. The journal version also gives the ratio of the four sample types as 3:1:1:2 (negatives, positives, part faces, landmark faces).

Picking hard samples during training

Online hard sample mining is used only for the classification task. After the forward pass of each mini-batch, the classification losses of all samples are sorted, and only the largest 70% are used to compute gradients; the other 30% aren't backpropagated.

Take two background samples. A patch of sky, which the network gives a 0.01 probability of being a face, has a loss of −log⁡0.99≈0.01-\log 0.99 \approx 0.01; a curtain with a pattern that looks like eyes, given 0.6, has a loss of −log⁡0.4≈0.92-\log 0.4 \approx 0.92. After sorting, the sky most likely lands in the bottom 30% and sits out this update. There's no need to train a round first and then go back to pick; each batch decides for itself.

Each stage's data comes from the stage before

The three networks are trained one after another.

  1. P-Net: random crops from WIDER FACE, sorted by IoU into positives, negatives and part faces; faces cropped from CelebA serve as landmark samples.
  2. R-Net: the trained P-Net runs detection on WIDER FACE, and positives, negatives and part faces are collected from its output; the landmark samples are likewise detected on CelebA.
  3. O-Net: the same procedure, using the output of P-Net plus R-Net.

This way, the negatives a later network sees are exactly the ones the earlier networks couldn't sort out. R-Net's job is to clear out P-Net's false positives, so its training data ought to look like P-Net's false positives.

Discussion

Two ablations

Original Fig. 3: (a) iterations (0 to 35 thousand) on the horizontal axis and classification loss on the validation set on the vertical axis; the black line with triangles is without hard sample mining and the green line is with it. Both lines fall together from 0.3 to around 0.15, the green one mostly slightly lower, and both have a spike around 10,000 iterations. (b) ROC curves on FDDB, with false positives from 0 to 1,000 on the horizontal axis and true positive rate from 0.90 to 0.95 on the vertical axis; JA (solid orange) is highest, No JA in BBR (red dashed) hugs it just below, and No JA (blue dotted) is clearly lower.
Original Fig. 3, Zhang et al., from PDF page 4, arXiv license, scholarly quotation.

The left plot is hard sample mining. The authors trained two O-Nets that do classification only, with the same initialization and the same fixed learning rate, and compared their validation losses. The green line (with mining) is mostly below the black one, but the gap between them is mostly under 0.01, and at 35,000 iterations it's about 0.145 versus 0.15. The paper calls the benefit "very clear" (you'll need to squint). The journal version swapped this experiment for two P-Nets compared on FDDB and reports an overall improvement of about 1.5%.

The right plot shows the effect of jointly learning landmarks, with three O-Nets attached to the same P-Net and R-Net and compared on FDDB:

  • JA: O-Net learns classification, boxes and landmarks together.
  • No JA: O-Net doesn't learn landmarks.
  • No JA in BBR: classification uses the O-Net that learned landmarks, while box regression uses the one that didn't.

Reading off the plot, at 200 false positives the three lines sit at about 0.925, 0.924 and 0.919, and at 1,000 false positives at about 0.943, 0.942 and 0.939. Take the landmarks away and the whole curve drops by roughly 0.5 percentage points, while the line that swaps out only the box regression nearly overlaps JA. Going by this plot, the landmark task mostly helps classification and does far less for box regression. The paper says it helps both.

Detection results

True positive rate on FDDB at 2,000 false positives:

MethodTrue positive rate
MTCNN0.9504
DP2MFD0.9173
Faceness0.9098
HeadHunter0.8808
Joint Cascade0.8667
CascadeCNN0.8567

Compiled from the legend of Fig. 4(a) of the paper, showing the top four baselines plus CascadeCNN. Joint Cascade is the JDA mentioned earlier.

AP on WIDER FACE:

MethodEasyMediumHard
MTCNN0.8510.8200.607
Faceness0.7160.6040.315
Multiscale Cascade0.7110.6360.400
ACF0.6950.5880.290
Two-stage CNN0.6570.5890.304

Compiled from the legends of Fig. 4(b)–(d) of the paper.

The baselines are all the WIDER FACE paper's own benchmarks. Hard goes from 0.400 to 0.607, the biggest gain of the three subsets; the authors later wrote in the code's documentation that reproducing these results requires setting the minimum face to 10 pixels. The paper doesn't say which split these numbers come from. Checked against the baseline curves shipped with the official WIDER FACE evaluation tools, they are test-set numbers; in the same tools, MTCNN's validation-set results are 0.848, 0.825 and 0.598.

Five-point alignment

Mean error of the five points on AFLW (normalized by the inter-ocular distance, %):

MethodMean error
TSPM15.9
CDM13.1
Luxand13.0
ESR12.4
RCPR11.6
SDM8.5
TCDCN8.0
MTCNN6.9

Compiled from the values labeled on the bar chart in Fig. 4(e) of the paper.

MTCNN comes in 1.1 percentage points below TCDCN. At test time there were 13 images where MTCNN couldn't detect a face, and for those the authors simply cropped the center of the image and fed it to O-Net.

Point by point, MTCNN is lowest on both eyes, the nose tip and the right mouth corner, while SDM is slightly lower on the left mouth corner (about 6.6% versus 7.0%). The arXiv version says it beats every baseline; the journal version adds a sentence saying the advantage in locating mouth corners is smaller, probably because the training data doesn't have enough variation in expression.

Speed

The arXiv version says 16 fps on a 2.60 GHz CPU and 99 fps on an Nvidia Titan Black GPU, with unoptimized Matlab code. It doesn't say how big the images were or how small the faces it was looking for. The journal version's conclusion fills in the conditions, 640×480640\times480 VGA images with a minimum face of 20×2020\times20.

As computed earlier, these two parameters decide how many windows P-Net has to scan, and the work for R-Net and O-Net depends on how many candidates the frame holds. In February 2018 comments on issue #26 of the official repo, someone got only 2 fps on a Titan X; another user reported about 5.5 fps on WIDER FACE images with a minimum face of 30 pixels and 20 to 80 fps on CelebA (one large face per photo) with a minimum face of 60 pixels, and said hitting 99 fps would take your own CUDA and optimized C++. facenet-pytorch's README measured it on a Kaggle P100 at 13 frames per second on 1080p video, against 3 frames per second for the TensorFlow-based mtcnn package under the same conditions.

How far the official code is from the paper

The official repo has Matlab inference code and three Caffe models, and no training code.

On October 3, 2016, issue #1 asked for the training code, and the first author replied the next day, "The training code may be released few months later (I am too busy to sort out them)." A year later someone asked in the same thread, "it's one YEAR passed, but where is the training code???" The repo was last updated in October 2022, and it still has only the inference code. Every training implementation the community has produced since was worked out on its own, for example AITTSMD/MTCNN-Tensorflow, whose author found that some of CelebA's landmarks are mislabeled, switched to a different five-point dataset, and says plainly in the README that the landmark results aren't very good.

People trying to reproduce the WIDER FACE results hit a wall too. The code's README says that to reproduce the paper's results you should set minsize to 10, factor to 0.79 and the three stage thresholds to 0.5, 0.5 and 0.3. issue #23 (September 2017) did exactly that and got 83.3, 80.9 and 62.2, against the paper's 85.1, 82.0 and 60.7; issue #26 got 0.834, 0.810 and 0.624 on the validation set, against 0.848, 0.825 and 0.598 in the official tools. Neither thread got a reply from the authors. Issue #23 compared against the paper's test-set numbers while it could only run on the validation set, so the two were never the same images in the first place; issue #26, with both sides on the validation set, came out 1.4 and 1.5 percentage points lower on Easy and Medium and 2.6 higher on Hard.

Reading the code turns up a few more things the paper never mentions.

  1. The box regression definition. As mentioned earlier, the code regresses the offsets of two corners, not the top-left corner, width and height the paper describes. issue #51 (May 2019) asked about this and got no reply.
  2. Flip-averaged landmarks. After O-Net, MTCNNv1 flips each 48×4848\times48 face patch horizontally and runs O-Net on it again, swaps the left and right eyes and the left and right mouth corners, replaces xx with 1−x1-x, and averages the result with the original prediction.
  3. A fourth network. MTCNNv2 adds an LNet after O-Net. It crops a small patch centered on each landmark with a side of 0.25 box widths, stacks the five patches into a 15-channel 24×2424\times24 input, and predicts a fine adjustment for each point; if a single point's shift is too large, it isn't applied.
  4. Transposed images. Caffe's Matlab interface expects data in width × height order, but the official code feeds Matlab's height × width images in as they are, so the network actually sees transposed images, and judging from the code, the models were trained on this kind of input too. David Sandberg's TensorFlow port transposes the image before feeding each network; the later mtcnn package stresses in its README that its implementation avoids unnecessary transpositions. The input channels are RGB, and feeding BGR straight from OpenCV misses faces; in issue #13 of the mtcnn package, someone went from 7 faces to 5 because of it.

The ports

Most people who use MTCNN are using a port, with weights converted step by step from the official Caffe models. David Sandberg's facenet project converted them to TensorFlow first, facenet-pytorch converted them from there to PyTorch, and the mtcnn package is also built on the official weights. facenet-pytorch's defaults are a minimum face of 20, thresholds of 0.6, 0.7 and 0.7, and a scale factor of 0.709, the same as the official example.

These packages all return only boxes and five points, without alignment. The facenet-pytorch author put it bluntly in issue #34 (November 2019), "No, MTCNN does not do face alignment." Its MTCNN() just crops the box and resizes it to 160×160160\times160, without straightening the face. To align, you have to compute the similarity transform from the five points and a template yourself.

The license of the weights isn't clear either. The official repo as a whole is MIT-licensed, but the models were trained on WIDER FACE and CelebA, the former under CC BY-NC-ND and the latter explicitly for non-commercial research only. Someone asked about this in the official repo twice (June 2018 and September 2019) and got no reply either time; the author of the mtcnn package answered in their own repo that the MIT license covers only the code, and the weights shouldn't be used commercially.

Why it became the standard preprocessing

Back to the beginning. MTCNN showed up just before the explosion of face recognition loss functions, it gave boxes and five points at the same time, and it could run on a CPU. Center Loss comes from the same lab, and its second author is MTCNN's first author, Kaipeng Zhang; the README of MTCNN's official repo still recommends Center Loss's face recognition toolkit today. SphereFace, CosFace and AM-Softmax all followed this pipeline afterwards, and the alignment template got passed down with it.

SphereFace's template is 112×96112\times96 (height × width). InsightFace's ArcFace switched to 112×112112\times112 and added 8 pixels to each of the template's five xx coordinates, so the left eye goes from (30.29,51.70)(30.29, 51.70) to (38.29,51.70)(38.29, 51.70) and nothing else changes, which amounts to padding 8 pixels on each side.

In 2022, AdaFace still used MTCNN for alignment when handling IJB-S and TinyFace, two datasets of surveillance and low-resolution faces.

What replaced it was RetinaFace, from the InsightFace team in 2019, a one-stage detector that regresses the box and the five points together at every anchor of the feature pyramid. The RetinaFace paper uses MTCNN as a baseline. On AFLW (normalized by box size), the five-point error drops from 2.72% to 2.21%; on the WIDER FACE validation set, counting an error above 10% as a failure, MTCNN fails 26.31% of the time and RetinaFace 9.37%.

Conclusion

MTCNN uses three small networks of increasing size to filter faces from coarse to fine over an image pyramid, with the last stage outputting both the box and five points. Training uses a multi-task loss with per-sample indicator variables, so background, part faces and CelebA landmark samples each contribute only the term they should, and classification adds online hard sample mining that keeps the top 70% of every batch. WIDER FACE Hard goes from 0.400 to 0.607, and the five-point error on AFLW is 6.9%. The evidence from the ablations is thinner. The curves for hard sample mining barely differ, and the landmark task's help for box regression is hard to make out.

What an MTCNN package hands back is boxes and five points; the face hasn't been straightened yet. You have to do the similarity transform yourself, with a template that matches the one the recognition model was trained with. The image you feed in has to be RGB, so remember to convert the BGR that OpenCV reads. And if the faces in your photos are all large, raise minsize, and P-Net gets to skip most of the windows it would otherwise scan.

Detectors have gone through several generations since, but the definition of these five points, the two eye centers, the nose tip and the two mouth corners, carried on all the way to RetinaFace.