Learning To Count Everything
- Publication
- CVPR 2021Conference
- First submitted to arXiv
- arXiv:2104.08391
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{retailproductfamnet2021,
title = {{Learning To Count Everything}},
author = {Viresh Ranjan and Udbhav Sharma and Thu Nguyen and Minh Hoai},
year = {2021},
eprint = {2104.08391},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2104.08391}
}
"Counting" in computer vision has always been done one category at a time.
Counting people has crowd-counting models, counting cars has aerial vehicle models, counting cells has microscopy models. Each one needs thousands of annotated images, with a dot on every head, every car, every cell, before it can train a usable counter. Want to count something else? Start over from scratch.
That is not how people count things. Hand someone a photo of a shelf, point at one can and say "count how many of these there are", and they don't need to have seen thousands of photos of cans first.
This paper comes from Stony Brook University and VinAI in Vietnam. The authors want a model that counts the same way: given an image with three exemplars boxed, it counts how many of the same thing are in the image, and that thing can belong to a category never seen during training.
Problem Definition

The authors call this task few-shot counting. The input is an image plus boxes around a few objects in that same image; the output is the total count of that kind of object in the image. As is customary in few-shot classification, the test categories do not overlap with the training categories at all.
Two problems stand in the way.
The first is the method. The mainstream approach to counting is density-map regression. During training, each object's dot annotation is smeared out with a Gaussian kernel into a "density map"; the network learns to predict this map from the image, and summing the whole density map gives the count. The approach is mature, but what it learns is the density map of one particular category, and it stops working when the category changes.
The second is the data. Existing counting datasets almost all have a single category: one dataset for crowds, one for vehicles, one for cells. None was designed for "counting anything".
Solution
FamNet

FamNet stands for Few-shot Adaptation and Matching Network, and it has two modules.
The feature extraction module is the first four blocks of an ImageNet-pretrained ResNet-50, with every parameter frozen. The authors' reasoning is that ImageNet has seen a thousand-odd categories, so its features already cover all sorts of objects. The whole image is represented by the feature maps of the third and fourth blocks; the exemplar boxes go through ROI pooling on the same two feature maps to give each exemplar's features.
The key piece is the density prediction module. It does not take the features directly; it takes only "correlation maps", obtained by using the exemplar features as convolution kernels and sliding them across the features of the whole image to compute how similar each position is to the exemplars.
The benefit is that what the density prediction module sees has nothing to do with the category. Whether the exemplars are hot-air balloons, fish or cans, it sees a map of "does this spot look like the exemplar", and it only has to learn to turn similarity peaks into density. That is what lets it work on unseen categories.
Since objects come in different sizes, the exemplar features are also rescaled to 0.9× and 1.1×; together with the original size, each of the three scales gives a correlation map, and the maps are concatenated and fed to the density prediction module. The density prediction module consists of five convolution blocks with three upsampling steps, and a final convolution outputs a density map the same size as the input image.
Ground-Truth Density Maps
Training needs ground-truth density maps. Crowd counting usually smears each dot with a fixed-size Gaussian kernel, for example . But FSC-147 has 147 categories, some of them individual beans and some an entire wall of windows, so a fixed-size kernel doesn't fit.
The authors use an adaptive size. For each dot annotation, they find the nearest other dot and compute the distance; the average of these distances over all the dots in the image becomes the window size of the Gaussian kernel, with the standard deviation set to a quarter of the window. Densely packed objects get a small kernel; sparse ones get a large kernel.
The training loss is the mean squared error between the predicted density map and the ground truth.
A Little Tuning at Test Time
A trained FamNet can already count new categories as is. But the authors want to squeeze a bit more out of the information given at test time. So far the exemplar boxes have only been used to extract appearance features; their "positions" haven't been used yet.
The exemplar boxes tell us two things, and the authors turn each into a loss.
First, each exemplar box contains at least one object. So the sum of the density map inside the box should be at least 1. It is not required to be exactly 1, because a box may overlap neighboring objects:
is the patch of the density map inside box . If the density inside a box sums to only 0.6, this term's loss is 0.4; if it sums to 1.3, the loss is 0.
Second, the position of an exemplar box should be exactly a peak. The idea comes from correlation-filter tracking: given the target's position, the response should be highest there and fall off with displacement, shaped like a Gaussian. FamNet's density map is essentially a correlation response between the exemplars and the image, so the density inside a box should look like a Gaussian:
The two losses are combined with weights, and each test image gets 100 steps of gradient descent that update only the density prediction module. The hyperparameters look odd, with a learning rate of and weights of and . The authors explain that this keeps the magnitude of the adaptation loss's gradient close to that during training; too large and it pushes the trained parameters away, too small and nothing changes.
This is a bit like MAML's test-time adaptation, except that FamNet does not need to simulate the adaptation process during training, so there are no second-order derivatives to compute and training is much faster.
FSC-147

