# Detect Defects in Automotive Parts with Roboflow

> Source: <https://roboflow.com/blog/detect-defects-in-automotive-parts>
> Published: 2026-11-30 21:34:05+00:00

**Key takeaway:** Pair an RF-DETR scratch/paint-damage detector with a Workflow that counts detections and draws boxes, and tune the confidence threshold to control which defects surface in inspection results.

A scratch along a wheel spoke or a small patch of damaged paint can be easy to overlook. During automotive inspection, an operator needs to know what kind of damage is visible and where to look. A labeled image can point them to the area that needs a closer look.

In this tutorial, we’ll use Roboflow's RF-DETR for object detection to detect scratches and paint damage on alloy wheels. Using real wheel images, we’ll see how changing the confidence threshold affects which defects appear in the inspection result.

How to detect defects in automotive parts with vision AI

The inspection system uses an object detector to identify visible defects and locate them with bounding boxes. A Workflow then counts the detected regions and draws the results on the original image.

Detection answers whether the model found a target defect. Localization identifies where that defect appears in the image. An object detection model provides both in the same prediction, returning a class label, confidence score, and bounding box. Here, the label distinguishes scratch from paint-damage, while the box directs the reviewer to the affected region. The box does not trace the exact outline of the damage.

The object detector that I am going to use in this tutorial recognizes scratch and paint-damage. I use Roboflow Annotate to review labels, dataset versions (opens in a new tab) to prepare training data, Custom Training (opens in a new tab) to train the model, and Workflows to connect the predictions to counting and visualization.

The Workflow has three useful outputs. The predictions identify the damaged regions, the count tells an application how many regions were detected, and the visualization helps an operator inspect the result. A count of zero means no target defect was detected in that image. Manufacturing acceptance also depends on the inspection requirements and image quality.

The annotation boxes identify damaged surface regions rather than entire wheels.

Before you start

You need a Roboflow account and a workspace where you can prepare data and train models. Readers using their own copy will use their destination workspace, project, and model IDs. Available operations depend on workspace permissions (opens in a new tab) and the workspace plan.

For recurring imports, Datasources and Bucket Mirror (opens in a new tab) connect supported cloud storage to the Asset Library. Select the imported images you want to add to a labeling project. A bucket connection is optional for this example.

Step 2: Review and complete the defect annotations

Open an image in Roboflow Annotate (opens in a new tab). Use the bounding box tool to surround a visible defect and select its class. Resize misplaced boxes and correct labels before adding the images to your training data. Use consistent working definitions for this project.

Class

What to annotate

scratch

A visible scratch region on the wheel surface.

paint-damage

A visible area of damaged paint or coating.

These definitions guide annotation. Your inspection requirements should define which appearances belong to each class, including how to label an area that could fit both descriptions.

Keep each box close to the damaged region. Include reviewed images with no target defects so the dataset covers ordinary reflections and acceptable surface variation. An image without boxes should be deliberately reviewed, rather than assumed to be a negative example because annotation is incomplete.

Use assisted labeling for new images

Auto Label can generate proposed annotations using supported foundation models, trained models, or saved Workflows.

Upload a batch and select Auto-Label And Review.

Choose a labeling model. For an existing wheel detector, check that its trained classes match the labels you need.

Supply class descriptions when the selected model uses them.

Run a preview and examine the proposed boxes.

Adjust the setup, label the batch, and review the results.

Correct missed defects, false detections, and oversized boxes. For image-by-image work, Label Assist (opens in a new tab) provides model suggestions inside the annotation editor. The goal at this stage is a consistent reference for training and evaluation.

Step 3: Check dataset quality and separate related images

Open Dataset and thenHealth Check. Dataset Health Check (opens in a new tab) summarizes images and annotations, missing and null annotations, dimensions, and annotation locations. Check whether both classes have useful coverage and whether small damage regions remain visible. Use Dataset Search (opens in a new tab) to review specific groups.

Search query

Review purpose

class:scratch

