Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
TensorFlow Lite is a lightweight version of Google's TensorFlow, designed specifically for mobile and embedded devices. It enables the deployment of machine learning models on devices with limited computational resources, making it an ideal solution for Raspberry Pi projects. Raspberry Pi, being a versatile and affordable single-board computer, can be used for a wide range of AI and machine learning applications. In this article, we will explore how to set up and run TensorFlow Lite on a Raspberry Pi, providing practical examples to help you get started.
Examples:
Before installing TensorFlow Lite, ensure your Raspberry Pi is up to date. Open a terminal and run the following commands:
sudo apt-get update
sudo apt-get upgrade
TensorFlow Lite requires some additional libraries. Install them using the following command:
sudo apt-get install libatlas-base-dev
You can install TensorFlow Lite using pip. Run the following command:
pip3 install tflite-runtime
For this example, we will use a pre-trained image classification model. Download the model using the following command:
wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/cats_vs_dogs.tflite
Create a new Python script named classify_image.py
and add the following code:
import numpy as np
import tflite_runtime.interpreter as tflite
from PIL import Image
# Load the TFLite model and allocate tensors
interpreter = tflite.Interpreter(model_path="cats_vs_dogs.tflite")
interpreter.allocate_tensors()
# Get input and output tensors
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Load an image and preprocess it
image = Image.open("cat.jpg").resize((224, 224))
input_data = np.expand_dims(image, axis=0).astype(np.float32)
# Run the model
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
# Get the result
output_data = interpreter.get_tensor(output_details[0]['index'])
print("Predicted label:", np.argmax(output_data))
Ensure you have an image named cat.jpg
in the same directory as your script. Run the script using the following command:
python3 classify_image.py
For better performance, you can enable GPU acceleration. First, install the necessary drivers:
sudo apt-get install libgles2-mesa-dev
Update your classify_image.py
script to use the GPU delegate:
interpreter = tflite.Interpreter(model_path="cats_vs_dogs.tflite", experimental_delegates=[tflite.load_delegate('libedgetpu.so.1')])
Run the script again to see the performance improvement:
python3 classify_image.py