Some original image labels are retained; figure captions and explanations are provided in English.

PART V · DEEP LEARNING

How Does Object Detection Work? YOLO, Faster R-CNN and DETR

Box representation, IoU and NMS introduce the detection approaches used by Faster R-CNN, YOLO and DETR. Small-screw inspection illustrates resolution loss, suppression of nearby objects and merging predictions from tiled images. Rotated boxes, conveyor counting and mAP interpretation connect detector outputs to the localisation and decision requirements of an application.

Article sectionsWhat is object detection, and how does it differ from classification?How is a bounding box represented?What is IoU, and how is it calculated?Why is NMS used, and when does it cause problems?How does Faster R-CNN work?Why is the YOLO family widely used?What do DETR and RT-DETR do differently?Why is small-object detection difficult?How are class imbalance and hard negatives handled?What does mAP measure, and what does it not measure?Rotated boxes and robotic applicationsNumerical scenario: counting parts on a conveyorWhich detector might be preferable, and when?Annotation box uncertainty in object detectionComparing anchor-based, anchor-free and query-based structuresWhat do box regression losses optimize?Planning tiled inference for small objectsStrengthening object detection with calibration and 3D orientation informationError analysis: was the object missed, suppressed or incorrectly matched?Frequently asked questionsImage sources

Object detection architectures, IoU, NMS, small objects, rotated boxes and industrial model selection. This guide examines the assumptions behind the method, the conditions in which it can be used, its failure modes and the decisions involved in field deployment.

What is object detection, and how does it differ from classification?

Short answer: Object detection estimates the location and class of objects or specific defect regions in an image. The output typically consists of a class label, a confidence score and a bounding box. For example, it is used to locate multiple products on a conveyor, inspect for a missing screw or mark clearly visible surface defects with boxes. However, a box does not show the actual boundary of a defect; segmentation may be needed to measure area and shape.

Classification asks, 'Is this image defective?' Object detection instead asks, 'Where in the image are the objects, how many are there, and which classes do they belong to?' This additional information is useful when objects are close together, partially overlap or appear at different sizes. In return, annotation costs and the complexity of the problem the model must solve increase.

Localization with boxesEstimating location together with a class labelimagebboxclassconfidenceConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Estimating location together with a class label

How is a bounding box represented?

The most common box formats are (x_min, y_min, x_max, y_max) and (x_center, y_center, width, height). Coordinates may be in pixels or normalized to the image dimensions. When converting between these formats, using the wrong order, origin or normalization can cause shifts of hundreds of pixels in deployment. The coordinate convention shared by the annotation tool and inference system must be clearly documented.

When the edges of a box are parallel to the image axes, an axis-aligned bounding box is used. If the object is tilted, a rotated box (oriented bounding box) may provide a tighter representation. However, not all rotated-box methods store angle signs, angular periods or edge order in the same way. Particularly for robotic grasping, it is important to remember that the box angle is not directly the robot's physical angle command.

The meaning of a box depends on the annotation guidelines: should it mark only the visible portion, the estimated full extent of an occluded object or the damaged area itself? If this decision is inconsistent throughout the training data, the model tries to learn multiple conflicting targets.

Real CC0 photograph of coins.
Real photograph / transformation: Real CC0 photograph of coins.

What is IoU, and how is it calculated?

Intersection over Union (IoU) is the ratio of the intersection area of two boxes to their union area. It ranges from 0 to 1. Two perfectly overlapping boxes have an IoU of 1, while boxes that do not intersect have an IoU of 0. IoU measures the similarity of box locations; on its own, it does not describe the correctness of the class label or the object's physical size. A shift of a few pixels can reduce IoU much more for small objects than for large ones.

For example, if a 20 × 20 pixel box shifts just 4 pixels to the right, the horizontal intersection decreases to 16 pixels. Even with the height unchanged, IoU becomes 320 / (400 + 400 − 320) = 0.667. The same 4-pixel shift produces a much smaller relative error for a 200 × 200 box. This is why small objects need to be evaluated separately.

Calculating IoURatio of intersection to unionbox AintersectionunionIoUConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Ratio of intersection to union
Interactive IoU calculation example

Reference box: x=52, y=49, width=75, height=64. Adjust the predicted box below. This calculates geometry only; it does not run a detector.

IoU: —

Why is NMS used, and when does it cause problems?