Inspect scratch labels.

class:paint-damage

Inspect paint-damage labels.

max-annotations:0

Confirm the labeling status of images without boxes.

class:scratch split:valid

Review validation examples containing scratches.

For new inspection data, keep frames from the same wheel or recording together when assigning splits. Use the dataset bulk actions to change split membership. Reserve separate wheels or capture sessions for validation and testing, and check that both defect classes are represented. This makes the evaluation more useful for assessing new inspection images.

If you change the split assignments, train from a public pretrained checkpoint. A previous wheel model could already have learned from images that have moved into the new evaluation split.

The reference wheel version uses Auto-Orient and a 512 × 512 resize with Fit (black edges) in. Color is preserved, with no dataset augmentation in the reference setup.

Preview the preprocessing (opens in a new tab) on images with small scratches. The damaged area must remain visible after resizing. For later experiments, image augmentation (opens in a new tab) can introduce plausible variations in training images. Preprocessing applies across the splits; dataset augmentation applies to training images.

Select a single architecture, then RF-DETR and Small.

Select the dataset version you prepared.

Choose a public pretrained checkpoint for your first run on these splits.

Review the training recipe and retain the supported defaults unless you are testing a particular change.

Review the duration and credit estimate, then start training.

Record the dataset version, training settings, and exact model ID (opens in a new tab). The saved Workflow in this tutorial uses the existing trained baseline below. A new training run is not required to reproduce the provided Workflow examples.

```
tim-4ijf0/alloy-wheel-defect-4fkug-2-rfdetr-small-t1
```

If you train your own copy, select your model's ID in the Workflow. For a later comparison, Neural Architecture Search (opens in a new tab) can explore model candidates and their accuracy and latency trade-offs. Review its estimate before starting a search.

Step 6: Evaluate detection quality and box placement

Open the trained model and select View Full Model Evaluation. Model Evaluation (opens in a new tab) provides tools for examining predictions, including class-level results and the confusion matrix. Inspect the underlying images as well as the aggregate scores.

For this inspection task, ask whether the model detects the damaged region, assigns the correct class, and places the box close enough to guide a reviewer. A detection can have the correct class while its box covers too much surrounding metal.

Use the production metrics explorer to inspect precision, recall, and F1 at different confidence thresholds. Select a threshold using validation evidence and the inspection requirement, then assess that fixed setting on independent test images. The worked Workflow uses 0.18 to reproduce the existing setup; it is not a universal threshold for wheel defects.

Model Comparison (opens in a new tab) lets you compare models trained on the same dataset version. Keep the split and metric consistent when comparing results. A model's API latency also differs from the complete time needed to capture an image, send it, inspect the response, and update an operator display.

The next sections focus on the completed inspection behavior. We will inspect actual outputs, including an example where increasing the threshold removes a visible defect prediction.

Read the measured evaluation results

The saved evaluation for the wheel model contains results for the RF-DETR Small baseline named in Step 5. Select the model ending in rfdetr-small-t1 if the project shows more than one training. The evaluation uses dataset version 2, with 38 validation images and 21 test images.

The validation confidence sweep identifies 0.18 as its optimal threshold. Keeping that setting fixed gives the following recorded results. Precision, recall, and F1 come from the sweep at 0.18; the mAP values come from the evaluation's separate mAP results (opens in a new tab).

Metric

Validation, 38 images

Test, 21 images

Precision at confidence 0.18

100.0%

92.9%

Recall at confidence 0.18

100.0%

100.0%

F1 at confidence 0.18

100.0%

96.2%

mAP@50

100.0%

100.0%

mAP@75

63.4%

55.4%

mAP@50:95

61.3%

51.0%

The test sweep also has its own optimal threshold, 0.24, where precision, recall, and F1 reach 100%. We retain the validation-selected 0.18 for the tutorial. Selecting a setting because it performs best on the test set would use the test results to tune the model's operating point.

Check localization as well as detection

