Back to paper library
arXiv 2020ECCV 2020Retail visionPaper notes

OS2D

Find It by the Picture

Original paper

OS2D: One-Stage One-Shot Object Detection by Matching Anchor Features

Paper authors

Anton Osokin · Denis Sumin · Vasily Lomakin

Publication
ECCV 2020Conference
First submitted to arXiv
arXiv:2003.06800
Cite this paper · BibTeX

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

@misc{retailproductos2d2020,
  title = {{OS2D: One-Stage One-Shot Object Detection by Matching Anchor Features}},
  author = {Anton Osokin and Denis Sumin and Vasily Lomakin},
  year = {2020},
  eprint = {2003.06800},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2003.06800}
}
On this page

Roughly a tenth of the products on supermarket shelves change every month. New flavors, new packaging, seasonal limited editions; every batch of changes means new photos, new boxes and a retrained detector.

If a detector could look at a single product photo and find the same product on the shelf, all of this would get much simpler. This task is called one-shot object detection. The classes to find at test time are never seen in training, and each class gets only one class image.

The authors are from the Higher School of Economics in Moscow, Yandex, and a company called mirum.io. They rewrote old-school feature matching plus geometric verification as a network that can be trained end to end, and named it OS2D.

Problem Definition

One-shot detection at the time mostly worked in two stages. The first stage is a class-agnostic proposal generator, such as the RPN in Faster R-CNN, which boxes every region that "looks like a thing"; the second stage turns each box into a global vector and measures its distance to the class image's vector.

This approach assumes that the detector already knows what "an object" looks like, and that it can settle on the boxes before it knows the target class.

On a shelf, that assumption often fails.

Original Fig. 1: (a) class images of two classes, numbered 9 and 10, both split cups with a small compartment of toppings on the left and a large compartment of yogurt on the right, differing in the color of the toppings. (b) The baseline system's result on a shelf photo: the yellow boxes split the topping compartment from the yogurt compartment and box each as a separate object. (c) The OS2D result: every box covers the whole split cup.
Original Fig. 1, Osokin et al., from PDF page 2, arXiv license, scholarly quotation.

The product in this example is a split-cup yogurt, with a small compartment of toppings such as chocolate balls on the left and the yogurt itself in the large compartment on the right. The baseline's detector doesn't know what it's looking for, so when it sees one small compartment and one large one, it cuts them into two boxes; the retrieval system downstream receives the wrongly cut boxes, and no amount of comparing will make them match.

OS2D doesn't define an "object" first. It compares the class image directly against the shelf photo, location by location. The class image itself shows that this product consists of two compartments, so the box naturally covers both.

The authors also take issue with the evaluation protocols common at the time. Many papers randomly pick an image from PASCAL VOC or COCO as the example, but the classes in these datasets are broad. The same class "dog" might be just a head or a whole body; the same class "car" might be seen from the front or from the side. Give the detector one dog's head and ask it to find whole dogs, and a single image simply can't define the class.

So the authors moved the fight to a place where the one-shot setting is more natural. On a shelf, every unit of the same product looks exactly alike, the class image is a front shot of the product, and the problem is close to "instance-level" recognition.

Solution

Original Fig. 2: on the left, OS2D's inputs, outputs and four steps: feature extraction, correlation matching, spatial alignment and computing outputs; at the bottom left are the localization boxes (yellow), the corresponding affine transformations (red parallelograms) and the score map. On the right, the tensor-level pipeline: input features h^A × w^A × d and class features h^C × w^C × d; the class features are bilinearly resampled to h^T × w^T × d and a correlation tensor h^A × w^A × (h^T w^T) is computed; TransformNet outputs transformation parameters h^A × w^A × P for every location, and the grid sampler produces sampling grids h^A × w^A × (2 h^T w^T); finally the correlations are resampled and average-pooled into detection scores h^A × w^A × 1, and localization boxes h^A × w^A × 4 are taken from the grids.
Original Fig. 2, Osokin et al., from PDF page 4, arXiv license, scholarly quotation.

The core parts of OS2D weren't invented by the authors; they're borrowed from a line of work on semantic alignment by Rocco et al.

Borrowed Parts

The problem semantic alignment solves is computing, for two given images, the geometric transformation that maps one onto the other. Rocco's approach first extracts two feature maps with a CNN, then computes the correlation between every pair of locations:

c[k,l,p,q]=⟨fkl,gpq⟩∥fkl∥2 ∥gpq∥2c[k, l, p, q] = \frac{\langle f_{kl}, g_{pq} \rangle}{\lVert f_{kl} \rVert_2 \, \lVert g_{pq} \rVert_2}

