Skip to content

ESP32-CAM · Build guide

ESP32-CAM YOLO Object Detection

Run general YOLO object detection on ESP32-CAM snapshots using a PC, label detected classes and confidence scores, and build a repeatable evaluation workflow.

ESP32-CAM YOLO Object Detection
Difficulty
Advanced
Read time
13 min
Board
ESP32-CAM
Author
Shantanu Kumar Mohanty
Published
Nov 3, 2026
Views
4

ESP32-CAM YOLO Object Detection: Detect and Label Objects

This project combines an ESP32-CAM snapshot endpoint with a computer running YOLO. The camera supplies JPEG images over the local network; Python downloads each image, runs object detection, and reports the labels and confidence scores. This is a general object-detection tutorial—not a parking-space occupancy detector and not a security alert system.

A classic ESP32-CAM usually cannot run a modern YOLO model at a useful speed with the same flexibility as a laptop or mini PC. Running inference on the computer keeps the camera firmware relatively simple and allows you to compare different models without reflashing the board. The trade-off is that the network and computer must stay available.

The reference model is a pretrained Ultralytics model using COCO classes. It can detect common objects such as people, cars, bicycles, chairs, bottles, and dogs, but it will not identify every object or recognise custom equipment unless you use a suitable model trained for those classes. Confidence is a model score, not a guarantee that a label is correct.

Data flow

  1. ESP32-CAM captures and serves a JPEG image.
  2. Python downloads and validates the image.
  3. YOLO predicts bounding boxes and classes.
  4. The program prints the detected label, confidence, and box coordinates.
  5. Optional visualisation draws the boxes on the frame so you can check the result.

Components

4 items
NameQtyLink
AI-Thinker ESP32-CAM with OV2640×1—
USB-to-serial adapter and regulated 5 V supply×1—
Computer with Python 3.10+ and network access×1—
Wi-Fi network connecting camera and computer×1—

Need these parts? Get this build sheet by email

Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.

⚠️ Warning

Keep the camera endpoint on a trusted LAN; the sample camera server may not require authentication. Do not expose it through public router port forwarding. Model weights and packages have their own licences; review them before redistributing the application or using it commercially.

1. Start with a working camera

Flash the official Espressif CameraWebServer example and choose the matching camera model. Configure Wi-Fi, upload using the board's required download-mode procedure, reset the board, and read its IP address from Serial Monitor. Open the camera page and confirm the image is sharp and the snapshot endpoint returns a JPEG.

If the image does not load, do not debug YOLO yet. First check power, serial output, Wi-Fi, and camera initialisation. A stable 5 V supply is important because the camera and Wi-Fi radio produce current peaks. Keep UART logic at 3.3 V when using a USB-to-serial adapter.

2. Install Python dependencies

Create an isolated Python environment:

terminal
python -m venv .venv
python -m pip install --upgrade pip
pip install ultralytics opencv-python requests numpy

The model weights may be downloaded the first time the code runs. Use a machine with internet access during initial setup, then follow the model package's licence and deployment terms. Replace the example IP address in the script with the address printed by your camera.

main.py
import time
import cv2
import numpy as np
import requests
from ultralytics import YOLO

CAMERA_IP = "192.168.1.50"
SNAPSHOT_URL = "http://" + CAMERA_IP + "/capture"
MODEL_NAME = "yolo26n.pt"
CONFIDENCE = 0.45
POLL_SECONDS = 2.0
SHOW_WINDOW = True

model = YOLO(MODEL_NAME)

def get_snapshot():
    response = requests.get(SNAPSHOT_URL, timeout=8)
    response.raise_for_status()
    content_type = response.headers.get("Content-Type", "").lower()
    if "image" not in content_type:
        raise ValueError("Snapshot endpoint did not return an image")
    encoded = np.frombuffer(response.content, dtype=np.uint8)
    frame = cv2.imdecode(encoded, cv2.IMREAD_COLOR)
    if frame is None:
        raise ValueError("Unable to decode camera JPEG")
    return frame