The mAP results become lower at stricter box-overlap requirements. In this evaluation, mAP@50 is 100%, but test mAP@50:95 is 51.0%. This difference indicates that box placement needs closer inspection even when the detector finds the labeled defects. These are average-precision metrics, not the average overlap of the boxes.

Class

Test mAP@50

Test mAP@50:95

paint-damage

100.0%

55.3%

scratch

100.0%

46.7%

Use the confusion matrix image viewer (opens in a new tab) to switch between ground-truth annotations and model predictions. Inspect narrow scratches, small damaged areas, and boxes that include unnecessary surrounding surface. The individual confidence score shown on a box describes that prediction; it is not the model's test-set accuracy.

Understand what these results establish

This is a small, existing dataset split. Its filenames show frames from the same source recordings in training, validation, and test. For example, normal-1_mp4 contributes 22 training frames, 7 validation frames, and 5 test frames. The recorded scores therefore describe this split and do not establish performance on independent wheels or new capture sessions.

For a deployment evaluation, collect additional wheels and recordings, keep each source group in one split, and retrain from a public pretrained checkpoint as described in Step 3. Check the fixed threshold on those separate test images before using the result to set an inspection acceptance target.

The saved evaluation also reports a median Cloud API latency of 15.47 ms. This latency measurement (opens in a new tab) includes server preprocessing and postprocessing but excludes network time. It is a model-evaluation measurement, not the throughput or end-to-end response time of the full inspection Workflow.

Inspect an individual image

The model-testing screen below shows the RF-DETR Small baseline detecting paint-damage on a wheel. The predicted region is displayed beside its JSON output, including the box coordinates and a confidence of approximately 0.821. This screen uses a confidence threshold of 0.50; the Workflow examples that follow use 0.18.

Keep an image input named image. Add a parameter named confidence_threshold with a default value of 0.18.

Add an Object Detection Model (opens in a new tab) block and name it wheel_defects. Select the wheel model, connect its image to image, choose a custom confidence threshold, and connect that setting to the confidence_threshold parameter.

The saved example disables active learning in this model block. Running the examples does not intentionally collect new training images. We will discuss collection separately in Step 10.

Count the detected regions

Add Property Definition (opens in a new tab) and name it count_defects. Set Data to the predictions from wheel_defects and choose Count Items. In the exported specification, this operation appears as SequenceLength.

The count represents retained bounding boxes in one image. It does not count unique wheels or track the same defect across video frames.

Existing RF-DETR Small model with a confidence threshold supplied as a parameter.

count_defects

Model predictions

Count Items.

draw_boxes

Original image and model predictions

ROBOFLOW palette with box thickness 2.

draw_labels

Image from draw_boxes and model predictions

Class and Confidence with text scale 0.4.

The tested visualization uses text thickness 1, padding 3, and TOP_LEFT label positioning. These settings keep the labels readable without covering a large portion of the 480 × 480 example images.

Save the Workflow. The example is published as automotive-wheel-defect-inspection-1795780256577 in workspace tim-4ijf0. Its exported configuration is included with the tutorial files.

An application can display Review required when defect_count > 0, and No target defect detected when the count is zero. Keep request errors separate from both states. If a request fails, the application has no completed inspection result.

If your model later includes unrelated classes, add a Detections Filter (opens in a new tab). Connect both counting and visualization to the filtered predictions so the displayed boxes and count agree.

Step 8: Test the complete Workflow

Use the Run panel (opens in a new tab) to submit a scratch image, a paint-damage image, and a reviewed image without the target defects. Inspect both the visualization and JSON. If you add storage blocks later, turn Sinks off during tests when you do not intend to create records.

Examine the paint-damage result

The Workflow returned one paint-damage prediction for paint-damage_mp4-0005.jpg. Its confidence was approximately 0.821 at the 0.18 threshold.

The structured output contains the same region shown in the image. The excerpt below omits the visualization's encoded image and run-specific detection identifiers, and rounds the confidence for readability.

JSON