(k,l)(k, l) is a location in the first image, (p,q)(p, q) a location in the second, and cc is simply the cosine similarity of the two feature vectors. When both images have 15×1515 \times 15 feature maps, cc is a 15×15×15×1515 \times 15 \times 15 \times 15 four-dimensional tensor.

Next, the last two dimensions are flattened into a 15×15×22515 \times 15 \times 225 three-dimensional tensor, which goes into a small network called TransformNet. It has three convolutional layers with a receptive field of exactly 15×1515 \times 15, shrinks the spatial size down to 1×11 \times 1, and outputs a set of transformation parameters.

From One Pair of Images to a Whole Shelf

The idea of OS2D is to treat TransformNet as a convolution kernel and slide it over a much larger shelf feature map.

Let's walk through an example. Say training cuts out a 600×600600 \times 600 patch of a shelf image, and the feature extractor is the third block of a ResNet with stride 16, so the shelf side gets a feature map of roughly 38×3838 \times 38. On the class-image side, whatever the size of the original image, it has to become 15×1515 \times 15, because the number of input channels of TransformNet's first convolution is fixed at 15×15=22515 \times 15 = 225.

The authors learned one thing the hard way here. Resizing the class photo straight into a square squashes a bottle into a can, and matching quality drops noticeably; extracting features first and then bilinearly resampling the feature map to 15×1515 \times 15 works better. The feature extractors on both sides also have to share parameters. The authors tried switching the shelf side to an FPN; the classes seen in training did well, but new classes could no longer be found.

Once the correlations are computed, we have a 38×38×22538 \times 38 \times 225 tensor. Every location on the shelf has 225 numbers, describing how similar its surroundings are to each cell of the class image. TransformNet is applied fully convolutionally, and every location outputs PP transformation parameters.

Next, for every location (k,l)(k, l), its transformation parameters map the 15×1515 \times 15 grid points of the class image onto the shelf feature map, giving 225 sampling points. These are the red parallelograms at the bottom left of Fig. 2; each parallelogram is the class image as it looks after being moved onto the shelf.

How the Score Is Computed

Rocco originally judged alignment quality with a soft-inlier count, but that requires building a mask of size hA×wA×hT×wT×hT×wTh^A \times w^A \times h^T \times w^T \times h^T \times w^T. In our example that's 38×38×225×22538 \times 38 \times 225 \times 225, about 73 million numbers, and every class needs its own copy.

The authors switched to an approach that saves memory. If cell (p,q)(p, q) of the class image is moved to some point gg on the shelf, go to channel (p,q)(p, q) of the correlation tensor and read the correlation at location gg:

s^[k,l,p,q]=c[g0, g1, p, q]gm=g[k,l,p,q,m],m∈{0,1}\begin{aligned} \hat{s}[k, l, p, q] &= c\big[g_0,\ g_1,\ p,\ q\big] \\ g_m &= g[k, l, p, q, m], \quad m \in \{0, 1\} \end{aligned}

The sampling points usually don't land on integer coordinates, so bilinear interpolation is used. Each location reads out 225 correlations; drop the ring at the edge of the grid (to reduce interference from the background), take the mean, and that's the detection score for this location.

In other words, if every cell of the class image, once moved over, lands near features that look a lot like that cell, this location very likely holds the target product.

The localization box is simpler still, just the bounding rectangle spanned by the minimum and maximum coordinates of these 225 sampling points.

So from start to finish, OS2D never produces a "class-agnostic object box". Every box is the result of moving some class image over, which is also why it can box a split cup of yogurt as a single product.

Two Kinds of Transformation

TransformNet's output comes in two versions:

  • V1: P=4P = 4, translation and scaling only. The mapping goes from the class image to the shelf, so the annotated boxes serve directly as the supervision signal, allowing full supervision.
  • V2: P=6P = 6, a full affine transformation, in the same direction as Rocco's original design. The upside is that Rocco's released weights can be loaded directly.

Unexpectedly, V2 works with Rocco's weights loaded and no training on retail data at all. The authors' guess is that because TransformNet takes the correlation tensor rather than the features themselves, it isn't very sensitive to which feature extractor sits in front of it.

The authors also note that even when given a full affine transformation, the model still learns only translation and scaling, judging from the visualized results.

Training

Shelf photos are high-resolution and crowded with objects, so they can't be shrunk to a fixed size as in ordinary detection; otherwise products get squashed or shrink to a few pixels. During training, each step randomly picks a scale and a location and resamples a fixed-size training patch. The class images for each batch are the annotated classes in that patch, plus a few randomly drawn classes as negatives.

The loss has two terms, recognition and localization:

ℓrecpos(s)=max⁡(mpos−s,0)ℓrecneg(s)=max⁡(s−mneg,0)\begin{aligned} \ell^{\text{pos}}_{\text{rec}}(s) &= \max(m_{\text{pos}} - s, 0) \\ \ell^{\text{neg}}_{\text{rec}}(s) &= \max(s - m_{\text{neg}}, 0) \end{aligned}

s∈[−1,1]s \in [-1, 1] is the recognition score; localization uses the standard smooth L1.

Positives and negatives are wildly imbalanced. The authors started with Faster R-CNN's recipe of three hardest negatives per positive, with a contrastive loss; later they switched to the ranked list loss (RLL). RLL gives more weight to negatives with larger losses, with weights proportional to exp⁡(T⋅ℓ)\exp(T \cdot \ell). The temperature TT is hard to tune by hand, so the authors let each image–class pair pick its own TT, such that the negative with the largest loss gets 10310^3 times the weight of a negative sitting right on the margin.

Another design is called target remapping. Ordinary detectors decide positives and negatives by the IoU between anchor boxes and annotated boxes, but OS2D processes each training patch at a single scale, so many annotated objects have no anchor box of matching size at all, and positives end up very sparse.

The authors' fix is to separate the two decisions. The anchor box IoU only sets the regression target for localization; positives and negatives for classification are decided after the model outputs its boxes, using the IoU between the output box and the annotated box, with above 0.8 positive and below 0.4 negative. The trick only makes sense for OS2D because OS2D's boxes have been transformed and have already moved away from their original anchor positions.

Discussion

Re-annotating GroZi-3.2k

The main data is GroZi-3.2k, 680 photos from 5 stores. The original annotations often put several similar products in a single box, and there was no strict rule about what counts as the same class. The authors re-annotated everything: one box per product, only identical products count as the same class, and class images come from the original annotations or from searching the product name online. Objects whose class even a human can't determine are marked difficult.

The result is 1,063 classes and 8,921 objects. The authors picked 185 classes and removed all 84 photos containing them from the training set; the 622 objects of these 185 classes in those photos form val-new-cl, the main validation set, and the 518 objects in the same photos that belong to training classes form val-old-cl.

The authors also collected three test sets, shot under conditions different from GroZi's and with entirely new classes:

  • dairy: 12 images, 166 classes of dairy products, 786 objects.
  • paste-f: 91 images, 259 classes of toothpaste and related products, 4,861 objects; products may lie sideways or upside down.
  • paste-v: a subset of paste-f, with wrongly oriented objects relabeled as difficult.

The metric is PASCAL VOC [email protected].

Against the Baselines

The main opponent is a "detector plus retrieval" combination. The detector is Faster R-CNN with FPN, trained with all products as a single class, and it reaches an mAP of 96.4 on the validation images; the retrieval system uses GeM pooling from Radenović et al. The other baseline is a sliding window, which uses the same feature extractor but drops TransformNet and convolves the class features directly over the shelf; the "target AR" version keeps the class image's original aspect ratio.

Methodval-old-clval-new-cldairypaste-vpaste-f
Class detector (trained classes only)87.1————
Detector + retrieval87.686.870.044.340.0
Sliding window, target AR72.571.363.065.145.9
Hsieh et al. (CoAE)91.188.257.232.627.6
OS2D V1-train89.188.770.561.948.8
OS2D V2-init (untrained)79.786.165.468.248.4
OS2D V2-train85.090.671.873.354.5

Source: Table 3 of the paper; numbers are mAP.

Start with the val-old-cl column. On the trained classes, the one-shot methods actually come out slightly ahead of the dedicated detector; the authors think GroZi doesn't have enough data to train a good multi-class detector.

The real test is new classes. On dairy and toothpaste the baselines fall off fast, down to 44.3 on paste-v; Hsieh et al.'s CoAE is the best on val-old-cl, but drops to the twenties and thirties on toothpaste. OS2D V2-train is the highest in every new-class column, with 73.3 on paste-v.

The sliding-window row is interesting too. It has no geometric transformation at all, just keeps the class image's aspect ratio, and still gets 65.1 on paste-v, far above the 44.3 of detector plus retrieval. The authors admit this baseline is surprisingly good, but once learned transformations are added, every column goes up further.

Original Fig. 3: three sets of shelf photos, from left to right dairy, val-new-cl and paste-f. In each set, the class images and class numbers are at the top, the baseline's detections in the middle and OS2D's at the bottom; green boxes are correct detections and red boxes wrong ones. In dairy, the baseline has a red box that merges two products; in the middle set, val-new-cl, OS2D has a red box that covers only half of a jar; for the toothpaste lying sideways in paste-f, OS2D has visibly more green boxes than the baseline.
Original Fig. 3, Osokin et al., from PDF page 14, arXiv license, scholarly quotation.