try:
    while True:
        started = time.monotonic()
        frame = get_snapshot()
        result = model.predict(frame, conf=CONFIDENCE, verbose=False)[0]

        if len(result.boxes) == 0:
            print("No objects above the current confidence threshold")
        for box in result.boxes:
            class_id = int(box.cls.item())
            label = model.names.get(class_id, str(class_id))
            confidence = float(box.conf.item())
            x1, y1, x2, y2 = [int(v) for v in box.xyxy[0].cpu().tolist()]
            print("{} {:.2f} box=({}, {}, {}, {})".format(
                label, confidence, x1, y1, x2, y2))

        if SHOW_WINDOW:
            annotated = result.plot()
            cv2.imshow("SolderHub ESP32-CAM object detection", annotated)
            if cv2.waitKey(1) & 0xFF == ord("q"):
                break

        elapsed = time.monotonic() - started
        time.sleep(max(0.0, POLL_SECONDS - elapsed))
finally:
    cv2.destroyAllWindows()

3. Understand the output

A detection is represented by a class label, a confidence score, and a bounding box. The box coordinates are pixel positions in the captured frame. They are useful for drawing, region filtering, or saving structured data, but they do not by themselves indicate object identity or intent.

Raise the confidence threshold to suppress weaker detections; lower it only if you see consistent misses. Always compare settings on real images from the final camera position. A result that looks good indoors can degrade outdoors because of glare, small objects, rain, motion blur, or strong backlighting.

The loop polls a snapshot rather than consuming a continuous video stream. This is easy to understand and useful for periodic checks, but a moving object can enter and leave between captures. If you need fast motion analysis, use the stream-based design in a later section of your system rather than assuming snapshots provide continuous coverage.

4. Test the model systematically

Collect a small evaluation set containing typical scenes and difficult cases. For each image, write down which objects are actually present and whether the model detected them. Record missed objects and incorrect labels separately; otherwise, increasing the threshold may appear to fix false positives while making recall worse.

Use the same camera position, frame size, and lighting for comparisons. If you use images containing people, consider privacy and retention before saving the dataset. Do not train or publish a dataset of private locations without permission.

Troubleshooting

SymptomCheck
Model download failsCheck internet access, package installation, and whether the runtime can write the model cache
Snapshot endpoint returns HTMLUse the exact IP and /capture path; check HTTP status and firmware version
Script shows no detectionsStart with a large, well-lit common object and lower the threshold for diagnostic testing
Display window is unavailableSet SHOW_WINDOW to False when running headless or on a server
CPU usage is highUse a smaller model, reduce polling frequency, or use a machine with suitable acceleration
Results are unstable between framesImprove lighting/framing and validate across more representative images

Extensions

Save annotated frames to a local folder, count detected classes per time interval, or send structured predictions to a local dashboard. Add a server-side queue if inference must continue when the browser is closed. Keep capture, inference, and storage as separate modules so a model swap does not require editing camera firmware.

This design demonstrates general visual detection rather than certified monitoring. For implementation details, read the Ultralytics prediction guide and the Espressif CameraWebServer example.

Steps

  1. 1Verify the ESP32-CAM snapshot in a browser before installing the computer-vision environment.
  2. 2Create a Python virtual environment and install Ultralytics, OpenCV, NumPy, and Requests.
  3. 3Set CAMERA_IP and run the detection loop; confirm that labels and confidence scores match the scene.
  4. 4Adjust confidence only after testing a repeatable set of representative images.
  5. 5Add annotated output, structured logging, or a dashboard after the basic prediction loop is stable.

5. Build a repeatable evaluation set

A useful object detector is judged against scenes it will actually encounter. Collect a small set of representative frames from the final camera position and label which object classes are visible. Include small objects, objects partially out of view, busy backgrounds, reflections, bright daylight, dim light, and different viewing distances. For each image, compare the model's labels to the ground truth and note false positives and missed detections separately.

A confidence score is a ranking signal from the model, not a calibrated probability that the detection is correct. If a box is labelled as a bottle with confidence 0.80, that does not mean it will be correct 80% of the time in your installation. Use an annotated validation set to select a threshold; do not choose it based on how plausible one result looks. A lower threshold tends to retain more detections and can increase false alarms; a higher threshold can make output cleaner while losing smaller or obscured objects.