```
{
  "predictions": {
    "image": {"width": 480, "height": 480},
    "predictions": [
      {
        "x": 114, "y": 181,
        "width": 18, "height": 30,
        "confidence": 0.820792,
        "class": "paint-damage",
        "class_id": 0
      }
    ]
  },
  "defect_count": 1
}
```

For this returned box, x and y identify its center, while width and height describe its size. Its corners are (105, 166) and (123, 196) in the 480 × 480 image. These coordinates let a display application place the detected region on the original image.

Check a scratch near the image boundary

The scratch example returned one scratch prediction with confidence approximately 0.809. Its bounding box reaches the left edge of the image.

This example is useful for checking the inspection view as well as the model. A camera arrangement should show the surface that must be inspected. Detecting one visible scratch does not establish that surfaces outside the frame were inspected.

Interpret a result with no detections

For normal-1_mp4-0001.jpg, the Workflow returned an empty predictions list and a defect count of zero.

Input image

Threshold

Returned class

Confidence

Defect count

paint-damage_mp4-0005.jpg

0.18

paint-damage

0.821

1

scratch-2_mp4-0003.jpg

0.18

scratch

0.809

1

normal-1_mp4-0001.jpg

0.18

Empty predictions

Not applicable

0

paint-damage_mp4-0005.jpg

0.85

Empty predictions

Not applicable

0

These are actual example executions showing output behavior, rather than an accuracy benchmark.

Change the threshold on the same image

Run the paint-damage image again with confidence_threshold set to 0.85. The prediction with confidence approximately 0.821 is no longer retained. The Workflow now returns zero detections and an image without a box.

The surface in the image has not changed. The threshold changed which predictions were returned. This is why the application status should describe the detection result precisely, and why threshold selection needs validation images containing both defects and acceptable surfaces.

Add images and select predictions and defect_count as outputs to check.

Review ground-truth boxes and enter expected counts. Explicitly mark the empty set for an image with no target objects.

Add output checks with suitable thresholds. Add a latency budget if required.

Run a preview, review the setup and credit estimate, then run the Eval.

Inspect failing cases before deploying a change.

When importing a Dataset test set, Evals uses current annotations on original images. Review the imported labels before approving them. Add cases that exercise small defects, reflections, partial views, and images with no target defects

Step 9: Run the Workflow from an application

Open Deploy in the Workflow editor. Its generated code provides the workspace and Workflow identifiers for the selected runtime. The following example uses the Inference SDK Workflow interface (opens in a new tab).

Install the client and CLI using the documented command.

Shell

```
pip install inference-sdk inference-cli
```

Set your API key for the current terminal session. For Windows PowerShell, use the following command with your own key.

```
$env:ROBOFLOW_API_KEY = "YOUR_API_KEY"
```

Save this as inspect_wheel.py. The default identifiers point to the saved example. Set the workspace and Workflow environment variables if you use your own copy.

Python

``` python
import json
import os
import sys
from inference_sdk import InferenceHTTPClient, InferenceConfiguration

client = InferenceHTTPClient(
    api_url=os.getenv("ROBOFLOW_API_URL", "https://serverless.roboflow.com"),
    api_key=os.environ["ROBOFLOW_API_KEY"],
).configure(InferenceConfiguration(api_key_transport="header"))

results = client.run_workflow(
    workspace_name=os.getenv("ROBOFLOW_WORKSPACE", "tim-4ijf0"),
    workflow_id=os.getenv(
        "ROBOFLOW_WORKFLOW_ID",
        "automotive-wheel-defect-inspection-1795780256577",
    ),
    images={"image": sys.argv[1]},
)

if len(results) != 1:
    raise RuntimeError("Expected one image result")
result = results[0]
count = result.get("defect_count")
if isinstance(count, bool) or not isinstance(count, (int, float)):
    raise RuntimeError("Missing or invalid defect count")
if count < 0 or int(count) != count:
    raise RuntimeError("Invalid defect count")

status = "Review required" if count > 0 else "No target defect detected"
print(f"{status}. Detected regions: {int(count)}")
print(json.dumps(result["predictions"], indent=2))
```