From the figure, the authors draw out two reasons the baselines lose. The detector doesn't know what it's looking for, so it easily cuts one product into parts or merges several products into one; the retrieval system ignores the geometric relations among matched points, so it can't separate two different products built from similar parts.

OS2D has its own failure mode. The jam jar in the middle set is a cylinder; turned at an angle, the class image can match only half of the jar, so the box covers only half. Using the bounding rectangle of a set of matched points as the box puts it at a disadvantage when products rotate in 3D.

In paste-f, some products lie sideways and some stand upright, and CNN features aren't rotation-invariant, so the authors give every method three extra rotated versions of each class image, at 90, 180 and 270 degrees.

Ablations

On the V1 track, switching from the contrastive loss to RLL raises val-new-cl from 81.8 to 85.7, and adding target remapping takes it to 87.0. The authors say that besides raising the score, the two changes also stabilized training; the original model overfit quickly.

Training V2 is more troublesome. The localization loss and the recognition loss send TransformNet gradients that fight each other; the authors couldn't balance them, and in the end simply set the localization loss to zero and trained the transformation on the recognition loss alone.

The feature extractor's initialization matters a lot. GroZi is small, so a ResNet-50 trained from scratch gets only 59.6 for V1, and V2-init just 2.0. Weights pretrained for ImageNet classification or Google Landmarks retrieval work best; weights pretrained for COCO detection are actually worse. The authors guess that detection models learn to ignore color, and color is exactly an important cue for telling apart flavors of the same product.

Speed

On a GTX 1080Ti, with an image pyramid at evaluation time, feature extraction for the shelf image takes 0.46 seconds per image; the matching, transformation and scoring after that take 0.052 to 0.064 seconds per image per class, of which TransformNet itself accounts for 0.020 seconds.

Class-image features only need to be computed once and can be shared across the whole dataset. But the second half scales with the number of classes: to find a hundred products in one shelf photo, the matching alone takes five or six seconds. With many classes, this part outweighs feature extraction.

Back on ImageNet

The appendix has an experiment few people mention. Following RepMet's setup, the authors ran a 5-way 1-shot evaluation on ImageNet, the semantic-class setting commonly used for one-shot detection at the time.

OS2D doesn't work there at all. The authors' own detector-plus-retrieval baseline gets 60.4 AP, higher than the 56.9 RepMet reported; OS2D V2-init gets only 21.8, and further training brings no improvement.

The authors take this gap as evidence for their argument that semantic classes and instance-level recognition are two different things. Read from another angle, it also marks out OS2D's limits clearly. What it's good at is "finding the exact same thing".

This experiment comes with a footnote. The authors found that if the backbone used PyTorch's official weights, trained on all ImageNet classes, the baseline rose to 73.0, because the test classes had already been seen in pretraining. So they retrained a ResNet-101 that excludes the test classes.

Using It in Practice

The code is public on GitHub, and the authors were still answering issues at the end of 2023. Leaf through the threads and you'll find people getting stuck in much the same places.

The most common is scale. Someone ran the demo on the same images as Fig. 3 and couldn't find the products; the authors replied that you either build a scale pyramid of the class image or first resize the class image to roughly the size of the product on the shelf, and attached a successful result after the adjustment (issue #28, June 2022).

Next come false positives and thresholds. The authors' suggestions include raising the score threshold and tuning NMS; they also point out that OS2D isn't invariant to horizontal flips of the class image, and that several look-alike classes can be merged into one first, with a separate classifier trained to tell them apart (issue #7, issue #1, 2020).

Slow evaluation is another frequent complaint; one user reported 50 minutes for 84 validation images. The cause is the image pyramid used at evaluation, with run time roughly proportional to the total pixel count across all pyramid levels; training uses random scales and carries no such load (issue #68, December 2023).

All three come from the same root. At each location OS2D compares against a single fixed-size class image, so scale has to be covered by an external pyramid, and classes have to be computed one at a time.

Conclusion

OS2D replaces the classic pipeline of "descriptor matching plus geometric verification" with dense learned features, a feed-forward transformation network and bilinear sampling, so the whole path is differentiable. There's no "generic object detector" anywhere in it; every box is carried over from a class image, so with split-cup yogurt or a row of new toothpastes, it holds up better than systems that cut boxes first and recognize them afterwards.

The evidence also maps out its range. On instance-level data like GroZi and toothpaste, it beats every baseline on new classes; on ImageNet's semantic classes, it loses to a simple detector plus retrieval. Run time grows linearly with the number of classes, scale depends on a pyramid, and boxes for products rotated in 3D are off.

For shelves, "one front photo per product" is a very practical onboarding process, and OS2D shows that this photo really can be used directly to find the goods. Searching for thousands of products in a store at the same time, though, first requires solving the compute cost that comes with the number of classes.