Image Recognition Using TensorFlow And Raspberry Pi

Introduction 

 
This article demonstrates how to install TensorFlow and recognize images using Raspberry Pi.
 
Prerequisite
  • Raspberry Pi
  • TensorFlow
  • Putty or VNC View  
About TensorFlow 
  • TensorFlow is a free and open-source software library for dataflow
  • It is a symbolic math library.
  • TensorFlow is a computational framework for building machine learning models.

TensorFlow has two components

  • a graph protocol buffer
  • a runtime that executes the (distributed) graph
Image Recognition Using TensorFlow And Raspberry Pi
 
Types of an image
  • BINARY IMAGE
  • BLACK AND WHITE IMAG
  • 8-bit COLOR FORMAT
  • 16-bit COLOR FORMAT
A 16-bit color format is divided into three different colors which are Red, Green, and Blue (RGB).
 
Step 1
 
Let's go to install the raspbian stretch operating system and also get the latest version of Python, so open the Linux terminal to update Python.
 
Image Recognition Using TensorFlow And Raspberry Pi 
  1. sudo apt-get update    
  2. python --version    
  3. python3 --version    
Installing TensorFlow needs some library file, so Libatlas library is required by the TensorFlow package installation. Once the library file is installed, then install the TensorFlow package.
 
Before installing TensorFlow, install the Atlas library.
  1. sudo apt install libatlas-base-dev  
Once that is finished install TensorFlow via pip3
  1. pip3 install --user tensorflow  
Nowwe've  successfully installed TensorFlowTensorFlow version-1-9-0. 
 
Step 2
 
Once we install the TensorFlow we're ready to test the basic TensorFlow script provided by the TensorFlow site and first, you can test the Hello World program. Now, I create a  new Python file like tftest.py,
  1. sudo nano tftest.py  
Next, you have to import the TensorFlow library. 
  1. import tensorflow as tf  
  2. hello = tf.constant('Hello, TensorFlow')  
  3. sess = tf.Session()  
  4. print (sess.run(hello))  
Just run the code. You can see the hello TensorFlow program is successfully printed.
 
Run the code from the terminal:
  1. python3 tftest.py   
Image Recognition Using TensorFlow And Raspberry Pi 
 
Step 3
 
Clone the TensorFlow classification script.
  1. git clone https://github.com/tensorflow/models.git  
This is a panda image for reference:
 
Image Recognition Using TensorFlow And Raspberry Pi 
 
Once the script is running the panda image will be recognized.
  1. cd models/tutorials/image/imagenet  
  2. python3 classify_image.py  