Run the script on an inspection image.

Shell

```
python inspect_wheel.py wheel.jpg
```

The script uses the saved Workflow's default threshold, 0.18. It prints the count and predictions; the returned visualization field is also available for an application display. The status text is application logic added here. An API failure remains an exception instead of becoming a zero-detection result.

For a folder or stored video, create a Batch Processing job, select the Workflow, provide the files, and review the runtime settings before starting. For live sources, use the Cloud Streaming quickstart and stop processing explicitly after the test. Measure the complete inspection response time on the intended runtime before setting an operating rate.

Step 10: Collect useful images and improve the detector

New finishes, lighting changes, and unfamiliar defect appearances can reveal weaknesses after deployment. Use reviewed inspection images to improve the next model.

The Roboflow Dataset Upload (opens in a new tab) block can collect images from a Workflow and optionally save predictions as annotations. Configure its destination project, sampling, upload limits, and batch naming. Review those predictions before treating them as training labels.

Collect confirmed misses and false alarms reported by operators. Include a sample of images with no detections, because collecting only positive predictions will not expose every missed defect. This is an inspection sampling choice for the application.

For an inspection record, add a Continue If (opens in a new tab) condition on defect_count > 0 and connect it to Roboflow Vision Events (opens in a new tab). Supply the image, predictions, and relevant metadata. Keep this optional branch separate from the main outputs. A video event cooldown limits event frequency; it does not identify unique wheels.

Where available for the workspace and deployment, Active Learning (opens in a new tab) provides project-level collection rules. Choose a collection approach deliberately to avoid uploading the same examples through multiple paths.

The saved demonstration Workflow contains detection, counting, and visualization only. Add and test a collection branch when you are ready to retain inspection data. Review the collected images, create a new dataset version, train a candidate, and evaluate it before replacing the deployed detector.

Optional approach when defect examples are scarce

The detector above learns the two labeled defect classes. Anomaly detection (opens in a new tab) offers another approach when normal images are easier to collect. It learns normal appearance and returns a normal or anomalous result, a score, and a heatmap.

Prepare normal and anomalous wheel images

Use the same wheel images in a separate Anomaly Detection project (opens in a new tab). Label each image normal or anomalous. A scratch or paint-damage image is anomalous for this experiment. These are image-level labels; the original bounding-box annotations remain in the object detection project.

The companion Wheel Surface Anomaly Tutorial project uses the 67 normal images and 36 defective images drawn from the original validation and test sets. Its separate split assignment is shown below. This is a demonstration using the existing recordings, not a comparison on independent production captures.

Image label

Training

Validation

Test

normal

44

14

9

anomalous

0

24

12

Total

44

38

21

For new data, collect acceptable wheels under the intended camera conditions and keep source recordings together when separating training and evaluation images. Only normal images belong in the training split. Include both normal and anomalous examples in validation and test.

Train PatchCore

PatchCore (opens in a new tab) represents normal appearance using features from image patches. A new image receives a higher anomaly score when its patches differ more from the stored normal examples.

Create a version with Auto-Orient and Stretch to resize at 224 × 224.

Leave dataset augmentation disabled and inspect the preprocessing preview.

Open Train, select Custom Training, and choose PatchCore.

Review the estimate and start training.

Record the trained model ID and review the reported test precision, recall, and F1.

The completed companion run uses version 2 and model tim-4ijf0/wheel-surface-anomaly-tutorial-2-patchcore-t1. Its saved raw anomaly threshold is 7.022127. On its 21-image test split, the training report returns 100% precision, recall, F1, and image-level accuracy. These are normal-versus-anomalous classification results. They do not measure how tightly a heatmap covers the actual defect and should not be compared directly with the detector's bounding-box mAP.

The source recordings also contribute frames to more than one split in this companion experiment. Treat these scores as demonstration results and use independent captures for an operating decision.

