{"slug": "build-an-end-to-end-mlops-pipeline-for-visual-quality-inspection-at-the-edge", "title": "Build an End-to-End MLOps Pipeline for Visual Quality Inspection at the Edge", "summary": "Roboflow published a guide for building an end-to-end MLOps pipeline for visual quality inspection at the edge, training an RF-DETR Small object detection model on the Metal Surface Defects dataset across six classes (pitted, crazing, inclusion, patches, rolled, and scratches). The resulting model scored 94.3% mAP@50, 89.1% precision, 93.5% recall, and 91.1% F1 on the test set, with large defects reaching 97.1% mAP@50 versus 58.6% for small defects. The five-stage loop — label, train, deploy to the edge, capture failures via active learning, and retrain — keeps inference local so results arrive before a part moves on, inspection continues through network dropouts, and only selected images such as low-confidence ones leave the plant.", "body_md": "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.\n\nRoboflow 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.\n\nEdge MLOps Pipeline for Quality Inspection\n\nAn inspection pipeline repeats five stages:\n\nYou label images from the line by marking the defects in them.\n\nYou train a detection model and measure its accuracy on images it has not seen.\n\nYou deploy the model at the edge. Edge inference means the model runs on a computer at the factory, not on a cloud server.\n\nYou capture the images where the model is unsure or wrong. Collecting these on purpose is called active learning.\n\nYou retrain by labeling the captured images, training a new version, and redeploying it.\n\nEach pass through the loop improves the model and adds to the record of how it got there.\n\nRunning 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.\n\nBuilding an MLOps Pipeline for Quality Inspection with Roboflow\n\nPicture 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.\n\nA 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.\n\nLabeling 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.\n\nThe 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.\n\nFinally, 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.\n\nStep 2: Train and Evaluate the Defect Detection Model\n\nWith 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.\n\nWhen 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.\n\nOur model scores 94.3% mAP@50, 89.1% precision, 93.5% recall, and 91.1% F1.\n\nThe 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.\n\nTo 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.\n\nThe 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.\n\nA 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.\n\nStep 3: Build the Inspection Logic with Workflows\n\nA 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.\n\nFirst, 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.\n\nThen 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.\n\nFinally, 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.\n\nThe 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.\n\nStep 4: Deploy to the Edge\n\nEdge 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.\n\nWe 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.\n\nPrerequisites\n\nBefore you start, you need:\n\nPython 3.10 to 3.13.\n\nDocker, installed and running. The Inference server runs in a Docker container.\n\nA Roboflow API key, plus the model and Workflow from Steps 2 and 3.\n\nCreate the project folder and a virtual environment inside it:\n\nShell\n\n```\nmkdir -p step4-edge-inspection/images && cd step4-edge-inspection\npython3 -m venv .venv\nsource .venv/bin/activate      # Windows: .venv\\Scripts\\activate\n```\n\nProject structure\n\n```\nstep4-edge-inspection/\n├── receiver.py          # stand-in MES, listens on port 8000\n├── run_inspection.py    # sends images, saves annotated outputs\n├── requirements.txt\n├── images/              # your test images (you create this)\n├── outputs/             # created by the script: annotated images and results.csv\n└── received/            # created by the receiver: webhooks.jsonl\n```\n\nPut 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.\n\nInstall the dependencies\n\n`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:\n\n```\ninference-cli\ninference-sdk\n```\n\nWith the environment active, install them:\n\nShell\n\n```\npip install -r requirements.txt\n```\n\nThe receiver\n\nPython\n\n``` python\nimport json\nimport os\nfrom datetime import datetime\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\nHOST = \"0.0.0.0\"   # needed so the Docker container can reach it\nPORT = 8000\nLOG_FILE = os.path.join(\"received\", \"webhooks.jsonl\")\n\nos.makedirs(\"received\", exist_ok=True)\n\nclass Handler(BaseHTTPRequestHandler):\n    def do_POST(self):\n        length = int(self.headers.get(\"Content-Length\", 0))\n        raw = self.rfile.read(length).decode(\"utf-8\", errors=\"replace\")\n        try:\n            body = json.loads(raw)\n        except json.JSONDecodeError:\n            body = raw\n\n        entry = {\n            \"received_at\": datetime.now().isoformat(timespec=\"seconds\"),\n            \"path\": self.path,\n            \"body\": body,\n        }\n        print(\"\\n--- Webhook received ---\")\n        print(json.dumps(entry, indent=2))\n\n        with open(LOG_FILE, \"a\") as f:\n            f.write(json.dumps(entry) + \"\\n\")\n\n        self.send_response(200)\n        self.send_header(\"Content-Type\", \"application/json\")\n        self.end_headers()\n        self.wfile.write(b'{\"status\": \"ok\"}')\n\n    def do_GET(self):\n        # Lets you check the receiver from a browser or curl.\n        self.send_response(200)\n        self.end_headers()\n        self.wfile.write(b\"Receiver is running. Send a POST.\")\n\n    def log_message(self, *args):\n        pass  # silence the default request log\n\nif __name__ == \"__main__\":\n    print(f\"Receiver listening on http://{HOST}:{PORT}  (log: {LOG_FILE})\")\n    HTTPServer((HOST, PORT), Handler).serve_forever()\n```\n\nThe inspection script\n\n`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.\n\nPython\n\n``` python\nimport base64\nimport csv\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\nfrom inference_sdk import InferenceHTTPClient\n\n# ---------------------------------------------------------------------------\n# REPLACE THESE (or set them as environment variables)\n# ---------------------------------------------------------------------------\nAPI_KEY = os.getenv(\"ROBOFLOW_API_KEY\", \"YOUR_ROBOFLOW_API_KEY\")\nWORKSPACE = os.getenv(\"ROBOFLOW_WORKSPACE\", \"YOUR_WORKSPACE_NAME\")   # from the app URL\nWORKFLOW_ID = os.getenv(\"ROBOFLOW_WORKFLOW_ID\", \"YOUR_WORKFLOW_ID\")  # the Workflow's slug\n\n# REPLACE THIS with your own images. For each image in images/ (without the\n# file extension), write the verdict you expect, decided by checking the\n# image by eye before the run.\nEXPECTED = {\n    \"clean_01\": \"PASS\",\n    \"clean_02\": \"PASS\",\n    \"clean_03\": \"PASS\",\n    \"In_172\": \"FAIL\",\n    \"Sc_85\": \"FAIL\",\n}\n\n# Change these only if your Workflow uses different names.\nIMAGE_INPUT_NAME = \"image\"\nRESULT_OUTPUT = \"result\"\nCOUNT_OUTPUT = \"defect_count\"\n# ---------------------------------------------------------------------------\n\nSERVER_URL = \"http://localhost:9001\"\nIMAGES_DIR = Path(\"images\")\nOUTPUTS_DIR = Path(\"outputs\")\nEXTENSIONS = {\".jpg\", \".jpeg\", \".png\", \".bmp\"}\n\ndef find_image_outputs(result: dict) -> dict:\n    \"\"\"Return {output_name: base64_string} for every image output.\"\"\"\n    found = {}\n    for name, value in result.items():\n        if isinstance(value, dict) and value.get(\"type\") == \"base64\":\n            found[name] = value[\"value\"]\n        elif isinstance(value, str) and len(value) > 1000:\n            try:\n                base64.b64decode(value, validate=True)\n                found[name] = value\n            except ValueError:\n                pass\n    return found\n\ndef main() -> None:\n    if \"YOUR_\" in API_KEY + WORKSPACE + WORKFLOW_ID:\n        sys.exit(\"Fill in API_KEY, WORKSPACE and WORKFLOW_ID first.\")\n\n    images = sorted(p for p in IMAGES_DIR.iterdir() if p.suffix.lower() in EXTENSIONS)\n    if not images:\n        sys.exit(f\"No images found in {IMAGES_DIR}/.\")\n\n    OUTPUTS_DIR.mkdir(exist_ok=True)\n    client = InferenceHTTPClient(api_url=SERVER_URL, api_key=API_KEY)\n\n    rows = []\n    for path in images:\n        start = time.perf_counter()\n        results = client.run_workflow(\n            workspace_name=WORKSPACE,\n            workflow_id=WORKFLOW_ID,\n            images={IMAGE_INPUT_NAME: str(path)},\n            use_cache=False,  # pick up Workflow edits right away\n        )\n        seconds = time.perf_counter() - start\n\n        result = results[0]\n        verdict = result.get(RESULT_OUTPUT, \"?\")\n        count = result.get(COUNT_OUTPUT, \"?\")\n        expected = EXPECTED.get(path.stem, \"?\")\n\n        for b64 in find_image_outputs(result).values():\n            (OUTPUTS_DIR / f\"{path.stem}_{verdict}.jpg\").write_bytes(base64.b64decode(b64))\n\n        rows.append({\n            \"image\": path.stem,\n            \"expected\": expected,\n            \"result\": verdict,\n            \"defect_count\": count,\n            \"seconds\": f\"{seconds:.2f}\",\n        })\n        print(f\"{path.stem}: expected {expected}, got {verdict} \"\n              f\"({count} detections, {seconds:.2f} s)\")\n\n    with open(OUTPUTS_DIR / \"results.csv\", \"w\", newline=\"\") as f:\n        writer = csv.DictWriter(\n            f, fieldnames=[\"image\", \"expected\", \"result\", \"defect_count\", \"seconds\"]\n        )\n        writer.writeheader()\n        writer.writerows(rows)\n\n    checked = [r for r in rows if r[\"expected\"] in (\"PASS\", \"FAIL\")]\n    agree = sum(r[\"expected\"] == r[\"result\"] for r in checked)\n    print(f\"\\n{agree} of {len(checked)} verdicts match the expected result.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nRun it\n\nStart Docker, then open three terminals in the project folder. In each one, activate the environment first with `source .venv/bin/activate`.\n\nShell\n\n```\n# Terminal 1: the Inference server (downloads the model weights on first use)\ninference server start\n\n# Terminal 2: the stand-in MES\npython receiver.py\n\n# Terminal 3: send the images\npython run_inspection.py\n```\n\nAll 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.\n\nThe receiver logs the payload the MES would get. This is the one for the part with three scratches:\n\nJSON\n\n```\n{\"result\": \"FAIL\", \"defect_count\": 3, \"scratches_count\": 3, \"crazing_count\": 0, \"inclusion_count\": 0, \"patches_count\": 0, \"rolled_count\": 0, \"pitted_count\": 0}\n```\n\nThe 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.\n\nStep 5: Close the Loop with Active Learning\n\nA 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.\n\nRoboflow 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.\n\nThe 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. Uploading needs your API key and a connection to Roboflow.\n\nYou 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.\n\nStep 6: Automate and Govern Releases\n\nA 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.\n\nEvery 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.\n\nWorkflow 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.\n\nTo 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.", "url": "https://wpnews.pro/news/build-an-end-to-end-mlops-pipeline-for-visual-quality-inspection-at-the-edge", "canonical_source": "https://roboflow.com/blog/mlops-pipeline-for-visual-quality-inspection", "published_at": "2026-11-30 21:18:39+00:00", "updated_at": "2026-11-30 21:43:19.235276+00:00", "lang": "en", "topics": ["mlops", "computer-vision", "machine-learning", "ai-infrastructure", "ai-tools"], "entities": ["Roboflow", "RF-DETR", "Metal Surface Defects dataset", "Auto Label"], "also_reported_by": [], "takeaway": "An RF-DETR Small model trained on the six-class Metal Surface Defects dataset reached 94.3% mAP@50 overall but only 58.6% on small defects versus 97.1% on large ones, so per-size mAP breakdowns should drive active-learning capture of low-confidence edge images.", "recommendation": {"advice": "Version each labeled dataset before training and review per-size and per-class mAP, then route low-confidence edge images back into labeling and retrain before redeploying.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/build-an-end-to-end-mlops-pipeline-for-visual-quality-inspection-at-the-edge", "markdown": "https://wpnews.pro/news/build-an-end-to-end-mlops-pipeline-for-visual-quality-inspection-at-the-edge.md", "text": "https://wpnews.pro/news/build-an-end-to-end-mlops-pipeline-for-visual-quality-inspection-at-the-edge.txt", "jsonld": "https://wpnews.pro/news/build-an-end-to-end-mlops-pipeline-for-visual-quality-inspection-at-the-edge.jsonld"}}