Source Code
  1. from __future__ import absolute_import  
  2. from __future__ import division  
  3. from __future__ import print_function  
  4.   
  5. import argparse  
  6. import os.path  
  7. import re  
  8. import sys  
  9. import tarfile  
  10.   
  11. import numpy as np  
  12. from six.moves import urllib  
  13. import tensorflow as tf  
  14.   
  15. FLAGS = None  
  16.   
  17.   
  18. DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'  
  19.   
  20. class NodeLookup(object):  
  21.   
  22.   def __init__(self,  
  23.                label_lookup_path=None,  
  24.                uid_lookup_path=None):  
  25.     if not label_lookup_path:  
  26.       label_lookup_path = os.path.join(  
  27.           FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')  
  28.     if not uid_lookup_path:  
  29.       uid_lookup_path = os.path.join(  
  30.           FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')  
  31.     self.node_lookup = self.load(label_lookup_path, uid_lookup_path)  
  32.   
  33.   def load(self, label_lookup_path, uid_lookup_path):  
  34.     if not tf.gfile.Exists(uid_lookup_path):  
  35.       tf.logging.fatal('File does not exist %s', uid_lookup_path)  
  36.     if not tf.gfile.Exists(label_lookup_path):  
  37.       tf.logging.fatal('File does not exist %s', label_lookup_path)  
  38.   
  39.     proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()  
  40.     uid_to_human = {}  
  41.     p = re.compile(r'[n\d]*[ \S,]*')  
  42.     for line in proto_as_ascii_lines:  
  43.       parsed_items = p.findall(line)  
  44.       uid = parsed_items[0]  
  45.       human_string = parsed_items[2]  
  46.       uid_to_human[uid] = human_string  
  47.     node_id_to_uid = {}  
  48.     proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()  
  49.     for line in proto_as_ascii:  
  50.       if line.startswith('  target_class:'):  
  51.         target_class = int(line.split(': ')[1])  
  52.       if line.startswith('  target_class_string:'):  
  53.         target_class_string = line.split(': ')[1]  
  54.         node_id_to_uid[target_class] = target_class_string[1:-2]  
  55.     node_id_to_name = {}  
  56.     for key, val in node_id_to_uid.items():  
  57.       if val not in uid_to_human:  
  58.         tf.logging.fatal('Failed to locate: %s', val)  
  59.       name = uid_to_human[val]  
  60.       node_id_to_name[key] = name  
  61.     return node_id_to_name 
  62.   def id_to_string(self, node_id):  
  63.     if node_id not in self.node_lookup:  
  64.       return ''  
  65.     return self.node_lookup[node_id]  
  66. def create_graph():  
  67.   with tf.gfile.FastGFile(os.path.join(  
  68.       FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:  
  69.     graph_def = tf.GraphDef()  
  70.     graph_def.ParseFromString(f.read())  
  71.     _ = tf.import_graph_def(graph_def, name='')  
  72. def run_inference_on_image(image):   
  73.   if not tf.gfile.Exists(image):  
  74.     tf.logging.fatal('File does not exist %s', image)  
  75.   image_data = tf.gfile.FastGFile(image, 'rb').read() 
  76.   
  77.   create_graph() 
  78.   with tf.Session() as sess:  
  79.     
  80.     softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')  
  81.     predictions = sess.run(softmax_tensor,  
  82.                            {'DecodeJpeg/contents:0': image_data})  
  83.     predictions = np.squeeze(predictions)  
  84.  .  node_lookup = NodeLookup()  
  85.     top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]  
  86.     for node_id in top_k:  
  87.       human_string = node_lookup.id_to_string(node_id)  
  88.       score = predictions[node_id]  
  89.       print('%s (score = %.5f)' % (human_string, score))  
  90.   
  91. def maybe_download_and_extract():  
  92.   dest_directory = FLAGS.model_dir  
  93.   if not os.path.exists(dest_directory):  
  94.     os.makedirs(dest_directory)  
  95.   filename = DATA_URL.split('/')[-1]  
  96.   filepath = os.path.join(dest_directory, filename)  
  97.   if not os.path.exists(filepath):  
  98.     def _progress(count, block_size, total_size):  
  99.       sys.stdout.write('\r>> Downloading %s %.1f%%' % (  
  100.           filename, float(count * block_size) / float(total_size) * 100.0))  
  101.       sys.stdout.flush()  
  102.     filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)  
  103.     print()  
  104.     statinfo = os.stat(filepath)  
  105.     print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')  
  106.   tarfile.open(filepath, 'r:gz').extractall(dest_directory)  
  107.   
  108. def main(_):  
  109.   maybe_download_and_extract()  
  110.   image = (FLAGS.image_file if FLAGS.image_file else  
  111.            os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))  
  112.   run_inference_on_image(image)
  113.   
  114. if __name__ == '__main__':  
  115.   parser = argparse.ArgumentParser()  
  116.   parser.add_argument(  
  117.       '--model_dir',  
  118.       type=str,  
  119.       default='/tmp/imagenet',  
  120.       help="""\ 
  121.     
  122.   )  
  123.   parser.add_argument(  
  124.       '--image_file',  
  125.       type=str,  
  126.       default='',  
  127.       help='Absolute path to image file.'  
  128.   )  
  129.   parser.add_argument(  
  130.       '--num_top_predictions',  
  131.       type=int,  
  132.       default=5,  
  133.       help='Display this many predictions.'  
  134.   )  
  135.   FLAGS, unparsed = parser.parse_known_args()  
  136.   tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)  
OUTPUT 
 
Image Recognition Using TensorFlow And Raspberry Pi
 
The same method is used to classify the external images like the following terminal command.
  1. python3 classify_image.py --image_file=/PATH 
This is the very beginning of the TensorFlow Raspberry pi, just install the TensorFlow and Classify the image.
 

Summary

 
In this article, you learned how to install TensorFlow and do image recognition using TensorFlow and Raspberry Pi.
 
If you have any questions/ feedback/ issues, please write in the comment box.