Simple image classification on raspberry pi from pi-camera using the pre-trained model VGG16 and TensorFlow

Alex G.
2 min readNov 18, 2020

--

Simple image classification on raspberry pi from pi-camera using the pre-trained model VGG16 (Photo,GIF by Author) https://github.com/oleksandr-g-rock/simple_classification_pi_vgg16_pretrain_model_from_pi_camera/blob/main/1_ERh8oKFSssQrAIiA_Yma_Q.png

Short summary:

In this article, I will explain, how to create simple image classification on raspberry pi from pi-camera using the pre-trained model VGG16.
In this example, I will use the pre-train model VGG16, but you can try to use any pre-train model. All code is located here.

Note before you start:

So, Let’s start :)

Hardware preparation:

Software preparation:

1 So, for that, you need to create a new file image_classify.py with the next code:

#import modules
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
import numpy as np
from picamera import PiCamera
#load imgenet vgg16 model
model = VGG16(weights='imagenet')
#create photo from pi camera
camera = PiCamera()
#save photo with name image.jpeg in this folder
camera.capture('image.jpeg')
#load image and change size to 224*224
img_path = 'image.jpeg'
img = image.load_img(img_path, target_size=(224, 224))
#convert image to array
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
#predict class for image
preds = model.predict(x)
print('Result:', decode_predictions(preds, top=3)[0])

Let me explain what this code will do:

At first, these two lines made a photo and save it to an image.jpeg file

camera = PiCamera()
camera.capture('image.jpeg')

After that, this code will classify (predict top 3 classes) what is in the photo

img_path = 'image.jpeg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Result:', decode_predictions(preds, top=3)[0])

2 run script for recognizing the image.

python3 image_classify.py

3 you should see some predicts in terminal like that

Simple image classification on raspberry pi from pi-camera using the pre-trained model VGG16 (Photo,GIF by Author) https://github.com/oleksandr-g-rock/simple_classification_pi_vgg16_pretrain_model_from_pi_camera/blob/main/1_ERh8oKFSssQrAIiA_Yma_Q.png

Result:

In this article, we created simple image classification on raspberry pi from pi-camera using the pre-trained model VGG16.
In this example, I using the pre-train model VGG16, but you can try to use any pre-train model. All code is located here.

--

--

Alex G.
Alex G.

Written by Alex G.

ML DevOps engineer. 🙂 I am always open to new opportunities and offers. 🖖 I trying to help the world 🌏 with machine learning.

No responses yet