The default resolution is 224 × 224. Check whether small scratches remain visible before trying a larger size. The anomaly score is unbounded and is not a percentage probability of damage.

Add an Anomaly Detection Model (opens in a new tab) named wheel_anomaly. Connect the image input and select the trained companion model. Enable the anomaly map, set confidence to 0.5, and leave the raw anomaly threshold unset to use the saved model threshold. Disable active learning for these demonstration runs.

Add Anomaly Heatmap Visualization (opens in a new tab) named draw_anomaly_heatmap. Connect the original image, the model's anomaly_map, and its anomaly_decision_threshold to the heatmap's anomaly_threshold. Use the ROBOFLOW color map and opacity 0.75.

At confidence 0.5, the decision follows the threshold calibrated during training. Connecting anomaly_decision_threshold keeps the visualization aligned if the model block's confidence setting changes. The heatmap uses a threshold-based color scale, so colors can be compared across images from this model.

Output

Selector

predictions

$steps.wheel_anomaly.predictions

anomaly_score

$steps.wheel_anomaly.anomaly_score

anomaly_threshold

$steps.wheel_anomaly.anomaly_threshold

anomaly_decision_threshold

$steps.wheel_anomaly.anomaly_decision_threshold

is_anomalous

$steps.wheel_anomaly.is_anomalous

output_image

$steps.draw_anomaly_heatmap.image

Inspect the verdict and heatmap together

Run held-out normal, scratch, and paint-damage images through the Workflow. Read is_anomalous and the raw score alongside the heatmap. A highlighted region shows a difference from learned normal appearance. It does not identify that region as scratch or paint-damage, and it does not provide an object count.

The saved Workflow produced the following results at confidence 0.5. All three input images belong to the companion project's test split. Scores are rounded here; the included JSON files retain the returned values.

Test image

Raw anomaly score

Decision threshold

Returned verdict

normal-1_mp4-0008.jpg

2.6881

7.0221

Normal

scratch-2_mp4-0003.jpg

9.4247

7.0221

Anomalous

paint-damage_mp4-0020.jpg

8.1651

7.0221

Anomalous

These images illustrate an important distinction. The three image-level verdicts agree with their labels, but the heatmaps respond broadly to the wheel and conveyor. These runs do not establish precise defect localization. The pictured wheels also differ in spoke layout and position, so additional normal examples covering those acceptable appearances are needed to investigate whether the model is responding to the damage or to other changes in the scene. Color is visible on the normal example too because the visualization draws continuous anomaly evidence rather than a binary pass/fail mask.

For an application, read is_anomalous to display the verdict and output_image to display the heatmap. The original inspect_wheel.py expects a defect count; use the separate inspect_wheel_anomaly.py included with the tutorial for this Workflow. Its SDK call uses the same documented Workflow deployment interface (opens in a new tab), with the companion Workflow identifier and anomaly output names.

Inspection need

Suitable starting point

Identify known defect classes and return their boxes

The RF-DETR Small detector and the original inspection Workflow.

Flag differences from normal appearance when defect examples are scarce

The PatchCore model and anomaly heatmap Workflow.

Review both false alarms on acceptable wheels and missed defects. A heatmap that highlights lighting changes or the conveyor rather than the relevant wheel surface is useful evidence for improving image capture and normal-image coverage. Compare application decisions on a common, independently collected evaluation set before choosing a production approach.

To reduce the conveyor highlights seen in these examples, add a detector trained on the wheel class. Use its bounding box to crop each wheel. Train PatchCore on normal wheel crops, then apply the same crop during inspection and display the heatmap on the cropped image. This keeps the area outside the wheel’s bounding box out of the heatmap.

Conclusion

Automotive surface inspection needs clear labels, representative images, and results that operators can interpret. Computer vision can locate visible damage and provide consistent information for review.

Start with the wheel project, build the inspection Workflow, and test it under your own camera conditions. Use the predictions, count, and annotated image together, then improve the detector with reviewed inspection examples.