When saving examples for review, record the camera address identifier, timestamp, model name, image size, confidence threshold, and software version. Avoid saving every frame by default. Sampling one image per interval or saving only diagnostic failures often provides enough information while reducing storage and privacy risk. If images contain people or identifiable private areas, keep the dataset access-controlled and remove it when the experiment ends.

The code displays an annotated OpenCV window for a desktop computer. For a headless mini PC or Linux service, set SHOW_WINDOW to False and replace the window code with structured logging. Write each prediction as a record containing timestamp, label, confidence, and bounding-box coordinates. Keep model inference separate from the logging or dashboard layer so you can change the model without rewriting the camera code.

6. Choose the next improvement by the measured failure

If the model often misses small objects, improve camera framing or reduce the field of view before jumping to a heavier model. If detections vary due to glare, correct the camera angle and exposure. If CPU use is the bottleneck, reduce polling frequency or use a smaller model. If the built-in COCO classes do not include your target, find or train a model whose class set and training data match the task, then check its licence and test performance on data captured by your own camera.

Document what the system has and has not been tested against. A few successful predictions demonstrate that the pipeline works; they do not establish precision, recall, or suitability for critical monitoring. The most valuable extension is often better data, stable mounting, and a measured acceptance test rather than more code.

7. Save predictions without turning the project into a video archive

You can turn the console output into useful measurements without saving every camera frame. For each polling cycle, write a timestamp, model name, confidence threshold, processing time, and the labels with their confidence values. If the task is to count how often a class appears, decide whether you need per-frame presence, unique tracked objects, or a line-crossing event; these are three different quantities and should not share the same label in a dashboard.

A bounded log also makes performance comparisons possible. Test two model weights with the same set of images and the same camera framing, then compare how many ground-truth objects were missed and how many incorrect labels appeared. Record inference latency separately from camera request latency. A slow result may be caused by a weak Wi-Fi link, a large JPEG, or a heavy model, and the fix differs for each case.

For images used in debugging, save only a small sample or selected failure cases. Give each image a timestamp-based filename, store a corresponding metadata row, and avoid overwriting the original image with annotated output. If a reviewer needs to compare the unmodified capture to a model result, keep both only when needed and limit retention. Images that include people or private indoor spaces should not become a public dataset by default.

If you deploy the detector on a mini PC, run it as a service without opening a GUI window, and rotate logs. Add a health endpoint or heartbeat that reports the last processed frame and whether the last model call succeeded. This avoids mistaking a stalled Python process for a stable scene with no objects.

When a class is missing consistently, check whether that class exists in the chosen model before altering code. For a special-purpose object absent from COCO, find or train a compatible model and validate it with your own captured images. Review the model and package licence before distributing it. The strongest next step is usually a clear test set and a documented result rather than a more complicated interface.

Create a reproducible evaluation set

Prepare a small group of representative images or clips from the actual camera position before tuning model settings. Include supported objects at different distances, objects partly hidden, an empty scene, cluttered backgrounds and difficult lighting. Record the expected classes for each sample and inspect the predicted boxes manually. Count false positives and missed detections separately instead of judging success by one convincing screenshot.

The confidence threshold changes the balance between missed objects and weak false detections. Compare a low, medium and high threshold over the same sample set. Record the model weights, package version, camera resolution and threshold so later changes can be compared fairly. Print the loaded model's class names when a filter does not behave as expected; class IDs belong to the loaded model and should not be assumed for a custom model.

The pipeline also includes network transfer, JPEG decoding, image resizing, inference, box drawing and display. Measure total delay as well as frames per second. If a large queue of stale frames builds up, prefer discarding old frames and processing the latest image. Show the timestamp of the last successful frame and a clear offline state during a disconnect. Review current library and model licensing before commercial redistribution. The ESP32-CAM is only the image source in this build; inference runs on the PC.

Topicsesp32-camyoloobject-detectionedge-aicomputer-vision

Questions & Answers