Manufacturing defect detection is one of the highest-ROI applications of computer vision. A single missed scratch or crack on an assembly line costs real money. YOLOv8 makes it straightforward to train a detector that spots defects in real time, and wrapping it in a FastAPI service means any system on your factory floor can call it over HTTP.
Here’s the full pipeline: dataset prep, training, inference with OpenCV annotations, and a production-ready API.
Prepare Your Dataset
YOLOv8 expects images and labels in a specific directory layout, plus a YAML config that describes the dataset. Each label file has one row per defect bounding box in normalized class x_center y_center width height format.
| |
Create the dataset.yaml that tells Ultralytics where everything lives and what your classes are:
| |
Adjust the class names to match your actual defect types. Label files use the same integer IDs. A label line like 2 0.45 0.30 0.10 0.08 means class crack centered at 45% across, 30% down, spanning 10% width and 8% height of the image.
If you’re labeling from scratch, tools like CVAT or Label Studio export directly to YOLO format. Aim for at least 200 images per class for a usable baseline.
Train YOLOv8 on Your Defect Dataset
Training takes a few lines. Start from a pretrained checkpoint so the model already understands edges, textures, and shapes – it just needs to learn what your specific defects look like.
| |
The patience parameter enables early stopping, which prevents overfitting on small datasets. Training outputs land in runs/detect/defect_detector/, including best.pt (the checkpoint with the lowest validation loss) and metrics like mAP@50.
For a production model, swap yolov8n.pt with yolov8m.pt or yolov8l.pt. The nano variant trains fast and is great for prototyping, but medium or large models catch subtle defects more reliably.
Run Inference and Annotate with OpenCV
Once you have a trained model, load it and run predictions on new images. YOLOv8’s predict method returns structured results you can iterate over. Use OpenCV to draw bounding boxes and save annotated images for review.
| |
The conf=0.5 threshold filters out low-confidence predictions. Lower it to 0.3 if you’d rather catch more defects at the cost of some false positives – for quality control, false positives are usually cheaper than misses.
Deploy as a FastAPI Endpoint
Wrapping the model in a REST API lets any system on your network request inspections. Use FastAPI’s lifespan context manager to load the model once at startup and share it across requests.
| |
Run it with uvicorn main:app --host 0.0.0.0 --port 8000. Test with curl:
| |
The response returns a JSON array of detected defects with class names, confidence scores, and pixel-coordinate bounding boxes. From here you can trigger alerts, log defects to a database, or feed results into a factory dashboard.
Common Errors and Fixes
RuntimeError: Dataset not found – Double-check that the path in your dataset.yaml is an absolute path, and that train and val paths are relative to it. A trailing slash or typo in the directory name is the usual culprit.
Low mAP after training – If your mAP@50 is below 0.5, you likely need more labeled data or your defects are too small relative to the image size. Try increasing imgsz to 1280 or cropping images tighter around the region of interest before labeling.
cv2.error: (-215:Assertion failed) !_src.empty() – OpenCV could not read the image. Verify the file path exists and the image is not corrupted. When receiving uploads via FastAPI, make sure you’re decoding the bytes with cv2.imdecode as shown above, not passing a file path.
Slow inference on CPU – YOLOv8 nano runs at roughly 20-40 FPS on a modern CPU. If that’s not enough, export to ONNX for faster CPU inference: model.export(format="onnx"), then load with YOLO("best.onnx").
ModuleNotFoundError: No module named 'ultralytics' – Install the package with pip install ultralytics. It pulls in PyTorch and OpenCV as dependencies automatically.
Related Guides
- How to Build Video Analytics Pipelines with OpenCV and Deep Learning
- How to Build a Lane Detection Pipeline with OpenCV and YOLO
- How to Build a Video Surveillance Analytics Pipeline with YOLOv8
- How to Build a Wildlife Camera Trap Classifier with YOLOv8 and FastAPI
- How to Build a Vehicle Counting Pipeline with YOLOv8 and OpenCV
- How to Build a Visual Inspection Pipeline with Anomaly Detection
- How to Detect Objects in Images with YOLOv8
- How to Build Multi-Object Tracking with DeepSORT and YOLOv8
- How to Train a Custom Object Detection Model with Ultralytics
- How to Build a Panoramic Image Stitching Pipeline with OpenCV