A detector may generate multiple candidate boxes for the same object. Non-Maximum Suppression (NMS) is a widely used family of operations that retains a high-confidence box and removes candidates that overlap it excessively. Conventional NMS operates according to a specified IoU threshold. However, for small products arranged side by side, the boxes of two real objects may overlap substantially. In that case, NMS may mistakenly remove one of the real objects.

Alternatives such as Soft-NMS soften the suppression behavior by reducing a candidate's score rather than setting it to zero. Some modern detectors instead use end-to-end matching or NMS-free output designs. Regardless of the approach, engineers must test how the final box count relates to the annotation count and the actual product geometry. A good mAP score does not mean there will be no counting errors on a densely stacked production line.

NMS behaviorBoxes very close to one another may be suppressedcandidatesoverlapsuppressionoutputConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Boxes very close to one another may be suppressed

How does Faster R-CNN work?

Faster R-CNN is a classic example of two-stage object detection. In the first stage, potential object regions are proposed; in the second, the class and box coordinates of those regions are refined. The Region Proposal Network (RPN) generates region proposals on the same feature maps. This arrangement allows candidate regions to be examined in greater detail, but overall latency and implementation complexity depend on the task and hardware.

The theoretical advantage of the two-stage approach is its ability to evaluate each candidate more selectively. Nevertheless, current single-stage detectors may produce similar or better results on some datasets. Describing Faster R-CNN as 'always more accurate but slower' is therefore a generalization. Such a judgment cannot guide a production decision without a direct comparison under the same conditions.

For small defect regions in particular, it is necessary to examine how the proposal mechanism operates, whether the anchor scales are appropriate and which feature pyramid levels are used. If candidate generation fails, the subsequent classifier cannot recover the missing object. This is a logical limitation of the two-stage architecture.

Why is the YOLO family widely used?

YOLO has evolved as a family of real-time detectors intended to produce object locations and classes through one or more dense outputs. The backbone, neck, head, use of anchors and post-processing have changed considerably between versions. As of 2026, Ultralytics offers the YOLO26 family with end-to-end inference and multiple task heads. However, with many different YOLO forks available, saying 'I use YOLO' is not technically sufficient.

A meaningful comparison must specify the source of the model weights, version, training image size, confidence threshold, hardware, runtime and preprocessing. YOLO's reputation for speed does not directly guarantee speed on the target device. A model that performs well on a small GPU may not achieve acceptable latency on a CPU-only edge computer. Quantization and runtime changes can also affect box locations and the score distribution.

Detector familiesTwo-stage, single-stage, transformer-basedproposaldensequeryoutputConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Two-stage, single-stage, transformer-based

What do DETR and RT-DETR do differently?

DETR treats object detection as a matching problem in which a fixed number of learnable queries are associated with image features. One-to-one assignment, such as Hungarian matching, aims to reduce duplicate boxes for the same object within the architecture's training objective. It therefore offers a framework different from conventional NMS.

In the earliest DETR designs, long training requirements and sensitivity to small objects were important research topics. Developments such as Deformable DETR, DINO and RT-DETR emerged with the goals of improving training convergence, multiscale feature use and real-time inference. The RT-DETR name does not automatically guarantee speed on a given piece of hardware either; model size and runtime matter.

One strength of transformer-based detectors is their ability to evaluate multiple objects in a global context through queries. However, representing very small local anomalies, such as impact marks or fine scratches, with boxes may not always be appropriate. First, verify that the defect can be consistently annotated with a box.

Why is small-object detection difficult?

If the field of view is large and the smallest target is small, the object may occupy only a few pixels at the detector's input. If an image captured at 4000 pixels wide is resized to 640 pixels, a 12-pixel-wide object shrinks to approximately 1.9 pixels. At this scale, distinguishing class and location becomes physically difficult. A deeper network cannot reliably recover image detail lost at the outset.

Possible solutions include closer-range optics, higher input resolution, tile- or patch-based inference, multiscale training and appropriate feature pyramid settings. Tiled inference divides the image into sections to preserve the relative size of a small object. However, objects may be cut at tile boundaries, the same object may be detected twice and the results must be merged. The processing time budget also increases with the number of images.

Small objectsScale and the limit of visible pixelsdistancesizestridemissConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Scale and the limit of visible pixels
Conventional edge map; details of small targets are visible.
Real photograph / transformation: Conventional edge map; details of small targets are visible.

How are class imbalance and hard negatives handled?

