Raspberry Pi based Object Detection using TensorFlow and OpenCV

Object Detection System using TensorFlow and Raspberry Pi

Designing a comprehensive Machine Learning Model that is capable of identifying multiple objects in one image is a challenging task in computer vision. However, with the latest advances in deep learning and object recognition systems, it is easier to develop this multiple object recognition system. Here we will use TensorFlow and OpenCV with Raspberry Pi to build object detection models.

 

TensorFlow's Object Detection API is an open-source framework built on top of TensorFlow that provides a collection of detection models, pre-trained on the COCO dataset, the Kitti dataset, the Open Images dataset, the AVA v2.1 dataset, and the iNaturalist Species Detection Dataset.

 

So in this tutorial, we are going to build an Object Detection System using TensorFlow and Raspberry Pi. We are going to use a pre-trained model from COCO that contains around 330K labeled images.

 

Requirements

  • Raspberry Pi 3 (any version)
  • Pi Camera Module

Here only Raspberry Pi and Pi camera are used to build this Raspberry Pi object detection using TensorFlow. We previously used Pi camera with Raspberry pi, and built few projects using it like-

OpenCV Object Detection using Raspberry Pi

Before proceeding with the project, let's have a look at the prerequisites. Here we need TensorFlow, Object Detection API, Pre-trained object detection model, OpenCV, Protobuf, and some other dependencies in this project.

 

Installing TensorFlow in Raspberry Pi for Object Detection

Before installing the TensorFlow and other dependencies, the Raspberry Pi needs to be fully updated. Use the below commands to update the Raspberry Pi to its latest version:

sudo apt-get update
sudo apt-get upgrade

 

Once the update is finished, install TensorFlow via pip3 using below command:

pip3 install tensorflow

 

Then Install the Atlas library to get support for the TensorFlow, Numpy, and other dependencies. Use the below command to install Atlas:

sudo apt-get install libatlas-base-dev

 

Installing OpenCV in Raspberry Pi 3

Use the following commands to install the required dependencies for installing OpenCV on your Raspberry Pi. We previously used OpenCV with Raspberry Pi in a few projects for License plate recognition and face recognition.

sudo apt-get install libhdf5-dev -y 
sudo apt-get install libhdf5-serial-dev –y 
sudo apt-get install libatlas-base-dev –y 
sudo apt-get install libjasper-dev -y 
sudo apt-get install libqtgui4 –y
sudo apt-get install libqt4-test –y

 

After that, use the below command to install the OpenCV on your Raspberry Pi.

pip3 install opencv-contrib-python==4.1.0.25

 

Installing Protobuf

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. Use the below command to install the Protobuf on your Raspberry Pi:

sudo apt-get install protobuf-compiler

 

Use the below commands to install the rest of the libraries.

pip install --user Cython
pip install --user contextlib2
pip install --user pillow
pip install --user lxml
pip install --user matplotlib

 

Now create a project directory. We are going to keep the TensorFlow models and Protobuf under one folder. Use the below command to create a new project directory called ObjectDetection

mkdir ObjectDetection

 

Now move inside your project directory using the cd command.

cd ObjectDetection

 

And download the TensorFlow's Model from Github.

git clone https://github.com/tensorflow/models.git

 

Next, go inside the ObjectDetection and then inside the research folder and run protobuf from there using this command:

cd /home/pi/ObjectDetection/models/research
protoc object_detection/protos/*.proto --python_out=.

 

Now to check whether this worked or not, go to-models>object_detection>protos and there you can see that for every proto file there's one python file created.

Installing Protobuf

When running locally, the ObjectDetection/models/research/ and slim directories should be appended to PYTHONPATH. This can be done by running the following command from ObjectDetection/models/research/:

export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim

 

Installing SSD_Lite in Raspberry Pi: 

Next, we will download the SSD_Lite model from the TensorFlow detection model zoo which is trained on the COCO dataset. Tensorflow detection model zoo provides a collection of detection models pre-trained on the COCO dataset, the Kitti dataset, the Open Images dataset, the AVA v2.1 dataset, and the iNaturalist Species Detection Dataset. COCO stands for Common Objects in Context; this dataset contains around 330K labeled images. We need to install the SSD_Lite model inside the object_detection directory, so first navigate to object_detection directory using the below command:

cd /home/pi/ObjectDetection/models/research/object_detection

 

Now download and unpack the SSD_Lite model by using the below commands:

wget http://download.tensorflow.org/models/object_detection/ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz
tar -xzvf ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz

 

After installing all the dependencies and SSD_Lite model, you need to create a new python file inside the same directory (object_detection). Use the below command to create a new python file:

sudo nano TensorFlow.py

 

The complete code for OpenCV Object Detection using TensorFlow is given at the end of this page. Copy the code paste it inside this file and save the changes using Ctrl+X > Y >  Enter.

 

Python Code Explanation

Complete python code is given at the end of the page. Here we are explaining the important sections of the code for a better explanation.

 

So at the starting of the code, we import all the required libraries that are going to be used in this project.

import os
import cv2
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
import tensorflow as tf
import argparse
import sys
from utils import label_map_util
from utils import visualization_utils as vis_util

 

The sys.path function is a list that is used to include new file paths that will point to modules that we want to import. This is needed because the working directory is the object_detection folder.

sys.path.append('..')

 

Next, we provide the directory containing the object detection module and Path to frozen detection graph .pb file, which includes the model that is used for object detection.

MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')
PATH_TO_LABELS = os.path.join(CWD_PATH,'data','mscoco_label_map.pbtxt')
NUM_CLASSES = 90

 

Now, we are going to load all the labels. Label maps map indices to category names.

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories=label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

 

Now, load the Tensorflow model into memory.

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

 

Each box around the object indicates that a particular object was detected

detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

 

The score is shown on the result image indicates confidence.

detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')

 

Now, inside the while loop initialize the camera object and set the resolution at (640, 480) and the frame rate at 10 fps

camera = PiCamera()
    camera.resolution = (640,480)
    camera.framerate = 10
    rawCapture = PiRGBArray(camera, size=(640,480))
    rawCapture.truncate(0)

 

Then perform the object detection by running the model with the image as input.

(boxes, scores, classes, num) = sess.run(
            [detection_boxes, detection_scores, detection_classes, num_detections],
            feed_dict={image_tensor: frame_expanded})

 

Visualize the results of the detection by drawing a box around the detected object with the percentage of confidence and the class label of the detected object.

vis_util.visualize_boxes_and_labels_on_image_array(
            frame,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates=True,
            line_thickness=8,
            min_score_thresh=0.40)

 

Testing the TensorFlow based Object Detection

Once everything is set up, navigate to the program directory and launch the object detection program. You will see a window showing a live view from your camera (It can take from 20 to 30 seconds).  Identified objects will have a rectangle drawn around them like shown in the below image:

TensorFlow based Object Detection

Raspberry Pi based Object Detection

With this, we come to the end of this Object Detection using TensorFlow and OpenCV Tutorial. I hope you guys enjoyed this article. If you have questions regarding this project, mention them in the comments section

Code

import os
import cv2
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
import tensorflow as tf
import argparse
import sys
# This is needed since the working directory is the object_detection folder.
sys.path.append('..')
# Import utilites
from utils import label_map_util
from utils import visualization_utils as vis_util
# Name of the directory containing the object detection module we're using
MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'
# Grab path to current working directory
CWD_PATH = os.getcwd()
# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')
# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'data','mscoco_label_map.pbtxt')
# Number of classes the object detector can identify
NUM_CLASSES = 90
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
# Load the Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')
    sess = tf.Session(graph=detection_graph)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
    # Initialize Picamera and grab reference to the raw capture
    camera = PiCamera()
    camera.resolution = (640,480)
    camera.framerate = 10
    rawCapture = PiRGBArray(camera, size=(640,480))
    rawCapture.truncate(0)
    for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
        t1 = cv2.getTickCount()
        # Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
        # i.e. a single-column array, where each item in the column has the pixel RGB value
        frame = np.copy(frame1.array)
        frame.setflags(write=1)
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame_expanded = np.expand_dims(frame_rgb, axis=0)
        # Perform the actual detection by running the model with the image as input
        (boxes, scores, classes, num) = sess.run(
            [detection_boxes, detection_scores, detection_classes, num_detections],
            feed_dict={image_tensor: frame_expanded})
        # Draw the results of the detection (aka 'visulaize the results')
        vis_util.visualize_boxes_and_labels_on_image_array(
            frame,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates=True,
            line_thickness=8,
            min_score_thresh=0.40)
        cv2.putText(frame,"FPS: {0:.2f}".format(frame_rate_calc),(30,50),font,1,(255,255,0),2,cv2.LINE_AA)
        # All the results have been drawn on the frame, so it's time to display it.
        cv2.imshow('Object detector', frame)
        t2 = cv2.getTickCount()
        time1 = (t2-t1)/freq
        frame_rate_calc = 1/time1
        # Press 'q' to quit
        if cv2.waitKey(1) == ord('s'):
            break
        rawCapture.truncate(0)
    camera.close()

Video

30 Comments

My wife and i got quite delighted that Edward could complete his reports from the ideas he got while using the web page. It is now and again perplexing just to choose to be giving out hints which the rest could have been selling. We fully understand we've got you to be grateful to for this. All of the explanations you have made, the straightforward web site navigation, the relationships your site aid to create - it is mostly spectacular, and it is making our son in addition to the family believe that this content is fun, which is really pressing. Thanks for all!

I must point out my affection for your generosity giving support to women who really need help on your issue. Your special dedication to getting the message up and down appears to be exceedingly interesting and have in most cases enabled girls just like me to realize their aims. Your valuable tutorial indicates a great deal to me and extremely more to my mates. Best wishes; from all of us.

Thank you so much for providing individuals with an extraordinarily terrific opportunity to read in detail from this website. It is always very kind and as well , stuffed with fun for me and my office peers to search your site not less than three times in one week to read through the fresh guides you will have. And of course, I'm so actually amazed considering the powerful knowledge you serve. Selected 2 points in this article are unquestionably the most suitable we have had.

You have to be in the directory where you saved the file for which the Python code was provided, which you saved as "Object_detection_picamera.py". If you followed these instructions, it will be "/home/pi/ObjectDetection/models/research/object_detection". This is the command: "python3 Object_detection_picamera.py" and if you want to use your USB camera instead of the picam, you would add the "--usbcam" parameter, i.e. your command will become "python3 Object_detection_picamera.py --usbcam".

Improve your strength, speed, iamazonsurmountwayweightedvest_2021and performance with our selection of weighted training vests.Weighted vests are covered in pockets on the outside and come with a bunch of small, brick-shaped weights that fit in them. Training with the best weighted vest can greatly improve your overall fitness by challenging workouts that are both strengths and opportunities. Weighted vests are vests made of leather or vinyl, which have pockets in which you place the weights that you would like.

I Unquestionably really like your website.. Very good shades & theme. Did you produce this Web page on your own? Make sure you reply again as I’m trying to make my own individual website and would love to find out where you bought this from or just what the concept is named. Thanks!

Hello I am so excited I found your site, I really found you by error, while I was researching on Google for something else, Nonetheless I am here now and would just like to say kudos for a incredible post and a all round exciting blog (I also love the theme/design), I don’t have time to read it all at the moment but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the superb work.|

I'm writing to let you be aware of what a notable experience my wife's princess gained viewing yuor web blog. She even learned such a lot of things, which included what it's like to have an awesome helping mindset to make folks smoothly learn certain extremely tough issues. You undoubtedly did more than our desires. I appreciate you for coming up with these informative, trusted, revealing and also unique tips on the topic to Gloria.

I want to show my thanks to you just for bailing me out of this particular situation. Because of searching throughout the the web and getting solutions that were not beneficial, I believed my entire life was gone. Being alive devoid of the answers to the issues you have fixed as a result of your main short post is a crucial case, and those which may have in a negative way damaged my entire career if I hadn't discovered your blog. The talents and kindness in touching everything was very useful. I am not sure what I would've done if I hadn't encountered such a subject like this. It's possible to at this point relish my future. Thanks for your time very much for this professional and result oriented help. I won't hesitate to refer your web page to any person who should get recommendations about this matter.

I want to express some appreciation to this writer just for rescuing me from this particular problem. Right after surfing around through the online world and meeting thoughts which are not beneficial, I was thinking my entire life was done. Existing devoid of the approaches to the issues you've fixed by means of your good guide is a serious case, and ones that could have in a wrong way affected my entire career if I hadn't discovered your site. Your personal know-how and kindness in dealing with all things was priceless. I am not sure what I would have done if I had not come across such a thing like this. I can at this point look forward to my future. Thanks a lot very much for the expert and sensible guide. I won't be reluctant to suggest your web blog to any individual who needs support about this situation.

I simply wanted to develop a brief message in order to thank you for these nice tactics you are giving out at this site. My prolonged internet research has now been rewarded with good facts and techniques to exchange with my colleagues. I would assert that many of us readers actually are unquestionably fortunate to exist in a notable community with very many brilliant professionals with insightful tactics. I feel truly lucky to have come across your website and look forward to plenty of more fabulous moments reading here. Thank you once more for a lot of things.

I am also writing to make you be aware of of the incredible experience my child developed reading yuor web blog. She discovered plenty of issues, with the inclusion of how it is like to possess a marvelous teaching mood to get other individuals with no trouble understand a variety of multifaceted issues. You truly did more than people's expectations. Thanks for rendering such great, trusted, informative and even fun guidance on your topic to Tanya.

Needed to draft you a little bit of note to help thank you so much as before with the exceptional strategies you have discussed above. It is certainly open-handed of people like you to convey unreservedly what many of us could possibly have made available as an electronic book in order to make some bucks for themselves, specifically considering that you could possibly have tried it in the event you decided. The secrets as well served to become good way to recognize that most people have similar eagerness just like my personal own to understand many more when considering this issue. I think there are several more pleasant instances ahead for individuals that read through your blog post.

I am glad for writing to make you understand what a impressive encounter my princess experienced visiting your web site. She realized so many issues, not to mention what it's like to have a very effective giving style to have other people smoothly fully grasp chosen complex subject areas. You undoubtedly did more than our expected results. I appreciate you for churning out those effective, healthy, revealing and cool tips on that topic to Mary.

I precisely wanted to appreciate you once more. I do not know what I might have gone through in the absence of those thoughts revealed by you regarding such industry. This has been an absolute frightful difficulty in my circumstances, however , taking note of the professional technique you managed the issue forced me to cry with fulfillment. I am just thankful for your advice and then have high hopes you realize what an amazing job you happen to be putting in instructing some other people with the aid of your web blog. I'm certain you haven't got to know any of us.

I am glad for writing to let you be aware of what a exceptional encounter our child gained going through your site. She picked up so many things, most notably what it is like to have an ideal teaching nature to make many others easily grasp chosen very confusing issues. You really surpassed readers' expectations. I appreciate you for presenting those beneficial, safe, explanatory as well as fun tips about that topic to Evelyn.

I and also my friends were actually digesting the great techniques from the website while all of the sudden I had a horrible suspicion I never thanked you for those secrets. Most of the women became for that reason glad to read them and have in effect pretty much been having fun with these things. Thanks for getting considerably thoughtful and also for picking out this kind of magnificent areas millions of individuals are really wanting to know about. My personal honest regret for not expressing appreciation to sooner.

Good post. I be taught something tougher on different blogs everyday. It is going to all the time be stimulating to read content material from other writers and apply slightly one thing from their store. I抎 want to use some with the content on my blog whether you don抰 mind. Natually I抣l provide you with a link in your web blog. Thanks for sharing.

|Coloring your hair at summertime is a good way to add some fashion to your ensemble. Make sure, however, that you do what's necessary to maintain the health of your hair. Spend the money on a solid conditioning treatment meant for colored hair, and use it religiously to keep your color pure and your hair looking healthy.

I'm just writing to make you be aware of what a useful encounter my girl experienced browsing your web site. She realized many issues, which included what it is like to possess an amazing helping heart to let folks really easily know precisely selected very confusing topics. You truly exceeded our desires. Thank you for displaying those beneficial, healthy, informative and as well as easy guidance on this topic to Kate.

An impressive share, I just given this onto a colleague who was doing somewhat evaluation on this. And he in reality bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to debate this, I really feel strongly about it and love reading extra on this topic. If attainable, as you grow to be experience, would you thoughts updating your weblog with more particulars? It is highly helpful for me. Huge thumb up for this weblog publish!

This is the appropriate blog for anyone who desires to seek out out about this topic. You notice a lot its nearly laborious to argue with you (not that I truly would want匟aHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Great stuff, just great!

After study a number of of the weblog posts in your website now, and I really like your approach of blogging. I bookmarked it to my bookmark web site record and can be checking back soon. Pls take a look at my web page as well and let me know what you think.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.