Visual Similarity Search: Finding and Annotating Objects from One Example
Visual similarity search takes one example, such as a box drawn around a bolt, and looks for other places that resemble it. Inside a single image this means comparing the example's features with the features at every position of the target, turning the result into a similarity map, and picking the peaks. It needs no training run and no class list.
It also returns exactly what the name says: similar regions. Not "the same object", not "the same class". The experiment below shows a second copy of the same drawing scoring less than 1, a recoloured version scoring almost as high as the copy, and an object with a piece missing passing a plausible threshold.
Three tasks that look alike
| Task | Question | Unit compared | Output |
|---|---|---|---|
| Image retrieval | Which images are like this one? | One vector per image | Ranked list of images |
| Object detection | Where are instances of these classes? | Learned class head | Boxes with class and score |
| Region similarity | Where does something like this crop appear? | Patches or windows against an example | Positions or boxes in the target, with similarity scores |
Retrieval can say that two photographs both show a workbench full of fasteners without telling you where any of them is. A detector can locate "bolt" only if it was trained for it. Region similarity sits in between: it localises, from one example, without knowing a name.
From pixels to a grid of descriptors
A vision transformer cuts an image into square patches, 14 by 14 pixels for DINOv2, and produces one vector for each. A 560 by 336 input therefore gives a grid of 24 rows by 40 columns of descriptors, each with 384 numbers for the small model, plus one class token that summarises the whole image.
That grid is the dense feature map. DINOv2 and DINOv3 are trained without labels, and their patch descriptors tend to be alike for parts that look alike or play a similar role. Two properties are easy to forget:
- A patch descriptor is not a description of those 196 pixels alone. Through attention it also depends on the rest of the input and on its position.
- The grid is coarse. An object smaller than a patch shares its descriptor with whatever surrounds it.
How many patches does your object cover?
Check this before anything else. If an image of width W pixels is resized to width W_in for the model, an object w pixels wide covers
patches = w * (W_in / W) / 14
patches along that side. For a 60 pixel object in a 4000 pixel wide photograph:
| Processing | Object width at the model | Patches along that side |
|---|---|---|
| Whole image resized to 518 | 60 × 518 / 4000 = 7.8 px | 0.55 |
| Whole image resized to 1036 | 15.5 px | 1.1 |
| 448 px tile fed at 448 (no resize) | 60 px | 4.3 |
| 224 px tile upscaled to 448 | 120 px | 8.6 |
Below one patch there is nothing to match. Cutting the image into overlapping tiles restores resolution at the price of more forward passes, and it limits what each patch can see of its surroundings, so scores near tile borders and across tile sizes need care.
Normalisation, dot product and cosine
For two feature vectors a and b with d components:
cos(a, b) = dot(a, b) / (norm(a) * norm(b))
where dot(a, b) is the sum of the products of matching components and norm(a) is the square root of dot(a, a). If every descriptor is first divided by its own norm (L2 normalisation), the dot product is the cosine, so a similarity map is one matrix multiplication. For unit vectors, squared Euclidean distance is 2 - 2 * cos(a, b), so ranking by distance and ranking by cosine give the same order.
Cosine ignores length and keeps direction. Edit the vectors below and note that doubling one of them changes the dot product but not the cosine.
Cosine similarity of two small descriptors
A table of two four component vectors with their products, unit length versions, dot product, norms and cosine similarity, showing that cosine depends on direction rather than length.
a = example patch, b = target patch. cosine(a, b) = a·b / (‖a‖ ‖b‖)
| k | a | b | a×b | a/‖a‖ | b/‖b‖ |
|---|---|---|---|---|---|
| 0 | 6 | 0.667 | 0.775 | ||
| 1 | 1 | 0.333 | 0.258 | ||
| 2 | 0 | 0.000 | 0.258 | ||
| 3 | 4 | 0.667 | 0.516 |
- dot product a·b
- 11
- norm ‖a‖
- 3.0000
- norm ‖b‖
- 3.8730
- cosine similarity
- 0.9467
Dot product 11, norms 3.0000 and 3.8730: cosine similarity 0.9467.
Turning one example into a similarity map
Let f(p) be the unit descriptor of target position p, and let the example crop cover the descriptors e(1) to e(n). Three common constructions:
- Mean descriptor. Average the example's descriptors, renormalise to get
m, and score each position withS(p) = dot(m, f(p)). Compact and tolerant of layout changes, but any background inside the crop is averaged in. - Template matching. Keep the example's grid and slide it:
S(o) = (1/n) * sum over cells c of dot(e(c), f(o + c))for each placemento. Layout counts, so a rearranged or rotated object scores lower. - Nearest neighbours. Match each target patch to its most similar example patch, optionally requiring that the match also works backwards, from the reference image into the example region.
From a reference crop to reviewed candidates
A reference crop and a target image each go through the same backbone to produce patch descriptors. Their comparison gives a similarity map, which is normalised, thresholded, reduced to peaks without overlap and sent to human review.
| box | arrows to |
|---|---|
| Reference crop | Example descriptors |
| Example descriptors | Similarity map |
| Similarity map | Normalise and threshold |
| Normalise and threshold | Peaks, overlap removal |
| Peaks, overlap removal | Review candidates |
| Review candidates | — |
| Target image | Dense feature map |
| Dense feature map | Similarity map |
8 boxes and 7 arrows. No box is selected.
From a map to candidates
A raw cosine has no natural cut-off. In one image the whole background may sit near 0.3, in another near 0.7. One remedy is to rescale each image's scores between its own typical value and the example's score against itself:
r = clip((s - median) / (s_self - median), 0, 1)
Here s is a position's score, median is the middle score over the target image, s_self is the example compared with itself, and clip limits the result to the range 0 to 1. With invented numbers:
Raw score s |
Image median | Self score | Relative score r |
|---|---|---|---|
| 0.80 | 0.30 | 0.95 | 0.50 / 0.65 = 0.769 |
| 0.80 | 0.70 | 0.95 | 0.10 / 0.25 = 0.400 |
The same cosine means different things in the two images. The rescaled value is not a probability either, and since the median depends on what else is in the picture, it is not comparable across images.
After thresholding, keep local maxima, discard boxes that overlap a stronger one beyond a chosen intersection over union (non-maximum suppression), exclude the reference itself, or group neighbouring positions into regions if you want shapes rather than fixed-size boxes.
Experiment: a scene with known distractors
To see what the scores do, draw a scene where the answer is known. The reference is a dark ring with a red cross, 84 pixels (6 by 6 patches). The scene also holds an identical copy, a blue cross, a version rotated by 45 degrees, a ring with no cross, a cross with no ring, a square frame and a 60 percent copy. The drawings have gaps, so the background shows through them. The same scene is built twice, on light noise and with random clutter behind it.
Environment of the recorded output: Python 3.13.12, PyTorch 2.15.0, transformers 5.24.1, Pillow 13.0.0, NumPy 2.5.5, facebook/dinov2-small at the pinned revision, one NVIDIA GeForce RTX 5080, run on 2026-11-27.
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image, ImageDraw
from transformers import AutoModel
MODEL, REVISION = "facebook/dinov2-small", "ed25f3a31f01632728cabb09d1542f84ab7b0056"
PATCH = 14
device = "cuda" if torch.cuda.is_available() else "cpu"
model = AutoModel.from_pretrained(MODEL, revision=REVISION).to(device).eval()
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
STD = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
def patch_features(image):
"""Unit patch descriptors [rows, cols, 384] of an image whose sides are multiples of 14."""
pixels = torch.from_numpy(np.asarray(image, np.float32) / 255).permute(2, 0, 1)
pixels = ((pixels - MEAN) / STD)[None].to(device)
with torch.inference_mode():
tokens = model(pixel_values=pixels).last_hidden_state[0, 1:] # drop the class token
return F.normalize(tokens, dim=-1).reshape(image.height // PATCH, image.width // PATCH, -1).cpu()
def sprite(ring=True, cross=True, color=(200, 40, 40), angle=0, square=False, size=84):
s = 336 # draw large, then shrink for smooth edges
image = Image.new("RGBA", (s, s), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
if ring:
(draw.rectangle if square else draw.ellipse)([16, 16, s - 16, s - 16], outline=(50, 50, 55, 255), width=44)
if cross:
draw.rectangle([s // 2 - 20, 40, s // 2 + 20, s - 40], fill=color + (255,))
draw.rectangle([40, s // 2 - 20, s - 40, s // 2 + 20], fill=color + (255,))
return image.rotate(angle, resample=Image.BICUBIC).resize((size, size), Image.LANCZOS)
# name: (column, row, sprite), positions in patch units
OBJECTS = {"reference": (2, 2, sprite()), "identical copy": (11, 2, sprite()),
"blue cross": (20, 2, sprite(color=(40, 70, 200))), "rotated 45": (29, 2, sprite(angle=45)),
"ring, no cross": (2, 13, sprite(cross=False)), "cross, no ring": (11, 13, sprite(ring=False)),
"square frame": (20, 13, sprite(square=True)), "60% size": (30, 14, sprite(size=50))}
def scene(clutter=False):
noise = np.random.default_rng(0).normal(205, 8, (336, 560, 1)).repeat(3, axis=2)
image = Image.fromarray(np.clip(noise, 0, 255).astype(np.uint8))
if clutter:
rng, draw = np.random.default_rng(1), ImageDraw.Draw(image)
for _ in range(500):
x, y = int(rng.integers(0, 540)), int(rng.integers(0, 320))
w, h = int(rng.integers(6, 24)), int(rng.integers(6, 24))
color = tuple(int(v) for v in rng.integers(40, 230, 3))
shape = draw.ellipse if rng.random() < 0.5 else draw.rectangle
shape([x, y, x + w, y + h], outline=color, width=3)
for column, row, item in OBJECTS.values():
image.paste(item, (column * PATCH, row * PATCH), item)
return image
def template_map(features, template):
"""Mean cell-by-cell cosine of the template at every placement."""
h, w = template.shape[:2]
windows = features.unfold(0, h, 1).unfold(1, w, 1) # [R, C, 384, h, w]
return (windows * template.permute(2, 0, 1)).sum(2).mean((-1, -2))
def relative(score, scores, self_score):
median = scores.median().item()
return min(1.0, max(0.0, (score - median) / (self_score - median)))
column, row, _ = OBJECTS["reference"]
for clutter in (False, True):
features = patch_features(scene(clutter))
scores = template_map(features, features[row:row + 6, column:column + 6])
print("cluttered" if clutter else "plain", f"background: median placement score {scores.median().item():.3f}")
for name, (c, r, _) in OBJECTS.items():
best = scores[max(0, r - 2):r + 3, max(0, c - 2):c + 3].max().item() # best placement nearby
print(f" {name:15s} cosine {best:.3f} relative {relative(best, scores, scores[row, column].item()):.3f}")
plain background: median placement score 0.514
reference cosine 1.000 relative 1.000
identical copy cosine 0.950 relative 0.898
blue cross cosine 0.934 relative 0.864
rotated 45 cosine 0.863 relative 0.719
ring, no cross cosine 0.769 relative 0.524
cross, no ring cosine 0.647 relative 0.274
square frame cosine 0.677 relative 0.336
60% size cosine 0.610 relative 0.199
cluttered background: median placement score 0.514
reference cosine 1.000 relative 1.000
identical copy cosine 0.838 relative 0.666
blue cross cosine 0.799 relative 0.586
rotated 45 cosine 0.781 relative 0.548
ring, no cross cosine 0.732 relative 0.449
cross, no ring cosine 0.562 relative 0.099
square frame cosine 0.603 relative 0.184
60% size cosine 0.569 relative 0.113
Reading the numbers:
- The identical copy does not score 1. The drawing is the same, but the noise showing through its gaps and around it is not, and a descriptor also depends on its position and on the rest of the picture. A threshold near 1 would miss real duplicates.
- Colour barely counted. On the plain background the blue cross is within 0.02 in cosine of the identical copy. If red and blue handles are different part numbers in your catalogue, similarity will not keep them apart.
- A missing part passed. On the plain background the empty ring has a relative score above 0.5. It is the high-scoring wrong match: similar outline, wrong object.
- Scale cost the most, rotation less. The 60 percent copy scores lowest on the plain background; the 45 degree version fell below the blue one. Nothing here searches over scales or angles.
- The background moved everything. With clutter behind the same objects, the identical copy drops below what the rotated copy scored on the plain background. The median barely changed; the descriptors themselves did, because clutter shows through the gaps of the drawings, including the reference, and patches also see their surroundings.
The same objects score differently on a different background
Relative similarity of eight drawn objects against one reference on a plain and a cluttered background. Scores fall on the cluttered background, and the ring without a cross is above 0.5 on the plain one but below it with clutter.
plain background (circles)cluttered (squares, dashed)
plain background, values at or above the threshold: 5 of 8 (ref, copy, blue, rot 45, ring)
cluttered, values at or above the threshold: 4 of 8 (ref, copy, blue, rot 45)
| object | plain background | cluttered | at or above threshold |
|---|---|---|---|
| ref | 1 | 1 | plain background, cluttered |
| copy | 0.898 | 0.666 | plain background, cluttered |
| blue | 0.864 | 0.586 | plain background, cluttered |
| rot 45 | 0.719 | 0.548 | plain background, cluttered |
| ring | 0.524 | 0.449 | plain background |
| cross | 0.274 | 0.099 | none |
| square | 0.336 | 0.184 | none |
| 60% | 0.199 | 0.113 | none |
Threshold 0.5. plain background is at or above it at 5 of 8 (ref, copy, blue, rot 45, ring). cluttered is at or above it at 4 of 8 (ref, copy, blue, rot 45).
Looking at the map itself
The table of per-object scores hides the shape of the map. Computing the relative score of every placement gives one value for each position where the 6 by 6 template fits:
features = patch_features(scene())
scores = template_map(features, features[row:row + 6, column:column + 6])
heat = ((scores - scores.median()) / (1 - scores.median())).clamp(0, 1) # the reference scores 1 by construction
print(list(heat.shape), int((heat >= 0.5).sum()), "placements reach 0.5")
[19, 35] 20 placements reach 0.5
Relative similarity of the reference at every placement
A grid of 19 rows by 35 columns of relative similarity for the plain scene. The brightest cell is the reference at the upper left, with further bright blobs along the top for the copy, the blue and the rotated objects, and a weaker one at lower left for the empty ring.
relative score (cells below the threshold are dimmed)
0 (dark)1 (light)
Left to right: patch column 0 to 34. Top to bottom: patch row 0 to 18.
- selected cell
- patch row 0, patch column 0
- relative score there
- 0.144
- relative score: cells counted
- 20 of 665
| row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.144 | 0.211 | 0.246 | 0.245 | 0.148 | 0.143 | 0.175 | 0.151 | 0.121 | 0.108 | 0.19 | 0.202 | 0.195 | 0.144 | 0.107 | 0.144 | 0.09 | 0.052 | 0.07 | 0.141 | 0.189 | 0.17 | 0.105 | 0.102 | 0.141 | 0.124 | 0.103 | 0.107 | 0.156 | 0.169 | 0.123 | 0.08 | 0 | 0 | 0 |
| 1 | 0.258 | 0.44 | 0.582 | 0.477 | 0.279 | 0.227 | 0.251 | 0.238 | 0.227 | 0.262 | 0.443 | 0.556 | 0.431 | 0.266 | 0.173 | 0.2 | 0.173 | 0.147 | 0.193 | 0.379 | 0.53 | 0.383 | 0.223 | 0.181 | 0.22 | 0.195 | 0.161 | 0.219 | 0.376 | 0.473 | 0.33 | 0.159 | 0.018 | 0 | 0 |
| 2 | 0.281 | 0.61 | 1 | 0.65 | 0.359 | 0.312 | 0.375 | 0.358 | 0.323 | 0.34 | 0.607 | 0.898 | 0.582 | 0.303 | 0.235 | 0.301 | 0.283 | 0.252 | 0.263 | 0.537 | 0.863 | 0.533 | 0.287 | 0.263 | 0.321 | 0.296 | 0.225 | 0.339 | 0.531 | 0.718 | 0.499 | 0.178 | 0.009 | 0 | 0 |
| 3 | 0.256 | 0.469 | 0.642 | 0.52 | 0.335 | 0.241 | 0.289 | 0.267 | 0.234 | 0.288 | 0.463 | 0.578 | 0.472 | 0.289 | 0.211 | 0.262 | 0.235 | 0.219 | 0.232 | 0.417 | 0.559 | 0.417 | 0.258 | 0.205 | 0.265 | 0.244 | 0.207 | 0.286 | 0.433 | 0.516 | 0.364 | 0.152 | 0 | 0 | 0 |
| 4 | 0.146 | 0.24 | 0.294 | 0.277 | 0.183 | 0.126 | 0.154 | 0.142 | 0.091 | 0.121 | 0.192 | 0.212 | 0.211 | 0.115 | 0.085 | 0.113 | 0.102 | 0.075 | 0.072 | 0.18 | 0.219 | 0.187 | 0.103 | 0.066 | 0.1 | 0.101 | 0.069 | 0.09 | 0.17 | 0.192 | 0.149 | 0.038 | 0 | 0 | 0 |
| 5 | 0.031 | 0.066 | 0.123 | 0.102 | 0.043 | 0.05 | 0.045 | 0.04 | 0.023 | 0.008 | 0.037 | 0.092 | 0.081 | 0.006 | 0.019 | 0.029 | 0.023 | 0 | 0 | 0.04 | 0.096 | 0.053 | 0.01 | 0.012 | 0.008 | 0 | 0 | 0.003 | 0.012 | 0 | 0.008 | 0 | 0 | 0 | 0 |
| 6 | 0 | 0.048 | 0.073 | 0.07 | 0.053 | 0.019 | 0 | 0 | 0 | 0 | 0.033 | 0.031 | 0.031 | 0 | 0 | 0 | 0 | 0 | 0 | 0.036 | 0.048 | 0.03 | 0.02 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 7 | 0 | 0.034 | 0.1 | 0.055 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031 | 0.04 | 0.007 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 8 | 0 | 0 | 0.057 | 0.023 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 9 | 0 | 0 | 0.005 | 0.003 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 10 | 0 | 0 | 0.023 | 0.023 | 0.005 | 0.02 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 11 | 0.059 | 0.116 | 0.139 | 0.133 | 0.086 | 0.098 | 0.075 | 0 | 0 | 0 | 0 | 0.017 | 0.006 | 0 | 0 | 0 | 0 | 0.009 | 0.051 | 0.097 | 0.109 | 0.091 | 0.031 | 0 | 0.022 | 0.028 | 0.008 | 0 | 0.056 | 0.055 | 0 | 0 | 0 | 0 | 0 |
| 12 | 0.122 | 0.267 | 0.349 | 0.302 | 0.171 | 0.107 | 0.118 | 0.041 | 0.009 | 0.023 | 0.107 | 0.166 | 0.125 | 0.062 | 0.018 | 0.007 | 0.007 | 0.057 | 0.14 | 0.233 | 0.259 | 0.214 | 0.114 | 0.063 | 0.04 | 0.055 | 0.038 | 0.062 | 0.184 | 0.138 | 0.035 | 0 | 0 | 0 | 0 |
| 13 | 0.147 | 0.359 | 0.524 | 0.382 | 0.2 | 0.14 | 0.145 | 0.136 | 0.083 | 0.098 | 0.201 | 0.273 | 0.206 | 0.13 | 0.084 | 0.068 | 0.056 | 0.095 | 0.184 | 0.289 | 0.335 | 0.275 | 0.153 | 0.101 | 0.067 | 0.104 | 0.09 | 0.119 | 0.199 | 0.148 | 0.066 | 0 | 0 | 0 | 0 |
| 14 | 0.094 | 0.254 | 0.332 | 0.27 | 0.156 | 0.091 | 0.1 | 0.05 | 0.014 | 0.029 | 0.085 | 0.144 | 0.127 | 0.06 | 0.025 | 0.016 | 0.023 | 0.063 | 0.138 | 0.227 | 0.281 | 0.229 | 0.109 | 0.062 | 0.026 | 0.035 | 0 | 0 | 0.079 | 0.06 | 0 | 0 | 0 | 0 | 0 |
| 15 | 0 | 0.019 | 0.041 | 0.05 | 0.011 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031 | 0.083 | 0.048 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 17 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 18 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
Cell patch row 0, patch column 0: relative score 0.144 (below the threshold). Cells at or above 0.5: relative score 20 of 665.
The bright regions are blobs, not single cells: neighbouring placements share most of their patches. That is why candidate selection needs peak picking with overlap removal, or each object would be reported several times.
Whole object or part?
A small crop asks a different question. Here the template is only the 2 by 2 patches at the hub of the reference cross, and each object gets its best placement inside its own footprint:
hub = features[row + 2:row + 4, column + 2:column + 4]
scores = template_map(features, hub)
for name, (c, r, item) in OBJECTS.items():
cells = item.width // PATCH
best = scores[r:r + cells - 1, c:c + cells - 1].max().item()
print(f"{name:15s} cosine {best:.3f} relative {relative(best, scores, scores[row + 2, column + 2].item()):.3f}")
reference cosine 1.000 relative 1.000
identical copy cosine 0.972 relative 0.959
blue cross cosine 0.955 relative 0.932
rotated 45 cosine 0.930 relative 0.895
ring, no cross cosine 0.463 relative 0.198
cross, no ring cosine 0.869 relative 0.804
square frame cosine 0.899 relative 0.849
60% size cosine 0.714 relative 0.573
At a 0.5 threshold the part query accepts everything that has a hub, including the bare cross and the square frame, and rejects the empty ring (0.198). The whole-object query did the reverse for the bare cross and the empty ring: it rejected the cross (0.274) and let the ring through (0.524). Neither is better. They answer different questions.
A whole-object query and a part query on one scene
Two sets of relative scores for eight objects. The hub query scores the cross without a ring, the square frame and the small copy far higher than the whole object query does, and scores the empty ring far lower.
whole object (circles)hub only (squares, dashed)
whole object, values at or above the threshold: 5 of 8 (ref, copy, blue, rot 45, ring)
hub only, values at or above the threshold: 7 of 8 (ref, copy, blue, rot 45, cross, square, 60%)
| object | whole object | hub only | at or above threshold |
|---|---|---|---|
| ref | 1 | 1 | whole object, hub only |
| copy | 0.898 | 0.959 | whole object, hub only |
| blue | 0.864 | 0.932 | whole object, hub only |
| rot 45 | 0.719 | 0.895 | whole object, hub only |
| ring | 0.524 | 0.198 | whole object |
| cross | 0.274 | 0.804 | hub only |
| square | 0.336 | 0.849 | hub only |
| 60% | 0.199 | 0.573 | hub only |
Threshold 0.5. whole object is at or above it at 5 of 8 (ref, copy, blue, rot 45, ring). hub only is at or above it at 7 of 8 (ref, copy, blue, rot 45, cross, square, 60%).
| Choice | Finds | Misses or confuses | Use when |
|---|---|---|---|
| Whole-object crop | Items with the same overall layout | Rotated, resized or occluded items; passes near-complete wrong ones | Counting repeated, similarly posed objects |
| Part or detail crop | Anything containing that detail | Cannot say which whole object it belongs to | Locating a feature such as a screw head or logo |
| Tight box | Less background in the descriptor | Very small crops cover few patches | Default |
| Several examples | More appearance variation | Averaging dissimilar examples blurs the descriptor | Objects that vary in pose or lighting |
If you want the object that contains the example rather than the example-sized region, you need grouping on top of similarity. INSID3 is one published, training-free method: it takes DINOv3 features, removes a position-dependent component from them for cross-image matching, clusters the target patches and keeps clusters that agree with the reference in both matching directions, producing a segmentation mask.
A real photograph
Drawn shapes are not photographs. The second test uses the CC0 cat photograph distributed with scikit-image (skimage.data.chelsea(), saved as chelsea.png). The example is a box around one eye, pooled into a mean descriptor, and the question is where else it responds.
photo = Image.open("chelsea.png").convert("RGB") # 451 x 300
sx, sy = 448 / photo.width, 294 / photo.height
features = patch_features(photo.resize((448, 294), Image.BICUBIC)) # 21 x 32 patches
def cells(x1, y1, x2, y2):
"""Patch rows and columns whose centres fall inside a box given in original pixels."""
rows = [i for i in range(21) if y1 * sy <= i * PATCH + 7 < y2 * sy]
columns = [j for j in range(32) if x1 * sx <= j * PATCH + 7 < x2 * sx]
return rows, columns
rows, columns = cells(133, 83, 210, 148) # the eye on the left of the picture
other_rows, other_columns = cells(294, 108, 347, 166) # the other eye, used only to score the result
example = F.normalize(features[rows][:, columns].reshape(-1, features.shape[-1]).mean(0), dim=0)
similarity = features @ example
print(f"median {similarity.median().item():.3f}, example's own patches {similarity[rows][:, columns].mean().item():.3f}")
masked = similarity.clone()
masked[rows[0] - 1:rows[-1] + 2, columns[0] - 1:columns[-1] + 2] = -1 # hide the example itself
best = torch.topk(masked.flatten(), 12)
for value, index in zip(best.values.tolist(), best.indices.tolist()):
i, j = divmod(index, 32)
where = "other eye" if i in other_rows and j in other_columns else "elsewhere"
print(f"{value:.3f} patch row {i:2d} col {j:2d} {where}")
median 0.251, example's own patches 0.876
0.861 patch row 10 col 23 other eye
0.856 patch row 8 col 23 other eye
0.854 patch row 10 col 22 other eye
0.852 patch row 9 col 21 other eye
0.838 patch row 10 col 21 other eye
0.836 patch row 9 col 23 other eye
0.827 patch row 11 col 22 other eye
0.821 patch row 8 col 22 other eye
0.805 patch row 9 col 24 other eye
0.790 patch row 7 col 23 elsewhere
0.742 patch row 11 col 21 other eye
0.722 patch row 9 col 22 other eye
The nine strongest responses outside the example all fall in the other eye, as do eleven of the top twelve, far above the image median. One easy photograph is an illustration of the mechanism, not an accuracy estimate: change the photograph, the box or the model size and measure again.
Similar is not the same instance
A cosine score carries no identity. Two bolts from one batch are, as far as appearance goes, interchangeable, so a high score cannot tell you that this is the bolt you saw before. In the other direction, one individual object can score lower against itself after turning or changing scale, as the drawn objects above did. Keep three claims apart: looks alike (what similarity measures), same class (a labelling decision with rules) and same individual (which needs other evidence such as position over time, a serial mark or a tracker).
Using similarity for annotation
Similarity search is a proposal generator. A sound loop:
- Draw a tight example. Check that it covers several patches at the model's input size.
- Rank candidates and review them from the top. Accept, adjust or reject each one.
- Scan the image for misses: nothing in a candidate list shows what was not found.
- Choose any automatic threshold on images you have labelled by hand, and report precision (accepted candidates that are right) and recall (true objects found) there.
- Never assign a class from similarity alone where the classes differ by colour, size or a small part.
Two numbers summarise a ranked list on a labelled test image. Precision at k is the share of the top k candidates that are wanted objects. Recall at k is the share of all wanted objects that appear among those k. Report both on images that contain look-alikes, and on at least one image that contains no true instance at all: a ranking has a first entry whether or not the object is there.
The review decisions, and how to measure a correction with IoU and Dice, are covered in AI-assisted image annotation.
To compare whole images instead of regions, for deduplication or retrieval, use one vector per image; and the same cosine over embeddings is a common way to build neighbour graphs, as in the vision graph recipes.
Similarity tools in Anastig
Disclosure: the author of this article is also involved in building Anastig.
Anastig is an independent, early-access visual AI platform, not part of TGraphX (overview on this site). As of 2026-11-27 several different things there involve "similarity", and they should not be merged:
| Tool | Runs | Compares | Returns | Access |
|---|---|---|---|---|
| Visual Similarity (DINOv2 Small, Base, Large), Beta | This device | Patch grids or a mean descriptor | Boxes | No account |
| INSID3 with DINOv3, experimental | This device | Dense tokens plus clustering | Polygons; boxes in part mode | No account |
| "Find similar - no AI", Beta | This device | Colour, gradients, grayscale template, or keypoints | Boxes | No account (may be restricted by the server) |
| Vision Lab similarity ranking | This device | One vector per image (DINOv2-Small, centre crop) | Ranked images, no location | No account |
| Worker Visual Similarity | GPU worker | Detector candidate crops plus dense recall | Boxes or masks | Paid Remote GPU by arrangement (the public Vision Lab page still lists Anastig-hosted inference as roadmap, so confirm access), or your own machine running Anastig (setup not documented) |
The first four are in Studio (try it from the annotation demo) or Vision Lab.
Per its published application, the browser Visual Similarity engine cuts the image into at most 36 tiles and computes unit patch descriptors for each. For a box on the current image it slides the reference's patch grid, and its mirror image, over the placements; for an uploaded example, several examples (up to three) or searches across other images it uses a mean descriptor. Both are rescaled with the median-relative formula above, with automatic floors of 0.5 and 0.45 respectively that your own threshold can replace (further matches of the first kind must also reach three quarters of the best one). One run covers at most eight loaded images; there is no dataset-wide index. Results enter a review queue where a label is required before accepting. Its whole-object versus part selector applies to INSID3 on this device, not to this DINOv2 engine; INSID3's whole-object mode returns the containing region, and its part mode switches to a DINOv2-Small template search. The first use downloads model weights (from about 24 MB for the smallest to about 600 MB for the large ones), and DINOv3 is distributed under Meta's own DINOv3 License.
The experiment above is not Anastig and is not evidence about its accuracy: no Anastig engine was run for this article, and no accuracy figures for these tools are available to quote.
What "this device" and "GPU worker" mean for your data is covered in local computer vision inference.
When you can name what you want rather than show it, see text-prompt object detection and segmentation.
What to remember
Similarity depends on the backbone, the crop, the aggregation, the rescaling and the rest of the picture. Treat a score as a ranking within one image under one setup, keep a person between candidates and labels, and test with distractors that differ in exactly the attribute you care about.
References
- Oquab et al., DINOv2: Learning Robust Visual Features without Supervision, 2023.
- DINOv2 official repository.
- Siméoni et al., DINOv3, 2025.
- Cuttano et al., INSID3: Training-Free In-Context Segmentation with DINOv3, 2026, with code.
- Dosovitskiy et al., An Image is Worth 16x16 Words, 2020.