The authors collected the dataset themselves. They drew up a list of categories and searched Flickr, Google and Bing, prefixing the keywords with words like many, multiple and stack of; they gathered a few hundred to a few thousand candidate images per category and then filtered them by hand.
There were four filtering criteria: the resolution has to be high enough; there must be at least 7 objects of the same kind, because people can count small numbers themselves; the objects should be similar in appearance and pose; and there should be no severe occlusion.
That left 6,135 images in 147 categories, ranging from kitchenware and stationery to vehicles and animals, with 340,000 objects in total, an average of 56 per image, and more than three thousand in the busiest image. Each object gets a dot, and objects 90% or more occluded are not counted; in each image, three objects are then boxed as exemplars.
The categories are split into 89 for training, 29 for validation and 29 for testing, with no overlap.
Incidentally, one of the 147 categories is called "supermarket shelf". It averages only 8 objects per image, tied with "meat skewer" for the fewest of any category in the dataset.
Discussion
Against Other Methods
Evaluation uses MAE and RMSE, the mean absolute error and the root mean squared error between predicted and true counts.
| Method | Val MAE | Val RMSE | Test MAE | Test RMSE |
|---|---|---|---|---|
| Always guess train mean | 53.38 | 124.53 | 47.55 | 147.67 |
| FSOD few-shot detector | 36.36 | 115.00 | 32.53 | 140.65 |
| GMN (pretrained) | 60.56 | 137.78 | 62.69 | 159.67 |
| GMN (FSC-147 trained) | 29.66 | 89.81 | 26.52 | 124.57 |
| MAML | 25.54 | 79.44 | 24.90 | 112.68 |
| FamNet | 23.75 | 69.07 | 22.08 | 99.54 |
Source: Table 1 of the paper, excerpt.
Start with the first row. A "method" that looks at nothing and always outputs the mean count of the training set gets a test MAE of 47.55. That gives the whole table a baseline.
The few-shot detector (detect first, then count the boxes) does poorly, with a test MAE of 32.53. The authors argue that density estimation suits counting better than detection, because it doesn't have to make an early yes-or-no decision on every box and is more tolerant of occlusion.
GMN is an earlier class-agnostic counting method from Lu and Zisserman, pretrained on tracking videos. Used as is, its pretrained version does worse than always guessing the mean; retrained on FSC-147, its MAE drops to 26.52. The authors take this as evidence that the dataset is useful.
The MAML row uses FamNet's architecture trained the MAML way. It comes second, but each training epoch is about three times slower than FamNet's.
Now look at RMSE. Every method's RMSE is two to five times its MAE, which means the error is concentrated in a handful of images. The counts in FSC-147 range from 7 to more than three thousand per image; on an image with over a thousand objects, being off by a few tens of percent means an error in the hundreds.
Against Off-the-Shelf Detectors
Some categories in the validation and test sets happen to be COCO categories, such as cars, people and birds. The authors picked out these images and had Faster R-CNN, Mask R-CNN and RetinaNet trained on COCO count the boxes.
On the test subset, Mask R-CNN gets an MAE of 35.56 and FamNet 22.76. These detectors have seen these categories tens of thousands of times on COCO, yet when the objects are numerous and crowded, they still lose to FamNet, which looks at only three exemplars.
Ablations
More exemplars mean more accuracy: the validation MAE is 26.55 with 1 exemplar, 24.09 with 2 and 23.75 with 3. With only 2 exemplars, it already beats every other method in Table 1.
Adding the three components one at a time brings the MAE down from 32.70 to 27.80 (multi-scale image features), 24.32 (multi-scale exemplar features) and 23.75 (test-time adaptation). Test-time adaptation contributes relatively little, cutting the MAE by only 0.57. The multi-scale image features cut the MAE the most (by 4.90), while the multi-scale exemplar features cut the RMSE the most, from 93.53 to 70.94.
Specialized Categories Are Another Story
The authors also honestly tested FamNet on a specific category. CARPK is a vehicle-counting dataset of aerial parking-lot images. After adaptation on CARPK, GMN gets an MAE of 7.48; FamNet used as is without training gets 28.84, and even retrained on CARPK's training data it only reaches 18.19.
The price of counting anything is counting each thing less accurately. If you only need to count one kind of thing and have enough annotated data, a specialized model is still better.
Reproduction
The code and data are public on GitHub, and the authors have been diligent about answering in the issues.
In 2021, a team taking part in the ML Reproducibility Challenge generated the density maps themselves following the paper's description, and the results didn't match the official ones (issue #6). The authors explained that the released dot coordinates correspond to images resized to a height of 384, but the official density maps were generated at the original size and then resized, and after resizing they are multiplied by a factor so that the sum keeps the original count. The paper doesn't mention this detail, so anyone generating their own density maps should watch for it.
Also, most images have 3 exemplar boxes and a few have 4 or 5; the authors say all experiments use only 3 (issue #9).
Conclusion
FamNet separates counting from category. Frozen ImageNet features do the "looking", correlation maps between the exemplars and the image do the "finding things that look alike", and the density prediction module only learns how to turn similarity into density. At test time, it then uses the positions of the exemplar boxes for 100 steps of fine-tuning, so that the density map sums to at least 1 at the exemplar positions and has a Gaussian shape there.
FSC-147 is the more lasting thing this paper left behind. With 147 categories, non-overlapping category splits and three exemplar boxes per image, it became the main benchmark for later class-agnostic counting methods such as CounTR, LOCA and CountGD.
On a shelf, where you box a few samples and have the model count how many facings a product has, FamNet showed that this path works. The three exemplars do need to be boxed accurately, though; and when the counts vary a lot from photo to photo, be prepared, since its RMSE is several times its MAE.