This project presents the design and implementation of a portable computer-vision system for real-time detection of a printed circuit board (PCB). The system combines an ESP32-CAM, an SSD1306 monochrome OLED display, a Linux computer with an NVIDIA RTX 3060 Ti GPU, OpenCV, OpenMMLab MMDetection, Flask, and a custom deep-learning model.
The objective was to create a compact vision node capable of capturing a live image of a PCB, transmitting the image wirelessly to a computer, performing object detection using a fine-tuned RTMDet Tiny model, and returning the detection result to the embedded hardware. When a PCB is detected, the OLED display connected to the ESP32-CAM displays a corresponding status message. At the same time, the processed video stream, including the detection bounding box, is made available through a web browser.
The machine-learning workflow begins with the creation of a custom PCB dataset. Images were annotated using CVAT and exported in COCO format. A Python preprocessing script divides the dataset into training and validation subsets. The RTMDet Tiny object-detection model, originally trained on the COCO dataset, is then fine-tuned using transfer learning so that its detection head contains a single custom PCB class.
The embedded camera system is developed using Espressif ESP-IDF rather than the Arduino framework. The ESP32-CAM operates as a Wi-Fi access point and provides an MJPEG camera stream through an HTTP server. A second HTTP interface is used for communication with the OLED display.
The Linux application receives the camera stream through OpenCV, performs inference using the trained MMDetection model on the GPU, evaluates the confidence of the detected objects, and determines whether a PCB is present. The resulting annotated frames are then delivered to a Flask web server and displayed in a browser.
The completed prototype demonstrates how embedded hardware, wireless communication, computer vision, deep learning, and a web interface can be integrated into a single real-time inspection system.
Keywords: computer vision, artificial intelligence, PCB detection, ESP32-CAM, RTMDet Tiny, MMDetection, OpenMMLab, Flask, OpenCV, CVAT, ESP-IDF, object detection, transfer learning.
Printed circuit boards are fundamental components of modern electronic equipment. They are found in computers, industrial machines, consumer products, embedded systems, measurement equipment, and many other electronic devices.
In manufacturing and inspection applications, computer vision can be used to automatically identify objects and monitor their position. Traditional image-processing techniques can be effective for simple tasks, but modern object-detection systems based on deep learning can provide greater flexibility when the appearance, orientation, lighting, and background of the target object vary.
The purpose of this project was to develop a portable vision AI node Prototype capable of detecting a PCB in real time.
The project combines two different computational environments.
The first is the embedded camera node, based on an ESP32-CAM. Its responsibilities are:
capturing images,
providing wireless communication,
streaming the camera image,
receiving detection-status messages,
controlling the OLED display.
The second is the Linux AI computer. Its responsibilities are:
receiving the camera stream,
running OpenCV,
loading the trained object-detection model,
performing GPU-accelerated inference,
deciding whether a PCB has been detected,
drawing detection results,
providing a browser-based interface.
This separation is important. The ESP32-CAM provides a low-cost and portable camera interface, while the considerably more powerful computer performs the deep-learning calculations.
The project therefore demonstrates a complete vision-AI pipeline rather than only a trained neural network.
The complete system can be represented as:
PORTABLE VISION AI NODEESP32-CAM│┌───────────┴───────────┐│ │Camera OLED│ ▲│ │MJPEG stream Detection status│ │▼ │Wi-Fi link ││ │▼ │Linux PC ││ │OpenCV ││ │▼ │RTMDet Tiny / GPU ││ │├──────────────┐ ││ │ │▼ ▼ │PCB detection Bounding box ││ │ │▼ ▼ │HTTP API Flask server ││ │ │└──────►ESP32 ◄────────┘│▼OLED
The main objective was to create a working prototype capable of detecting a target PCB from a live camera stream.
The project objectives were:
Build a portable camera node using an ESP32-CAM.
Capture and transmit live images over Wi-Fi.
Create a custom PCB image dataset.
Annotate the images using CVAT.
Export the annotations in COCO format.
Prepare the dataset for MMDetection.
Fine-tune RTMDet Tiny using transfer learning.
Perform inference using an NVIDIA RTX 3060 Ti GPU.
Receive the ESP32-CAM stream using OpenCV.
Detect the PCB in real time.
Display a bounding box around the detected PCB.
Send the detection result back to the ESP32-CAM.
Display the result on an SSD1306 OLED.
Provide a browser-based interface using Flask.
Design and build the electronic PCB for the prototype.
Design a physical enclosure.
Assemble and test the complete system.
The final goal was not simply to train an AI model, but to integrate the model into a functioning physical system.
The system is divided into four main layers.
The embedded layer contains:
ESP32-CAM
camera sensor
SSD1306 128 × 64 monochrome OLED
LEDs
resistors
connectors
pin headers
custom PCB
The ESP32-CAM provides the connection between the physical environment and the AI computer.
The ESP32-CAM operates as a Wi-Fi access point.
The camera node provides an HTTP camera stream and a separate HTTP interface for OLED messages.
The camera stream uses:
ESP32-CAM192.168.4.1Port 80
The OLED communication interface uses:
ESP32-CAM192.168.4.1Port 81
This means that an external Wi-Fi router is not required for communication between the camera node and the computer.
The AI layer runs on the Linux computer.
The main software components are:
Python
OpenCV
OpenMMLab MMDetection
RTMDet Tiny
CUDA
PyTorch
Flask
The NVIDIA RTX 3060 Ti is used for GPU-accelerated inference.
The Flask application provides a browser interface.
The browser receives an MJPEG stream containing the annotated camera frames.
The user can therefore observe:
the live camera image,
the detected PCB,
the bounding box,
the confidence score,
the operation of the detection system.
The software development was performed using Linux Mint Cinnamon.
The project uses separate environments for different components. This is particularly useful for machine-learning projects because libraries such as PyTorch, MMCV, MMDetection, CUDA-related packages, and OpenCV may have specific version dependencies.
The main AI environment used for this project was:
mamba activate openmmlab-mmcvMamba was used to manage the Python environment and its dependencies.
The project does not use the Arduino development environment for the ESP32 firmware. Instead, the ESP32-CAM firmware was developed using Espressif's ESP-IDF framework.
The main tools used in the project are:
Component |
Purpose |
|---|---|
Linux Mint |
Development operating system |
Mamba |
Python environment management |
Python |
AI and application programming |
OpenCV |
Image and video processing |
OpenMMLab MMDetection |
Object detection framework |
RTMDet Tiny |
Object-detection model |
PyTorch |
Deep-learning framework |
CUDA |
GPU acceleration |
Flask |
Web application |
CVAT |
Dataset annotation |
ESP-IDF |
ESP32 firmware development |
KiCad |
PCB design |
FreeCAD |
Enclosure design |
After connecting the ESP32-CAM and preparing the software environment, the AI application can be started from a Linux terminal.
First, the required Mamba environment is activated:
mamba activate openmmlab-mmcvThe Flask application can then be started:
python3 flask_openmmlab.pyThe application initializes the trained detection model and starts the real-time processing pipeline.
The Flask web server listens on port 5000.
When running locally, the browser can be opened at:
http://127.0.0.1:5000/The browser interface displays the processed video stream.
The basic startup sequence is:
Power ESP32-CAM│▼ESP32 creates Wi-Fi AP│▼Computer connects to ESP32-CAM│▼Open Linux terminal│▼mamba activate openmmlab-mmcv│▼python3 flask_openmmlab.py│▼Open browser│▼127.0.0.1:5000│▼Live PCB detection
Figure 1. ESP32-CAM connected wirelessly to the Linux computer.
Figure 2. Linux terminal showing the Flask application being started.
A machine-learning object detector requires examples of the object it is expected to recognize.
For this project, the target object was a specific PCB.
The dataset was created using photographs of the PCB under different conditions.
Variation in the dataset is important because a model trained only on nearly identical images may have difficulty recognizing the object when its position, orientation, lighting, or background changes.
The initial dataset contained:
118 annotated images.
The dataset was divided into approximately:
80% training images
20% validation images
This corresponds to approximately:
94 training images
24 validation images
The exact numbers are determined automatically by split_coco.py.
CVAT, the Computer Vision Annotation Tool, was used to create the object-detection annotations.
For each image, a bounding box was placed around the PCB.
The annotation provides the model with two important pieces of information:
the object category;
the location of the object in the image.
The target class used by the model is:
this_is_labelnamed_pcbFor the final version of the project, the class name should be kept identical in CVAT, the COCO dataset, the MMDetection configuration, and the Flask application.
The current source material contains both:
THIS_IS_LABELNAMED_PCBand:
this_is_labelnamed_pcbThese should be standardized before final submission.
The annotation workflow was:
PCB photograph│▼Import image into CVAT│▼Create bounding box│▼Assign PCB class│▼Review annotation│▼Repeat for dataset│▼Export COCO dataset
The bounding box should contain the PCB while avoiding unnecessary background.
Good annotations are important because the neural network learns from the examples provided during training.
Figures 3-10. Examples of PCB images annotated in CVAT.
After annotation, the dataset was exported from CVAT using the COCO object-detection format.
The exported structure contains the images and the annotation JSON file.
Conceptually:
dataset/├──images/│ └──default/└──annotations/└──instances_default.json
The custom split_coco.py
script prepares this dataset for MMDetection.
split_coco.pyThe split_coco.py program randomly
divides the annotated images into training and validation subsets.
A fixed random seed is used:
random_seed = 42This makes the split reproducible.
The training ratio is:
train_ratio = 0.8Therefore, approximately 80% of the images are assigned to the training dataset and 20% to validation.
The script also ensures that annotations remain associated with the correct images.
The resulting structure is:
data/└──pcb/├──train/├──val/├──train.json└──val.json
The complete process is:
CVAT│▼COCO export│▼instances_default.json│▼split_coco.py│├───────────────┐▼ ▼Training Validationimages images│ │▼ ▼train.json val.json│ │└───────┬───────┘▼MMDetection
This preprocessing stage separates the data used for learning from data used to evaluate the model.
The object-detection model selected for this project is RTMDet Tiny.
RTMDet is an object-detection architecture provided through the OpenMMLab ecosystem.
The Tiny version was selected because it provides a useful balance between computational requirements and detection capability.
The project uses transfer learning rather than training a model completely from random initialization.
The original RTMDet Tiny model was trained using the COCO dataset.
COCO contains a large number of images and object categories, allowing the pre-trained model to learn general visual features.
Instead of starting from random weights, this project starts from the pre-trained model:
COCO-trained RTMDet Tiny│▼Pre-trained weights│▼Custom PCB dataset│▼Fine-tuning│▼PCB detection model
This approach is known as transfer learning.
It is particularly useful when the custom dataset is relatively small.
The file:
pcb_custom_config.pycontains the configuration used for the custom PCB detection task.
The configuration inherits the original RTMDet Tiny configuration:
_base_ = './rtmdet_tiny_8xb32-300e_coco.py'This allows the project to reuse the existing model architecture and training settings while modifying the parts that are specific to the PCB dataset.
The original COCO model contains many object classes.
This project requires only one class:
model = dict(bbox_head=dict(num_classes=1))
The class metadata is:
metainfo = {'classes': ('this_is_labelnamed_pcb', ),'palette': [(220, 20, 60),]}
Therefore, the model is specifically configured to detect one PCB class.
The training configuration uses:
Batch size per GPU: 4Workers: 2Maximum epochs: 100Base learning rate: 0.00008Optimizer: AdamWWeight decay: 0.05
The model is trained for a maximum of 100 epochs.
Validation is performed after every epoch.
train_cfg = dict(type='EpochBasedTrainLoop',max_epochs=max_epochs,val_interval=1)
This makes it possible to monitor the model during training and identify the best-performing checkpoint.
The configuration uses a learning-rate schedule consisting of a linear warm-up stage and cosine annealing.
The initial stage is:
LinearLRfollowed by:
CosineAnnealingLRThe purpose of the learning-rate schedule is to control the size of the parameter updates during training.
A relatively small base learning rate was selected because the project is fine-tuning a pre-trained model rather than training the complete detector from scratch.
Data augmentation is used to expose the model to variations of the training images.
The training pipeline includes operations such as:
resizing,
random cropping,
HSV colour augmentation,
horizontal flipping,
padding.
The pipeline can be summarized as:
Original image│▼Load image│▼Load annotations│▼Random resize│▼Random crop│▼HSV colour augmentation│▼Random horizontal flip│▼Padding│▼Training image
These transformations can help reduce the dependence of the model on a single fixed image appearance.
During training, checkpoints are periodically saved.
The configuration specifies:
interval=5and:
max_keep_ckpts=2This limits the number of stored checkpoints and reduces unnecessary disk usage.
The best-performing checkpoint is then used for inference.
The project therefore follows this process:
Training│├──Epoch 1├──Epoch 2├──...├──Epoch 50├──...└──Epoch 100│▼Validation results│▼Best checkpoint│▼Inference
Before implementing real-time detection, the trained model was tested using a single image.
The script:
custom_model_pcb.pyloads the trained configuration and checkpoint.
The configuration is:
config = './pcb_custom_config.py'The trained checkpoint is then loaded.
The inference device is:
device = 'cuda:0'This selects the first CUDA GPU.
The model is initialized with:
inferencer = DetInferencer(config,checkpoint,device)
A test image can then be processed:
img = './pcb_image2.png'result = inferencer(img,out_dir='./output')
The resulting image can contain the detected PCB and its bounding box.
Training and inference are two separate stages.
Training images│▼Annotations│▼RTMDet Tiny│▼Fine-tuning│▼Learned weights│▼.pth checkpoint
.pth checkpoint│▼RTMDet Tiny│▼New image│▼Prediction│▼PCB bounding box
During inference, the model parameters are not updated.
The trained model is simply used to make predictions.
This distinction is important because custom_model_pcb.py
is an inference program, while pcb_custom_config.py
defines the training configuration.
The embedded hardware is based on an ESP32-CAM.
The main hardware components are:
ESP32-CAM
camera module
SSD1306 128 × 64 monochrome OLED
LEDs
resistors
connectors
pin headers
custom PCB
The ESP32-CAM was selected because it combines a microcontroller, Wi-Fi connectivity, and a camera interface in a small module.
The OLED provides a simple physical user interface.
The ESP32-CAM firmware was developed using Espressif ESP-IDF.
The Arduino framework was not used for this project.
The firmware uses components including:
FreeRTOS
ESP camera driver
Wi-Fi
HTTP server
GPIO
NVS
SSD1306 OLED driver
The main firmware responsibilities are:
Initialize OLED│▼Initialize Wi-Fi│▼Initialize camera│▼Start camera HTTP server│▼Start OLED message API│▼Stream camera continuously
The camera is configured for JPEG capture.
The selected frame size is:
VGA640 × 480 pixels
The camera uses two frame buffers in PSRAM.
The configuration contains:
pixel_format = PIXFORMAT_JPEGframe_size = FRAMESIZE_VGAfb_count = 2grab_mode = CAMERA_GRAB_LATESTfb_location = CAMERA_FB_IN_PSRAM
The CAMERA_GRAB_LATEST setting
prioritizes the most recent available frame, which is useful for a
real-time detection application where processing an old frame is less
useful than receiving the latest frame.
The ESP32-CAM operates as a Wi-Fi access point.
The computer connects directly to the ESP32-CAM.
The access point uses:
SSID:ESP32-CAM
The ESP32-CAM uses:
192.168.4.1This architecture means that an external wireless router is not required for the camera-to-computer connection.
The system is therefore suitable for a portable prototype.
The camera server operates on port 80.
The root endpoint:
/provides the camera stream.
The stream uses MJPEG:
multipart/x-mixed-replaceThe camera continuously captures JPEG images and sends them as a sequence of HTTP chunks.
The communication path is:
Camera sensor│▼JPEG frame│▼ESP32 HTTP server│▼Wi-Fi│▼Linux computer│▼OpenCV
The ESP32-CAM does not execute the RTMDet neural network.
It only captures and transmits the image.
A second HTTP server operates on port 81.
The endpoint is:
/messageThe computer can send a message using a request such as:
/message?text=PCB%20DETECTEDThe ESP32 firmware receives the message and displays it on the SSD1306 OLED.
The communication sequence is:
RTMDet Tiny│▼PCB detected│▼Flask application│▼HTTP request│▼ESP32 /message│▼OLED│▼PCB DETECTED
If no PCB is detected, the application sends:
UNDEFINED
The OLED communicates with the ESP32 using I2C.
The firmware defines:
SDA = GPIO 14SCL = GPIO 15
During startup, the display provides basic status information.
The startup sequence is:
START...│▼INITIALIZING...│▼READY
During normal operation, the display is used for the AI detection result.
Example:
┌────────────────┐│PCB DETECTED ││ ││ ││ │└────────────────┘
or:
┌────────────────┐│UNDEFINED ││ ││ ││ │└────────────────┘
This provides a physical indication of the AI result without requiring the user to look at the computer.
GPIO 4 is used to control the camera's integrated LED.
The LED provides additional illumination for the camera.
This is useful because object-detection performance can be affected by image quality and lighting conditions.
The LED is activated while streaming and turned off when the stream stops or an error occurs.
The Flask application is the central software component of the complete system.
It connects:
ESP32-CAM,
OpenCV,
RTMDet Tiny,
GPU inference,
OLED communication,
browser visualization.
The main data path is:
ESP32-CAM│▼MJPEG stream│▼OpenCV│▼RTMDet Tiny│▼Prediction│├───────────────┐▼ ▼OLED status Visualization│▼JPEG frame│▼Flask /video│▼Browser
OpenCV connects to the ESP32-CAM:
cap = cv2.VideoCapture("http://192.168.4.1/")
The OpenCV video capture object receives the MJPEG stream.
Each frame is read using:
ret, frame = cap.read()The frame is then passed to the object-detection model.
The trained model is initialized with:
model = init_detector(config_file,checkpoint_file,device="cuda:0")
The use of:
cuda:0selects the first CUDA-compatible GPU.
In this project, the computer is equipped with an NVIDIA RTX 3060 Ti.
The computational architecture is therefore:
ESP32-CAM││Image▼Linux computer│▼OpenCV│▼RTX 3060 Ti│▼RTMDet Tiny
The division of work makes it possible to use a small embedded camera node while keeping the computationally expensive AI processing on the more powerful computer.
The real-time inference loop continuously reads frames from the ESP32-CAM.
For every valid frame:
result = inference_detector(model,frame)
The model produces object predictions.
Each prediction contains information such as:
class label,
confidence score,
bounding-box coordinates.
The application then examines the predictions.
A confidence threshold of:
0.3is used.
Only predictions with a confidence score greater than 0.3 are considered.
The logic is:
Prediction│▼Confidence > 0.3?│┌──┴──┐No Yes│ │▼ ▼Ignore Check class│▼PCB class?│┌──┴──┐No Yes│ │▼ ▼Ignore PCB DETECTED
The threshold is a practical parameter and could be changed during future testing to study the trade-off between false detections and missed detections.
The application obtains the prediction scores and labels:
scores = (pred_instances.scores.cpu().numpy())labels = (pred_instances.labels.cpu().numpy())
The class name is then obtained from the model metadata.
If the class is:
this_is_labelnamed_pcband the confidence is above 0.3, the system sets:
pcb_found = TrueThe final result is then communicated to the ESP32.
The application does not send the same OLED message repeatedly if the state has not changed.
For example, if 100 consecutive frames contain a PCB, it is unnecessary to send:
PCB DETECTED100 times.
The application stores:
last_messageand sends a new message only when the detection state changes.
This reduces unnecessary HTTP communication between the computer and ESP32-CAM.
A threading lock is used to protect the shared state.
After inference, the MMDetection visualizer is used to draw the predictions.
The application uses:
visualizer.add_datasample(name="result",image=frame,data_sample=result,draw_gt=False,draw_pred=True,pred_score_thr=0.3,show=False,)
The resulting frame contains the predicted bounding box and associated detection information.
This provides direct visual feedback showing where the model believes the PCB is located.
The annotated frame is converted into JPEG format:
success, buffer = cv2.imencode(".jpg",annotated)
The JPEG image is then converted to bytes.
The most recent frame is stored in shared memory:
latest_frameA thread lock protects access to the frame.
This allows the inference thread and Flask server to operate concurrently.
The inference loop runs in a separate background thread.
threading.Thread(target=inference_loop,daemon=True).start()
This is important because Flask needs to remain responsive while the AI model is processing frames.
The architecture is:
Main Flask Process│▼Web requests│▼/video streamBackground Thread│▼ESP32-CAM stream│▼OpenCV frame│▼RTMDet Tiny│▼Annotated JPEG│▼latest_frame│└──────────────►Flask
The root Flask route is:
/The web page contains an image element connected to:
/videoThe browser therefore displays the processed frames produced by the AI pipeline.
The user can open:
http://127.0.0.1:5000/to view the system.
The browser interface acts as a simple monitoring station for the portable vision node prototype.
The Flask application provides the annotated images using multipart HTTP streaming.
The format is:
--frameContent-Type: image/jpegJPEG DATA
The browser receives a continuous sequence of JPEG images and displays them as a live video.
This approach avoids the need for a more complex video-streaming protocol for the prototype.
The electronic hardware was designed using KiCad.
The PCB integrates the required connections between the ESP32-CAM, OLED, power supply, and other components.
The design process includes:
Electrical schematic│▼Component placement│▼PCB routing│▼Design-rule checking│▼3D PCB inspection│▼Manufacturing files│▼PCB fabrication
The completed PCB design was prepared for manufacturing.
The manufacturing process included:
completing the schematic;
assigning footprints;
designing the PCB;
checking the routing;
generating manufacturing files;
submitting the design for PCB fabrication;
receiving the manufactured boards;
inspecting the boards before assembly.
A physical enclosure was designed using FreeCAD.
The purpose of the enclosure is to transform the collection of electronic components into a more practical portable prototype.
The enclosure design considered:
ESP32-CAM position,
camera field of view,
OLED visibility,
PCB dimensions,
mounting points,
cable routing,
ventilation,
access to connectors.
The design process was:
Measure electronics│▼Create enclosure model│▼Position components│▼Check camera field of view│▼Check OLED visibility│▼Manufacture enclosure│▼Assembly
Figure 15. FreeCAD enclosure design.
Figure 16. Completed enclosure.
After manufacturing, the electronic components were assembled.
The assembly process included:
mounting the ESP32-CAM,
connecting the OLED,
installing the PCB,
installing connectors,
checking component orientation,
checking wiring,
installing the enclosure.
Before powering the system, electrical connections were inspected to reduce the risk of incorrect wiring or short circuits.
Measurement |
Measured value |
|---|---|
Supply voltage |
5V |
ESP32 operating voltage |
5 V |
Idle current |
174 mA |
Camera streaming current |
507 mA |
OLED operating current |
N/A mA |
Maximum observed current |
507 mA |
The complete system operates as follows:
1. Power on ESP32-CAM│▼2. Initialize OLED│▼3. Start Wi-Fi access point│▼4. Initialize camera│▼5. Start HTTP camera server│▼6. Start OLED API server│▼7. Connect Linux computer│▼8. Activate Mamba environment│▼9. Start Flask application│▼10. Open ESP32 camera stream│▼11. Receive frames using OpenCV│▼12. Run RTMDet Tiny inference│▼13. Evaluate confidence│▼14. Check PCB class│┌─────┴─────┐▼ ▼PCB No PCB│ │▼ ▼PCB DETECTED UNDEFINED│ │└─────┬─────┘▼15. Send status to ESP32│▼16. Update OLED│▼17. Draw detection box│▼18. Encode annotated frame│▼19. Flask MJPEG stream│▼20. Browser displays result
This represents the complete integration of the embedded and AI systems.
The final prototype was tested as a complete working system.
The demonstration consists of placing the target PCB in front of the camera and observing the system response.
When the PCB enters the camera view, the AI model attempts to identify it.
A successful detection produces:
AI model│├──Bounding box in browser│└──"PCB DETECTED" on OLED
When the PCB is not detected:
AI model│├──No valid PCB detection│└──"UNDEFINED" on OLED
Figure 17. Completed Portable Vision AI prototype.
Figure 18. PCB detection during testing.
The main result of the project is a functioning end-to-end PCB detection prototype.
The system successfully combines:
custom dataset creation;
object annotation;
COCO dataset preparation;
transfer learning;
RTMDet Tiny;
GPU inference;
ESP32-CAM wireless communication;
OpenCV;
Flask;
OLED hardware output;
custom PCB hardware;
mechanical enclosure.
The most important achievement is that the trained AI model was successfully integrated into a physical embedded system.
The project therefore goes beyond a software-only machine-learning experiment.
The AI model receives live data from a physical camera, makes a prediction, and sends the result back to physical hardware.
Metric |
Result |
|---|---|
Training images |
94 |
Validation images |
24 |
Number of classes |
1 |
Training epochs |
100 |
Confidence threshold |
0.30 |
GPU |
NVIDIA RTX 3060 Ti |
|
|
|
|
|
|
One of the main limitations of the project is the size of the custom dataset.
The initial dataset contains only 118 images.
Although the model was able to demonstrate the intended detection functionality, a larger and more diverse dataset would likely improve robustness.
A larger dataset could contain thousands of images covering:
different lighting conditions;
different distances;
different camera angles;
different PCB rotations;
partially obscured PCBs;
different backgrounds;
different exposure levels;
multiple PCBs;
empty scenes;
visually similar objects.
The current system should therefore be considered a working prototype rather than a production-ready industrial inspection system.
Several improvements are possible.
The most obvious improvement would be to increase the number of training images.
For example, a future dataset could contain several thousand carefully selected and annotated images.
The important factor is not only the number of images but also their diversity.
The dataset could include deliberately difficult examples:
low-light images;
reflections;
motion blur;
rotated PCBs;
partially hidden PCBs;
different backgrounds;
PCB-like objects.
This would help evaluate the robustness of the detector.
The current confidence threshold is:
0.3Future testing could compare values such as:
0.20.30.40.50.60.7
The optimal value depends on the desired balance between false positives and missed detections.
The current system makes a detection decision for each frame.
A future version could require a PCB to be detected in several consecutive frames before changing the OLED status.
For example:
Frame 1: PCB detectedFrame 2: PCB detectedFrame 3: PCB detectedFrame 4: PCB detected│▼PCB DETECTED
This could make the output more stable.
The current architecture uses the RTX 3060 Ti computer for inference.
A future version could investigate whether a smaller optimized model could run directly on more powerful edge hardware.
This would make the system more self-contained and reduce the dependence on a separate computer.
The Flask interface could be expanded to show:
FPS;
detection confidence;
connection status;
camera status;
GPU status;
inference latency;
detection history.
A more advanced interface could also provide configuration controls.
The same architecture could be extended from simple PCB presence detection to actual PCB inspection.
A future model could identify:
missing components;
incorrect component placement;
damaged areas;
soldering defects;
connector orientation;
different PCB types.
This would turn the current detection prototype into a more complete automated inspection system.
Several technical challenges were encountered during the development of the project.
The first challenge was integrating multiple software ecosystems. OpenMMLab, PyTorch, CUDA, OpenCV, Flask, and the ESP-IDF environment each have their own dependencies and configuration requirements.
The second challenge was connecting an embedded camera system to a GPU-based computer-vision pipeline.
The ESP32-CAM is capable of capturing and transmitting images, but it does not have the computational resources required to run the RTMDet Tiny model used in this project.
The solution was to divide the system into two parts:
ESP32-CAMCamera + Wi-Fi + OLED│▼Linux computerOpenCV + GPU + AI model
Another challenge was making the real-time system responsive. The inference process was placed in a separate thread so that Flask could continue serving the browser.
The final system therefore required both hardware and software integration.
Several design decisions were made during the project.
ESP-IDF was selected because it provides lower-level access to the ESP32 platform and fits the requirements of the camera, networking, FreeRTOS, and HTTP server implementation.
RTMDet Tiny was selected as a relatively lightweight object detector suitable for real-time experimentation while still providing a modern deep-learning detection architecture.
Starting with COCO-pretrained weights reduces the amount of custom data required compared with training the entire network from scratch.
Using the ESP32-CAM as an access point allows the camera node to operate without an external wireless router.
Flask provides a simple way to expose the processed video through a web browser without introducing unnecessary complexity into the prototype.
The OLED provides an immediate physical output, making it possible to observe the AI decision without looking at the computer.
The current prototype is intended for development and demonstration.
The ESP32-CAM uses a simple Wi-Fi access point and HTTP communication. This is appropriate for a controlled prototype environment but should not be considered a secure production architecture.
A production version could introduce:
stronger credential management;
encrypted communication;
authentication;
input validation;
watchdog recovery;
automatic reconnection;
camera-stream error recovery;
structured logging.
The current system should therefore be regarded as a prototype architecture.
The main project files can be organized as follows:
Portable-Vision-AIprototype/│├──pcb_custom_config.py│├──custom_model_pcb.py│├──flask_openmmlab.py│├──split_coco.py│├──data/│ └──pcb/│ ├──train/│ ├──val/│ ├──train.json│ └──val.json│├──checkpoints/│ └──RTMDet pretrained model│├──work_dirs/│ └──pcb_custom_config/│ └──trained checkpoints│├──output/│ └──inference results│└──ESP32-CAM/├──main/├──components/└──ESP-IDF project files
This structure separates the machine-learning components from the embedded firmware.
split_coco.py
import json import random import shutil from pathlib import Path # ===================================================== # CHANGE THESE PATHS ONLY # ===================================================== dataset_root = Path("dataset") images_dir = dataset_root / "images" / "default" annotation_file = dataset_root / "annotations" / "instances_default.json" output_root = Path("data") / "pcb" train_ratio = 0.8 # 80% train random_seed = 42 # ===================================================== random.seed(random_seed) with open(annotation_file, "r") as f: coco = json.load(f) images = coco["images"] annotations = coco["annotations"] categories = coco["categories"] print(f"Found {len(images)} images") random.shuffle(images) split_index = int(len(images) * train_ratio) train_images = images[:split_index] val_images = images[split_index:] print(f"Training images: {len(train_images)}") print(f"Validation images: {len(val_images)}") train_ids = {img["id"] for img in train_images} val_ids = {img["id"] for img in val_images} train_annotations = [ ann for ann in annotations if ann["image_id"] in train_ids ] val_annotations = [ ann for ann in annotations if ann["image_id"] in val_ids ] train_dir = output_root / "train" val_dir = output_root / "val" train_dir.mkdir(parents=True, exist_ok=True) val_dir.mkdir(parents=True, exist_ok=True) print("Copying training images...") for img in train_images: src = images_dir / img["file_name"] dst = train_dir / img["file_name"] shutil.copy(src, dst) print("Copying validation images...") for img in val_images: src = images_dir / img["file_name"] dst = val_dir / img["file_name"] shutil.copy(src, dst) train_json = { "images": train_images, "annotations": train_annotations, "categories": categories } val_json = { "images": val_images, "annotations": val_annotations, "categories": categories } with open(output_root / "train.json", "w") as f: json.dump(train_json, f) with open(output_root / "val.json", "w") as f: json.dump(val_json, f) print("\nDone!") print(f"Dataset written to: {output_root}")
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_camera.h" #include "esp_http_server.h" #include "esp_log.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_netif.h" #include "nvs_flash.h" #include "driver/gpio.h" #include "ssd1306.h" #define SDA_PIN GPIO_NUM_14 #define SCL_PIN GPIO_NUM_15 static const char *TAG = "ESP32-CAM"; static SSD1306_t dev; #define CAM_GPIO_LED 4 #define CAM_PIN_PWDN 32 #define CAM_PIN_RESET -1 #define CAM_PIN_XCLK 0 #define CAM_PIN_SIOD 26 #define CAM_PIN_SIOC 27 #define CAM_PIN_D7 35 #define CAM_PIN_D6 34 #define CAM_PIN_D5 39 #define CAM_PIN_D4 36 #define CAM_PIN_D3 21 #define CAM_PIN_D2 19 #define CAM_PIN_D1 18 #define CAM_PIN_D0 5 #define CAM_PIN_VSYNC 25 #define CAM_PIN_HREF 23 #define CAM_PIN_PCLK 22 #define STREAM_BOUNDARY "123456789000000000000987654321" static httpd_handle_t stream_server = NULL; static httpd_handle_t api_server = NULL; static esp_err_t camera_init(void) { camera_config_t config = { .pin_pwdn = CAM_PIN_PWDN, .pin_reset = CAM_PIN_RESET, .pin_xclk = CAM_PIN_XCLK, .pin_sccb_sda = CAM_PIN_SIOD, .pin_sccb_scl = CAM_PIN_SIOC, .pin_d7 = CAM_PIN_D7, .pin_d6 = CAM_PIN_D6, .pin_d5 = CAM_PIN_D5, .pin_d4 = CAM_PIN_D4, .pin_d3 = CAM_PIN_D3, .pin_d2 = CAM_PIN_D2, .pin_d1 = CAM_PIN_D1, .pin_d0 = CAM_PIN_D0, .pin_vsync = CAM_PIN_VSYNC, .pin_href = CAM_PIN_HREF, .pin_pclk = CAM_PIN_PCLK, .xclk_freq_hz = 20000000, .ledc_timer = LEDC_TIMER_0, .ledc_channel = LEDC_CHANNEL_0, .pixel_format = PIXFORMAT_JPEG, .frame_size = FRAMESIZE_VGA, .jpeg_quality = 10, .fb_count = 2, .grab_mode = CAMERA_GRAB_LATEST, .fb_location = CAMERA_FB_IN_PSRAM }; esp_err_t ret = esp_camera_init(&config); if(ret != ESP_OK) { ESP_LOGE(TAG,"Camera init failed"); return ret; } sensor_t *s = esp_camera_sensor_get(); s->set_brightness(s,0); s->set_contrast(s,0); ESP_LOGI(TAG,"Camera initialized"); return ESP_OK; } static esp_err_t stream_handler(httpd_req_t *req) { camera_fb_t *fb = NULL; char part_buf[128]; httpd_resp_set_type( req, "multipart/x-mixed-replace;boundary=" STREAM_BOUNDARY ); gpio_set_level( CAM_GPIO_LED, 1 ); while(true) { fb = esp_camera_fb_get(); if(!fb) { gpio_set_level( CAM_GPIO_LED, 0 ); return ESP_FAIL; } size_t hlen = snprintf( part_buf, sizeof(part_buf), "\r\n--" STREAM_BOUNDARY "\r\nContent-Type: image/jpeg" "\r\nContent-Length: %u" "\r\n\r\n", fb->len ); esp_err_t res = httpd_resp_send_chunk( req, part_buf, hlen ); if(res == ESP_OK) { res = httpd_resp_send_chunk( req, (const char *)fb->buf, fb->len ); } esp_camera_fb_return(fb); vTaskDelay(pdMS_TO_TICKS(1)); if(res != ESP_OK) { break; } } gpio_set_level( CAM_GPIO_LED, 0 ); return ESP_OK; } /* * Camera stream URL */ static httpd_uri_t stream_uri = { .uri = "/", .method = HTTP_GET, .handler = stream_handler, .user_ctx = NULL }; /* * Receive message from PC * * Test: * http://192.168.4.1/message?text=PCB%20DETECTED */ static esp_err_t message_handler(httpd_req_t *req) { char text[64] = "NO MESSAGE"; size_t buf_len = httpd_req_get_url_query_len(req) + 1; if(buf_len > 1) { char *buf = malloc(buf_len); if(buf != NULL) { if(httpd_req_get_url_query_str( req, buf, buf_len) == ESP_OK) { httpd_query_key_value( buf, "text", text, sizeof(text) ); } free(buf); } } printf( "OLED MESSAGE: %s\n", text ); ssd1306_clear_screen( &dev, false ); ssd1306_display_text( &dev, 0, text, strlen(text), false ); httpd_resp_sendstr( req, "Message received" ); return ESP_OK; } /* * Message URL */ static httpd_uri_t message_uri = { .uri = "/message", .method = HTTP_GET, .handler = message_handler, .user_ctx = NULL }; static void start_server(void) { // // Camera server // httpd_config_t stream_config = HTTPD_DEFAULT_CONFIG(); stream_config.server_port = 80; if (httpd_start(&stream_server, &stream_config) == ESP_OK) { httpd_register_uri_handler( stream_server, &stream_uri ); ESP_LOGI(TAG, "Camera server started"); } // // API server // httpd_config_t api_config = HTTPD_DEFAULT_CONFIG(); api_config.server_port = 81; // IMPORTANT api_config.ctrl_port += 1; if (httpd_start(&api_server, &api_config) == ESP_OK) { httpd_register_uri_handler( api_server, &message_uri ); ESP_LOGI(TAG, "API server started"); } } static void wifi_ap_init(void) { ESP_ERROR_CHECK( esp_netif_init() ); ESP_ERROR_CHECK( esp_event_loop_create_default() ); esp_netif_create_default_wifi_ap(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK( esp_wifi_init(&cfg) ); wifi_config_t ap_config = { .ap = { .ssid = "ESP32-CAM", .ssid_len = 9, .password = "12345678", .channel = 1, .max_connection = 4, .authmode = WIFI_AUTH_WPA2_PSK } }; ESP_ERROR_CHECK( esp_wifi_set_mode( WIFI_MODE_AP ) ); ESP_ERROR_CHECK( esp_wifi_set_config( WIFI_IF_AP, &ap_config ) ); ESP_ERROR_CHECK( esp_wifi_start() ); ESP_LOGI( TAG, "WiFi AP started" ); ESP_LOGI( TAG, "IP: 192.168.4.1" ); } void app_main(void) { printf( "Starting OLED...\n" ); i2c_master_init( &dev, SDA_PIN, SCL_PIN, -1 ); ssd1306_init( &dev, 128, 64 ); ssd1306_clear_screen( &dev, false ); ssd1306_display_text( &dev, 0, "START...", 8, false ); vTaskDelay( pdMS_TO_TICKS(2000) ); ssd1306_clear_screen( &dev, false ); ssd1306_display_text( &dev, 0, "INITIALIZING...", 16, false ); vTaskDelay( pdMS_TO_TICKS(3000) ); ssd1306_clear_screen( &dev, false ); ssd1306_display_text( &dev, 0, "READY", 5, false ); ESP_ERROR_CHECK( nvs_flash_init() ); gpio_reset_pin( CAM_GPIO_LED ); gpio_set_direction( CAM_GPIO_LED, GPIO_MODE_OUTPUT ); gpio_set_level( CAM_GPIO_LED, 0 ); wifi_ap_init(); vTaskDelay( pdMS_TO_TICKS(1000) ); if(camera_init() == ESP_OK) { start_server(); } }
custom_model_pcb.py
from mmdet.apis import DetInferencer
import glob
# Choose to use a config
config = './pcb_custom_config.py'
# Setup a checkpoint file to load
checkpoint = glob.glob('./work_dirs/pcb_custom_config/best_coco_bb*pth')[0]
# Set the device to be used for evaluation
device = 'cuda:0'
# Initialize the DetInferencer
inferencer = DetInferencer(config, checkpoint, device)
# Use the detector to do inference
img = './pcb_image2.png'
result = inferencer(img, out_dir='./output')
from flask import Flask, Response
import cv2
import threading
import time
import requests
from mmdet.apis import init_detector, inference_detector
from mmdet.registry import VISUALIZERS
app = Flask(__name__)
# -------------------------------------------------------------
# MMDetection Model
# -------------------------------------------------------------
config_file = "./pcb_custom_config.py"
checkpoint_file = (
"./work_dirs/pcb_custom_config/"
"best_coco_bbox_mAP_epoch_89.pth"
)
model = init_detector(
config_file,
checkpoint_file,
device="cuda:0"
)
# Visualizer
visualizer = VISUALIZERS.build(
model.cfg.visualizer
)
visualizer.dataset_meta = model.dataset_meta
# -------------------------------------------------------------
# ESP32 OLED Communication
# -------------------------------------------------------------
ESP32_API = "192.168.4.1:81"
last_message = None
message_lock = threading.Lock()
def send_oled_message(text):
global last_message
with message_lock:
if text == last_message:
return
last_message = text
try:
response = requests.get(
f"http://{ESP32_API}/message",
params={
"text": text
},
timeout=1
)
print(
"OLED MESSAGE:",
text,
response.status_code
)
except Exception as e:
print(
"ESP32 ERROR:",
e
)
# -------------------------------------------------------------
# Camera
# -------------------------------------------------------------
cap = cv2.VideoCapture(
"http://192.168.4.1/"
)
if not cap.isOpened():
raise RuntimeError(
"Could not open video stream."
)
# -------------------------------------------------------------
# Shared frame storage
# -------------------------------------------------------------
latest_frame = None
frame_lock = threading.Lock()
def inference_loop():
global latest_frame
while True:
ret, frame = cap.read()
if not ret:
time.sleep(0.1)
continue
# -----------------------------------------
# MMDetection inference
# -----------------------------------------
result = inference_detector(
model,
frame
)
# -----------------------------------------
# PCB Detection Decision
# -----------------------------------------
pcb_found = False
pred_instances = result.pred_instances
if len(pred_instances) > 0:
scores = (
pred_instances
.scores
.cpu()
.numpy()
)
labels = (
pred_instances
.labels
.cpu()
.numpy()
)
for score, label in zip(scores, labels):
if score > 0.3:
class_name = (
model
.dataset_meta["classes"][label]
)
print(
"Detected:",
class_name,
score
)
if class_name == "this_is_labelnamed_pcb":
pcb_found = True
break
if pcb_found:
send_oled_message(
"PCB DETECTED"
)
else:
send_oled_message(
"UNDEFINED"
)
# -----------------------------------------
# Draw predictions
# -----------------------------------------
visualizer.add_datasample(
name="result",
image=frame,
data_sample=result,
draw_gt=False,
draw_pred=True,
pred_score_thr=0.3,
show=False,
)
annotated = visualizer.get_image()
# -----------------------------------------
# Encode JPEG
# -----------------------------------------
success, buffer = cv2.imencode(
".jpg",
annotated
)
if not success:
continue
jpg = buffer.tobytes()
with frame_lock:
latest_frame = jpg
# -------------------------------------------------------------
# Start inference thread
# -------------------------------------------------------------
threading.Thread(
target=inference_loop,
daemon=True
).start()
# -------------------------------------------------------------
# MJPEG Generator
# -------------------------------------------------------------
def generate():
global latest_frame
while True:
with frame_lock:
frame = latest_frame
if frame is None:
time.sleep(0.05)
continue
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n"
+ frame
+ b"\r\n"
)
time.sleep(0.03)
# -------------------------------------------------------------
# Web page
# -------------------------------------------------------------
@app.route("/")
def index():
return """
<!DOCTYPE html>
<html>
<head>
<title>
PCB Detection
</title>
</head>
<body>
<h2>
MMDetection PCB Stream
</h2>
<img
src="/video"
width="800"
>
</body>
</html>
"""
# -------------------------------------------------------------
# Video stream
# -------------------------------------------------------------
@app.route("/video")
def video():
return Response(
generate(),
mimetype=
"multipart/x-mixed-replace; boundary=frame"
)
# -------------------------------------------------------------
# Run
# -------------------------------------------------------------
if __name__ == "__main__":
app.run(
host="0.0.0.0",
port=5000,
debug=False,
threaded=True
)
The complete pcb_custom_config.py
file is included in the appendix.
# Inherit and overwrite part of the config based on this config
_base_ = './rtmdet_tiny_8xb32-300e_coco.py'
data_root = 'data/pcb/' # dataset root
train_batch_size_per_gpu = 4
train_num_workers = 2
max_epochs = 100
stage2_num_epochs = 1
base_lr = 0.00008
metainfo = {
'classes': ('this_is_labelnamed_pcb', ),
'palette': [
(220, 20, 60),
]
}
train_dataloader = dict(
batch_size=train_batch_size_per_gpu,
num_workers=train_num_workers,
dataset=dict(
data_root=data_root,
metainfo=metainfo,
data_prefix=dict(img='train/'),
ann_file='train.json'))
val_dataloader = dict(
dataset=dict(
data_root=data_root,
metainfo=metainfo,
data_prefix=dict(img='val/'),
ann_file='val.json'))
test_dataloader = val_dataloader
val_evaluator = dict(ann_file=data_root + 'val.json')
test_evaluator = val_evaluator
model = dict(bbox_head=dict(num_classes=1))
# learning rate
param_scheduler = [
dict(
type='LinearLR',
start_factor=1.0e-5,
by_epoch=False,
begin=0,
end=10),
dict(
# use cosine lr from 10 to 20 epoch
type='CosineAnnealingLR',
eta_min=base_lr * 0.05,
begin=max_epochs // 2,
end=max_epochs,
T_max=max_epochs // 2,
by_epoch=True,
convert_to_iter_based=True),
]
train_pipeline_stage2 = [
dict(type='LoadImageFromFile', backend_args=None),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='RandomResize',
scale=(640, 640),
ratio_range=(0.1, 2.0),
keep_ratio=True),
dict(type='RandomCrop', crop_size=(640, 640)),
dict(type='YOLOXHSVRandomAug'),
dict(type='RandomFlip', prob=0.5),
dict(type='Pad', size=(640, 640), pad_val=dict(img=(114, 114, 114))),
dict(type='PackDetInputs')
]
# optimizer
optim_wrapper = dict(
_delete_=True,
type='OptimWrapper',
optimizer=dict(type='AdamW', lr=base_lr, weight_decay=0.05),
paramwise_cfg=dict(
norm_decay_mult=0, bias_decay_mult=0, bypass_duplicate=True))
default_hooks = dict(
checkpoint=dict(
interval=5,
max_keep_ckpts=2, # only keep latest 2 checkpoints
save_best='auto'
),
logger=dict(type='LoggerHook', interval=5))
custom_hooks = [
dict(
type='PipelineSwitchHook',
switch_epoch=max_epochs - stage2_num_epochs,
switch_pipeline=train_pipeline_stage2)
]
# load COCO pre-trained weight
load_from = './checkpoints/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth'
train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=1)
visualizer = dict(vis_backends=[dict(type='LocalVisBackend'),dict(type='TensorboardVisBackend')])
Inspected the PCB from JLCPCB and soldered the components:
This project successfully demonstrates the integration of artificial intelligence with embedded hardware to create a portable real-time vision system.
A custom dataset of PCB images was created and annotated using CVAT. The annotations were exported in COCO format and prepared for MMDetection using a custom Python preprocessing script.
The RTMDet Tiny object-detection model was adapted to the custom PCB detection task using transfer learning. Instead of training the model from the beginning, COCO-pretrained weights were used as the starting point and the model was fine-tuned using the custom PCB dataset.
The trained model was first tested using individual images and was then integrated into a real-time application.
The ESP32-CAM provides the physical camera interface and wireless communication. It captures JPEG images and transmits them through an MJPEG HTTP stream. The Linux computer receives these images using OpenCV and performs the computationally intensive neural-network inference using an NVIDIA RTX 3060 Ti GPU.
When a PCB is detected with sufficient confidence, the Flask application sends the detection status back to the ESP32-CAM. The ESP32 then displays the result on an SSD1306 OLED.
At the same time, the annotated camera image is encoded as JPEG and provided through Flask as an MJPEG browser stream.
The final system can therefore be summarized as:
PORTABLE VISION AICamera│▼ESP32-CAM│Wi-Fi│▼OpenCV│▼RTMDet Tiny│RTX 3060 Ti│▼PCB detection│ ││ │▼ ▼OLED Browser│ │▼ ▼Physical Visualoutput output
The project demonstrates that a relatively small embedded camera platform can be combined with a powerful external AI computer to create a practical computer-vision prototype.
The most significant future improvement would be to expand the dataset substantially and evaluate the model quantitatively under a wider range of real-world conditions. With a larger and more diverse dataset, improved temporal filtering, optimized inference, and a more robust embedded architecture, the prototype could be developed further toward an automated PCB inspection system.
The completed project therefore provides a practical demonstration of the complete development cycle of a vision-AI system: data collection, annotation, model training, embedded firmware, wireless communication, real-time inference, hardware output, web visualization, PCB design, mechanical design, assembly, and testing.