Image Classification with EdgeTPU and PiCamera2
This Python script captures images from a Raspberry Pi camera using PiCamera2, classifies them in real-time using a TensorFlow Lite model optimized for the Coral EdgeTPU, and sends classification results via a custom messages module.
Libraries
time: Controls the delay between classification cycles.
numpy: Handles image data and numerical operations.
cv2 (OpenCV): Image resizing and format conversion.
picamera2: Interface for accessing the Raspberry Pi Camera.
tflite_runtime: Lightweight TensorFlow interpreter for running TFLite models.
messages: Custom module to send notifications/messages.
Files and Resources
model_path: Path to the pre-trained quantized MobileNetV3 TFLite model.
label_path: Text file containing class labels.
CONFIDENCE_THRESHOLD: Minimum confidence level required to accept a classification.
Loads the TFLite model and labels used for classification.
Model Interpreter Configuration
Loads the model using the EdgeTPU delegate to run inference on the Coral accelerator.
Retrieves input and output tensor metadata.
Camera Configuration
Initializes the PiCamera with a preview configuration that matches the model’s input size and color format (RGB888, 224×224 pixels).
Main Loop
Runs indefinitely until manually interrupted.
1. Capture Image
Captures a single frame from the PiCamera.
2. Preprocessing
Resizes the image to fit the model’s input shape and adds a batch dimension.
3. Model Inference
Sends the image to the model and triggers inference.
4. Output Extraction
Retrieves the model's top prediction and calculates confidence, normalizing it if necessary.
5. Classification Decision
Compares the confidence score against the threshold.
If confident, prints and sends the result; otherwise sends a default message.
6. Delay Between Inferences
Adds a short delay between cycles to reduce load and avoid redundant classifications.
7. Example Output
Graceful Shutdown
Terminates the program cleanly when interrupted by the user.
Notes
You can adjust CONFIDENCE_THRESHOLD to control the model's sensitivity.
Ensure that libedgetpu.so.1 is correctly installed on your device for EdgeTPU acceleration.