0
0
Iot-protocolsHow-ToBeginner · 4 min read

Raspberry Pi Project for AI Image Recognition: Setup and Code

You can build an AI image recognition project on Raspberry Pi by installing TensorFlow Lite and using a pre-trained model like MobileNet. Write a Python script to capture images from the camera and run the model to identify objects in real time.
📐

Syntax

This is the basic syntax to load a TensorFlow Lite model and run image recognition on Raspberry Pi:

  • Interpreter(model_path): Loads the AI model file.
  • set_tensor(): Sets the input image data.
  • invoke(): Runs the model inference.
  • get_tensor(): Gets the output predictions.
python
from tflite_runtime.interpreter import Interpreter

# Load the TensorFlow Lite model
interpreter = Interpreter(model_path='model.tflite')
interpreter.allocate_tensors()

# Get input and output details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Prepare input image as numpy array
input_data = ...  # image data preprocessed

# Set input tensor
interpreter.set_tensor(input_details[0]['index'], input_data)

# Run inference
interpreter.invoke()

# Get output tensor
output_data = interpreter.get_tensor(output_details[0]['index'])
💻

Example

This example shows how to capture an image from the Raspberry Pi camera, preprocess it, and run AI image recognition using TensorFlow Lite with MobileNet model.

python
import numpy as np
import cv2
from tflite_runtime.interpreter import Interpreter

# Load TFLite model and allocate tensors
interpreter = Interpreter(model_path='mobilenet_v1_1.0_224.tflite')
interpreter.allocate_tensors()

# Get input and output tensors details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Initialize camera
cap = cv2.VideoCapture(0)

# Capture one frame
ret, frame = cap.read()
cap.release()

if not ret:
    print('Failed to capture image')
    exit()

# Resize frame to model input size
input_shape = input_details[0]['shape']
img = cv2.resize(frame, (input_shape[2], input_shape[1]))

# Convert image to float32 and normalize
input_data = np.expand_dims(img.astype(np.float32) / 255.0, axis=0)

# Set the tensor to the input data
interpreter.set_tensor(input_details[0]['index'], input_data)

# Run inference
interpreter.invoke()

# Get output data
output_data = interpreter.get_tensor(output_details[0]['index'])

# Find the highest confidence label
predicted_label = np.argmax(output_data[0])
confidence = output_data[0][predicted_label]

print(f'Predicted label index: {predicted_label}, confidence: {confidence:.2f}')
Output
Predicted label index: 243, confidence: 0.85
⚠️

Common Pitfalls

  • Wrong model format: Using a TensorFlow model instead of TensorFlow Lite model will cause errors.
  • Incorrect input shape: Not resizing or normalizing the image to the model's expected input size and scale leads to wrong predictions.
  • Camera not initialized: Forgetting to release or properly initialize the camera can cause capture failures.
  • Missing dependencies: Not installing tflite-runtime or opencv-python will break the code.
python
## Wrong way: Using unnormalized input
interpreter.set_tensor(input_details[0]['index'], img)  # img not normalized

## Right way: Normalize input
input_data = np.expand_dims(img.astype(np.float32) / 255.0, axis=0)
interpreter.set_tensor(input_details[0]['index'], input_data)
📊

Quick Reference

Tips for Raspberry Pi AI image recognition projects:

  • Use tflite-runtime for lightweight TensorFlow Lite support.
  • Preprocess images: resize to model input size and normalize pixel values.
  • Use pre-trained models like MobileNet for fast setup.
  • Test camera capture separately before running AI code.
  • Run inference on small images for better performance on Raspberry Pi.

Key Takeaways

Install TensorFlow Lite runtime and use pre-trained models for easy AI image recognition on Raspberry Pi.
Always preprocess images by resizing and normalizing before feeding them to the model.
Test your camera setup independently to avoid capture errors.
Use lightweight models like MobileNet for real-time performance on Raspberry Pi.
Check dependencies like tflite-runtime and OpenCV are installed correctly.