A production line may have few scratches but many normal machining marks. A detector can easily mistake these marks for scratches. Hard negatives are acceptable examples that visually resemble defects. Annotating these examples and incorporating them into training in a balanced way may be more useful than collecting more randomly selected defect-free images. However, selecting hard negatives from the test data and reusing them during training compromises independent evaluation.

Repeatedly oversampling the rare class is not a solution on its own. If the defects lack diversity in location, size, angle and lighting, duplicated examples may increase memorization. Data augmentation must be consistent with real physics; for example, arbitrarily rotating a crack that can mechanically form in only one direction may create an incorrect data distribution.

What does mAP measure, and what does it not measure?

Mean Average Precision (mAP) summarizes the precision-recall relationship across classes and, in many applications, across IoU thresholds. AP50 and COCO-style mAP50:95 are not the same value; numerical comparisons must state which metric is being used. A model may have a high mAP while systematically missing a small subgroup of critical defects.

For production, important metrics include product-level recall, critical-defect recall, false alarms per 1000 defect-free parts, localization error and maximum inference latency. If an image contains many objects, 'at least one detection was found' and 'all objects were counted' are also different success criteria. The metric should suit the decision mechanism the process feeds.

Rotated boxes and robotic applications

An oriented bounding box can provide more compact location information for tilted metal parts, long pipes or objects rotating on a conveyor. A center and angle can be extracted from this box to generate a candidate pose for robotic grasping. However, transforming camera coordinates into robot coordinates requires consideration of the working plane, perspective, height and calibration. Sending the box's image angle directly to a mechanical axis is not a reliable integration approach.

It is also important to remember that not every box in an image represents a physical object. One box may cover two adjacent defects, or a single scratch may be split into multiple boxes. If a repair operation requires the endpoints of the defect line, working with a mask or line geometry rather than a box may make more sense.

Rotated boxProblems with axis-aligned boxes for tilted objectsangleboxrotationmeasurementConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Problems with axis-aligned boxes for tilted objects

Numerical scenario: counting parts on a conveyor

Suppose we want to count each product exactly once on a conveyor carrying 240 small parts per minute. If the camera runs at 30 FPS, the average interval between frames is 33.3 ms, but product passage and task latency may not align with this period. Counting the boxes detected in individual frames causes the same part to be counted repeatedly across successive frames. Object detection alone is therefore insufficient; temporal logic such as tracking IDs and virtual line crossings is needed.

The combined sensor trigger delay, image transfer, inference and PLC output time must also be shorter than the time it takes the product to reach the sorting mechanism. In this example, selecting a good detector is only one step in the complete timing chain. If model experiments are conducted without considering the production rate, the model with the best mAP may become the worst system-level choice.

Which detector might be preferable, and when?

Scenario Starting approach Specific risk
Counting individual products quickly Lightweight real-time detector + tracking Double counting, ID switches
Drawing boxes around very small defects Tiled inference + multiscale detector Duplicate boxes, latency
Densely packed and overlapping parts Testing different NMS/matching families Suppression of a real object
Estimating part orientation Rotated box + calibration Angle convention, perspective
Measuring the area of a fine crack Segmentation or conventional geometry Insufficient boundary information in a box

Model selection should not rely on a single benchmark table. Scores on different datasets, input sizes and hardware conditions are not directly comparable. A suitable starting model is one that can be tested with real images on the actual device as quickly as possible.

Annotation box uncertainty in object detection

Drawing a box around an object may seem simple, but where the box should begin is not always clear. If the object is partially occluded, should only the visible region or the entire object be marked? For a linear defect such as a scratch, how much margin should the box leave around the line? When reflections and the actual surface boundary become difficult to distinguish, which pixel should the annotator use as a reference? Unless these questions are resolved before modeling, conflicting boxes will be drawn for the same physical situation.

When IoU is used for training and evaluation, this uncertainty can penalize the model incorrectly. For example, two experts may draw boxes around a small scratch that differ by only two pixels. Although both boxes correctly cover the same visible defect, their IoU may be low. Small-defect testing should therefore examine not just box geometry but also whether the defect was detected and whether the acceptance decision was correct.

It is useful to include box examples for each defect type in the annotation guidelines. The conditions under which an example is split into multiple boxes, the handling of touching objects, partial visibility and rotated-box angles should all be clear. Such a standard improves the technical quality of the dataset regardless of the model architecture.

Comparing anchor-based, anchor-free and query-based structures

