An MLOps pipeline for visual quality inspection trains an object detection model such as RF-DETR (opens in a new tab), runs it on a computer beside the production line (the edge), and feeds it the images it gets wrong. MLOps means running machine learning as a repeatable process instead of a one-off project. For inspection, every step from labeling images to updating the deployed model can be repeated, versioned, and checked.
Roboflow runs the whole loop in one platform: label, train, deploy to the edge, capture failures, and retrain. This guide builds it for defect detection on metal surfaces, then shows how to check a new model version before it goes live.
Edge MLOps Pipeline for Quality Inspection
An inspection pipeline repeats five stages:
You label images from the line by marking the defects in them.
You train a detection model and measure its accuracy on images it has not seen.
You deploy the model at the edge. Edge inference means the model runs on a computer at the factory, not on a cloud server.
You capture the images where the model is unsure or wrong. Collecting these on purpose is called active learning.
You retrain by labeling the captured images, training a new version, and redeploying it.
Each pass through the loop improves the model and adds to the record of how it got there.
Running the model at the edge matters for three reasons. The result has to arrive before the part moves on, and local inference skips the round trip to the cloud. Plant networks can drop out, but once the weights are on the device, it keeps inspecting without a connection. And images are processed on the factory network, so only the ones you choose to send, such as low-confidence ones, leave the site.
Building an MLOps Pipeline for Quality Inspection with Roboflow
Picture a production line that makes metal parts. Each part needs a surface check before it moves on, and checking by eye is slow and varies from person to person. A camera over the line and a detection model can mark defects on every part as it passes.
A pipeline starts with images from the line. In production, you would upload frames from your inspection camera to a Roboflow project. Here we fork the Metal Surface Defects dataset into our workspace instead, which gives us images in six classes: pitted, crazing, inclusion, patches, rolled, and scratches.
Labeling is the slow part, so we let AI draft the labels. In Annotate, we sent a batch of 100 images to Auto Label, chose a model, and listed the six classes. A preview run on a few images shows the boxes before you commit to the whole batch. Auto Label uses credits.
The AI labels are a first draft. Open each image, check the boxes, then approve it or reject it. Approved images go into the dataset with Add to Dataset.
Finally, save the labeled dataset as a version. A version freezes the images and labels, so every model you train can be traced back to the exact data it learned from.
Step 2: Train and Evaluate the Defect Detection Model
With the dataset versioned, the next step is training. In Roboflow, click Train Model and pick an architecture. We chose RF-DETR at Small size. Smaller sizes run faster but can be less accurate, and speed matters once the model runs at the edge in Step 4.
When training finishes, Roboflow scores the model on the test set, images it never trained on. Four numbers summarize the result. Precision is the share of predicted boxes that are correct. Recall is the share of real defects the model found. F1 combines the two. mAP@50 (mean average precision) measures how well predicted boxes match the labeled ones, counting a box as correct when it overlaps the label by at least half.
Our model scores 94.3% mAP@50, 89.1% precision, 93.5% recall, and 91.1% F1.
The detailed view breaks mAP down by object size. Large defects score 97.1% at mAP@50, while small ones score 58.6%, so tiny defects are the hardest case.
To see which defects the model misses, check the per-class view, since one overall score averages them together. The bars compare ground truth with correct predictions, false negatives, and false positives for each class.
The confusion matrix gives exact counts. Rows are the true class and columns are the prediction. No class was mistaken for another, so every error is a miss or a false alarm. Inclusion is the weak spot, with 114 found, 43 missed, and 38 false positives. Scratches follow, with 45 found, 6 missed, and 12 false positives.
A missed defect is a bad part that passes inspection, so false negatives matter most here. Step 5 collects more examples of the classes the model is least sure about.
Step 3: Build the Inspection Logic with Workflows
A model returns boxes, but a production line needs a decision, so we build that decision in a Roboflow Workflow, a chain of blocks that runs on every image. The Workflow we'll build below has four parts.
First, the Object Detection Model block runs our trained RF-DETR model on the image and returns a list of detected defects with a class and confidence for each. Next, Property Definition blocks turn that list into numbers: the total defect count, and one count per class, fed by six Detections Filter blocks, one for each class.
Then an Expression block makes the decision: if the defect count is 0, the result is PASS, and otherwise it is FAIL. This is the simplest rule. Real lines tune it, for example by failing only on scratches and crazing and tolerating small patches.
Finally, a Webhook Sink block sends the result and counts as an HTTP POST to the system that records inspections. In a factory, that is usually a Manufacturing Execution System (MES), the software that tracks production and quality records. The Workflow also draws the detections on the image and returns it, so an operator can see why a part failed.
The URL here http://host.docker.internal:8000/webhook points to a small receiver on our own computer, standing in for the MES. Step 4 sets it up. host.docker.internal works on Mac and Windows. On a Jetson or other Linux machine, use the host's LAN IP address instead, or your MES address in production.
Step 4: Deploy to the Edge
Edge deployment means the model runs on a computer next to the production line instead of in the cloud. In production that is a Jetson or an industrial PC runningRoboflow Inference (opens in a new tab), the server that loads your Workflow and trained model. Self-hosted Inference and weight downloads are free on every plan, so the model runs without credits.
We simulate the factory computer with a laptop. Three pieces work together: the Inference server runs the Workflow, a script feeds it images, and a small receiver plays the MES the Webhook Sink reports to.
Prerequisites
Before you start, you need:
Python 3.10 to 3.13.
Docker, installed and running. The Inference server runs in a Docker container.
A Roboflow API key, plus the model and Workflow from Steps 2 and 3.
Create the project folder and a virtual environment inside it:
Shell
mkdir -p step4-edge-inspection/images && cd step4-edge-inspection
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
Project structure
step4-edge-inspection/
├── receiver.py # stand-in MES, listens on port 8000
├── run_inspection.py # sends images, saves annotated outputs
├── requirements.txt
├── images/ # your test images (you create this)
├── outputs/ # created by the script: annotated images and results.csv
└── received/ # created by the receiver: webhooks.jsonl
Put five or more test images in images/. We used five: two defect images from the dataset ( In_172 and Sc_85) and three clean images from outside it ( clean_01, clean_02, and clean_03), since the dataset contains only defective parts.
Install the dependencies
requirements.txt holds two packages. inference-cli starts the server and inference-sdk lets the script call it. Create the file with these two lines:
inference-cli
inference-sdk
With the environment active, install them:
Shell
pip install -r requirements.txt
The receiver
Python
import json
import os
from datetime import datetime
from http.server import BaseHTTPRequestHandler, HTTPServer
HOST = "0.0.0.0" # needed so the Docker container can reach it
PORT = 8000
LOG_FILE = os.path.join("received", "webhooks.jsonl")
os.makedirs("received", exist_ok=True)
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
raw = self.rfile.read(length).decode("utf-8", errors="replace")
try:
body = json.loads(raw)
except json.JSONDecodeError:
body = raw
entry = {
"received_at": datetime.now().isoformat(timespec="seconds"),
"path": self.path,
"body": body,
}
print("\n--- Webhook received ---")
print(json.dumps(entry, indent=2))
with open(LOG_FILE, "a") as f:
f.write(json.dumps(entry) + "\n")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"status": "ok"}')
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"Receiver is running. Send a POST.")
def log_message(self, *args):
pass # silence the default request log
if __name__ == "__main__":
print(f"Receiver listening on http://{HOST}:{PORT} (log: {LOG_FILE})")
HTTPServer((HOST, PORT), Handler).serve_forever()
The inspection script
run_inspection.py sends every image in images/ to the local server, saves the annotated image, and writes a summary table that compares each verdict with the one you expected. Replace the three placeholders at the top, and edit the EXPECTED list to match your own image names.
Python
import base64
import csv
import os
import sys
import time
from pathlib import Path
from inference_sdk import InferenceHTTPClient
API_KEY = os.getenv("ROBOFLOW_API_KEY", "YOUR_ROBOFLOW_API_KEY")
WORKSPACE = os.getenv("ROBOFLOW_WORKSPACE", "YOUR_WORKSPACE_NAME") # from the app URL
WORKFLOW_ID = os.getenv("ROBOFLOW_WORKFLOW_ID", "YOUR_WORKFLOW_ID") # the Workflow's slug
EXPECTED = {
"clean_01": "PASS",
"clean_02": "PASS",
"clean_03": "PASS",
"In_172": "FAIL",
"Sc_85": "FAIL",
}
IMAGE_INPUT_NAME = "image"
RESULT_OUTPUT = "result"
COUNT_OUTPUT = "defect_count"
SERVER_URL = "http://localhost:9001"
IMAGES_DIR = Path("images")
OUTPUTS_DIR = Path("outputs")
EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp"}
def find_image_outputs(result: dict) -> dict:
"""Return {output_name: base64_string} for every image output."""
found = {}
for name, value in result.items():
if isinstance(value, dict) and value.get("type") == "base64":
found[name] = value["value"]
elif isinstance(value, str) and len(value) > 1000:
try:
base64.b64decode(value, validate=True)
found[name] = value
except ValueError:
pass
return found
def main() -> None:
if "YOUR_" in API_KEY + WORKSPACE + WORKFLOW_ID:
sys.exit("Fill in API_KEY, WORKSPACE and WORKFLOW_ID first.")
images = sorted(p for p in IMAGES_DIR.iterdir() if p.suffix.lower() in EXTENSIONS)
if not images:
sys.exit(f"No images found in {IMAGES_DIR}/.")
OUTPUTS_DIR.mkdir(exist_ok=True)
client = InferenceHTTPClient(api_url=SERVER_URL, api_key=API_KEY)
rows = []
for path in images:
start = time.perf_counter()
results = client.run_workflow(
workspace_name=WORKSPACE,
workflow_id=WORKFLOW_ID,
images={IMAGE_INPUT_NAME: str(path)},
use_cache=False, # pick up Workflow edits right away
)
seconds = time.perf_counter() - start
result = results[0]
verdict = result.get(RESULT_OUTPUT, "?")
count = result.get(COUNT_OUTPUT, "?")
expected = EXPECTED.get(path.stem, "?")
for b64 in find_image_outputs(result).values():
(OUTPUTS_DIR / f"{path.stem}_{verdict}.jpg").write_bytes(base64.b64decode(b64))
rows.append({
"image": path.stem,
"expected": expected,
"result": verdict,
"defect_count": count,
"seconds": f"{seconds:.2f}",
})
print(f"{path.stem}: expected {expected}, got {verdict} "
f"({count} detections, {seconds:.2f} s)")
with open(OUTPUTS_DIR / "results.csv", "w", newline="") as f:
writer = csv.DictWriter(
f, fieldnames=["image", "expected", "result", "defect_count", "seconds"]
)
writer.writeheader()
writer.writerows(rows)
checked = [r for r in rows if r["expected"] in ("PASS", "FAIL")]
agree = sum(r["expected"] == r["result"] for r in checked)
print(f"\n{agree} of {len(checked)} verdicts match the expected result.")
if __name__ == "__main__":
main()
Run it
Start Docker, then open three terminals in the project folder. In each one, activate the environment first with source .venv/bin/activate.
Shell
inference server start
python receiver.py
python run_inspection.py
All five verdicts matched what we expected: both defect images failed and all three clean images passed. Each image took 0.63 to 0.78 seconds from sending it to getting the result back, on an M5 chip with the model metal-surface-defects-rmbhy-hzgfj/1 at a confidence threshold of 50%. Five images show that the pipeline works end-to-end, and the Step 2 metrics cover accuracy.
The receiver logs the payload the MES would get. This is the one for the part with three scratches:
JSON
{"result": "FAIL", "defect_count": 3, "scratches_count": 3, "crazing_count": 0, "inclusion_count": 0, "patches_count": 0, "rolled_count": 0, "pitted_count": 0}
The annotated image for each part, with the detections drawn on it, is saved in outputs/. The webhook carries only text and numbers, which is what an MES expects, so the script saves the picture separately.
Step 5: Close the Loop with Active Learning
A deployed model meets parts it was never trained on. Active learning sends the ones it is unsure about back to your dataset, so the next version learns from them. In our model, inclusions are the likely candidate, since it is least reliable there.
Roboflow gives you two ways to collect these images. The first is project-level Active Learning, which you turn on from the project’s Active Learning page. Set the rules for what to collect: confidence below a threshold, specific classes, or a detection count. You also set a sampling rate and caps per minute, hour, and day. Collected images arrive in batches, and you assign reviewers to approve or correct them. The Object Detection Model block has a switch for this, Disable Active Learning, which lets a single block opt out of the project’s collection.
The docs say project-level Active Learning requires a cloud deployment, so it isn’t the route for a self-hosted edge device. On the edge, the second way is to add the collection step to the Workflow yourself. Set the model’s confidence threshold low enough that uncertain detections still come through, then add a filter block, such as Continue If, so only images with uncertain predictions reach a Dataset Upload block. That block sends the image to your project and can save the predictions as pre-labels. A sampling percentage and usage limits keep the volume manageable. Up needs your API key and a connection to Roboflow.
You trigger retraining yourself: review the collected images, fix the labels, add them to the dataset, retrain as in Step 2, and update the model in the Workflow.
Step 6: Automate and Govern Releases
A new model is a change to a production line, so treat it like a software release. Three things make that practical: versions that record every change, Eval gates that check a change before it goes live, and rollbacks that undo one that slipped through.
Every save of a Workflow creates a version, and the latest save is the live one. All plans can see the three most recent versions, while full history, renaming, and restoring need the Teams add-on or Enterprise.
Workflow Evals (opens in a new tab) score a Workflow against test images with known answers. To turn them into a gate, enable “Require an Eval to pass” under Publishing Requirements, pick the Eval, and set a minimum pass rate for each Check. Every new saved version needs its own passing run before it can publish. The same Eval can run from a CI job: a script starts a Run through the SDK, CLI, or HTTP API, waits for it, and fails the job if any Check falls short. For our line, that means a set of images with known PASS and FAIL verdicts.
To roll back, restore the earlier version in the editor and save. The restored content becomes the new live version, and the history stays intact. Devices that run the Workflow by ID pick it up when they next fetch it.