Anchor-based detectors may make predictions using candidate boxes with specified scales and aspect ratios. Anchor-free approaches can derive boxes from object centers, corners or dense positional predictions. In query-based detectors, learned queries can be matched to individual object predictions. These families solve the same task, but their training objectives and post-processing details differ.

If anchor dimensions do not represent the geometry of very narrow or long defects, candidate matching may become difficult. In an anchor-free model, defining the center of an irregular object may be problematic. In a query-based model, the number of queries or the matching dynamics may matter for very dense groups of objects. These observations do not establish the automatic superiority of any family; it is necessary to examine which assumptions fit the object distribution in the field.

The most common mistake in comparing model specifications is to look only at model size and the mAP table. If anchor settings, input resizing, augmentation, loss components and inference post-processing actually differ, attributing the results to the model family is misleading. The test protocol and model configuration must be recorded.

What do box regression losses optimize?

A detector's training objective includes box coordinate error as well as class prediction. L1-type coordinate losses may examine boundary differences directly; IoU-based losses focus on box overlap. Variants such as GIoU, DIoU and CIoU aim to provide additional geometric signals when boxes do not overlap or their centers differ. Not every loss produces the same result for a given defect type.

For a defect only a few pixels across, a small error in a boundary coordinate has a large relative effect. Even if the box regression objective looks good during training, it may or may not be adequate for the physical decision in deployment. If the actual tolerance is 0.1 mm, image scale and calibration error must also be considered. A loss function does not automatically resolve physical measurement uncertainty.

The balance between classification and box losses also matters. A model may learn the object type correctly but position the box incorrectly, or it may produce the right box with the wrong class. These two errors may have different consequences in production. Error analysis should make this distinction explicit.

Planning tiled inference for small objects

Examining a large image in tiles can make small targets appear larger at the input. However, tile size, overlap, batch count and merging of objects at boundaries must be designed. For example, dividing a 4096 × 4096 image into 1024 × 1024 tiles requires 16 calls without overlap. Adding 25% overlap increases the tile count further. This incurs not just model-call costs but also memory transfer and duplicate-box removal costs.

If a defect is split across a patch boundary, it may produce weak detections in both patches. Sufficient overlap reduces this risk, but the same defect may be reported twice. Results must be mapped back to full-image coordinates, and duplicate boxes must be merged correctly. If the image acquisition rate in deployment leaves insufficient time for these steps, closer-range optics or a targeted ROI design may be preferable.

A fair comparison of two models using tiled inference requires measuring total product processing time. Performing inference on one tile in 5 ms does not mean a product with 20 tiles is processed in 5 ms. Production decisions should be based on total latency per product and worst-case queueing time.

Strengthening object detection with calibration and 3D orientation information

Detection output is expressed in image coordinates. If a motion command is to be sent to a production robot, the box must be transformed from the camera coordinate system into physical working coordinates. If the camera is tilted, a single fixed pixel-to-millimeter scale may not apply everywhere. A homography may be useful for a fixed plane; objects at different heights may require depth information or additional calibration.

In robotic picking, the box center is not guaranteed to coincide with the actual grasp center. An asymmetric part, a heavy protrusion or the object's shape may place the grasp point away from the box center. In that case, object detection provides the approximate location, while additional geometry or pose estimation determines the final decision. An incorrect center command can cause mechanical failure even when the object was correctly detected.

The angle representation of rotated boxes requires particular care. One system may express the angle between −90 and 90 degrees, while another uses 0 to 180 degrees. If the ordering of the long and short edges changes, the angle may jump by 90 degrees. Convention and symmetry tests must be performed before generating robot commands.

Error analysis: was the object missed, suppressed or incorrectly matched?

An object may be absent from the final output for reasons other than the detector failing to interpret the image. The model may have assigned a low score, NMS may have suppressed a real box or post-processing may have excluded it as outside the ROI. The initial investigation should compare the model's raw candidates, scores and outputs before and after NMS. This avoids unnecessary training for a problem that threshold adjustment could solve.

Another source is annotation error. If some small objects are not marked with reference boxes at all, a real object found by the model may be counted as a false positive during evaluation. Difficult test images in particular therefore need expert review. Annotation quality and evaluation quality are not independent.

Finally, product-level errors should be matched to operational records. The output 'Two screws found' may be correct, but if the product actually requires three screws, the quality decision remains incomplete. Keeping the vision algorithm, rule engine and control system distinct speeds up error analysis.

Advanced engineering details to consider in deployment

Matching errors between boxes

If a production image contains many small screws around a part, the detector generates dozens of boxes of the same class. Matching these boxes to real objects involves more than simply counting boxes below a threshold. Which box belongs to which annotation during learning, and how matching is performed during evaluation, make important differences. In particular, when boxes are close together, a high IoU requirement magnifies small localization errors. NMS may then delete one of two candidates for the same product, but it may also mistakenly suppress one of two real products side by side. Whether the error arises during learning, box localization or post-processing must be investigated separately.

Merging results in tiled inference

When a very high-resolution image is divided into small sections, a small defect occupies more pixels. However, the same object may appear twice at a section boundary. Overlap should be provided between sections, coordinates mapped back to the original image and predictions representing the same object carefully merged. Doubling the number of tiles does not always exactly double inference costs; data transfer, processing queues and batch inference also come into play. Speed tests should measure the time to complete the whole image, not the time for one tile. For critical small objects, improving the optics may be more effective than simple enlargement.

The wrong questions to ask when selecting a detector

The question 'Which YOLO version is best?' cannot be answered without defining the target task. A model with high AP on COCO may perform differently when detecting a small hole defect on uniform metal parts. Likewise, a transformer-based architecture is not automatically superior simply because it is more complex. Start with a fast, stable baseline to understand the limits of the data. Changing only one variable in subsequent experiments makes it easier to identify the source of improvement. The measurement report must include the input size, model version, hardware and runtime used.

Why location matters in product rejection

Detecting an object in the correct class does not mean that an air-jet sorting system will reject the correct part. A geometric and temporal transformation is required between camera coordinates and physical position on the conveyor. If an encoder is used, small speed changes in belt motion can be compensated for. With a fixed time delay, however, slip, product spacing and belt-speed fluctuations may cause errors. How well the detector's box center represents the part center must be checked. Object detection output is only the perception input to the control mechanism, not the entire industrial decision.

Application scenario: inspecting small screws on a conveyor

Box detection on metal products carrying many screws appears straightforward at first. However, when screws are close together, NMS may delete one of the real objects, and a small screw head may shrink to just a few pixels when the image is resized. The experimental plan records optical resolution, box coordinates, overlap threshold, model version, ROI and latency as separate variables. For a successful counting system, a detector producing a good mAP on its own is not enough.

Field-test checklist

  • Is it documented which tests were kept independent by product, shift and imaging conditions?
  • Have failures that can be corrected by the algorithm alone been distinguished from those requiring optical or process changes?
  • Has it been verified that the model score does not replace the physical acceptance criterion?
  • Are input resolution, model version, threshold and operating hardware held constant in the experiment records?
  • Are illustrative visuals clearly distinguished from actual measured model results?
  • Are false rejects, missed defects, latency and reinspection workload reported separately?

Frequently asked questions

What is the difference between YOLO and DETR?

Many versions of the YOLO family are real-time detectors based on dense predictions. The DETR family uses object queries and a matching approach. Current implementations have different architectural details on both sides; the model version must be specified to establish the actual difference.

If mAP is 90%, does that mean 90% of products are correct?

No. mAP summarizes precision-recall and box matching. Product-level acceptance/rejection accuracy and the missed-critical-defect rate must be calculated separately.

Is object detection suitable for small scratches?

It can be tried if the scratch can be clearly enclosed in a box. For very fine, irregular scratches or scratches that require measurement, segmentation or well-designed conventional image processing may be more suitable.

Is NMS mandatory for every model?

No. Some modern architectures aim to eliminate the need for NMS through end-to-end matching. The inference pipeline of the version being used should be checked.

Can a bounding box be used for robot positioning?

A candidate center and angle can be extracted from the box; reliable robot commands require camera calibration, coordinate transformation and mechanical validation.

References and image provenance

Technical references and original publications are listed below. The photographs used in the visual examples are genuine CC0/public-domain images; transformations made for comparison are explained. The diagrams are original designs. Illustrative examples are not presented as trained-model performance.

  1. https://docs.ultralytics.com/models/yolo26/
  2. https://arxiv.org/abs/1506.01497
  3. https://arxiv.org/abs/2005.12872
  4. https://arxiv.org/abs/2304.08069
  5. scikit-image example data: source photographs and reuse notes

Image sources and illustration note

The photographic examples are taken from the scikit-image sample data collection. Added boxes, masks, synthetic defects and heatmaps are demonstrations that explain concepts; they are not outputs of a trained model or validated performance results. The technical diagrams are original drawings included in the package.

Source and usage notes for sample images