硬件:树莓派3B

软件环境:

1.python3.4

2.tensorflow-1.1.0-cp34-cp34m-linux_armv7l.whl

安装呢,其实网上特别多教程,这里我是使用安装包方式安装的,指令如下:

sudo pip install tensorflow-1.1.0-cp34-cp34m-linux_armv7l.whl


这里重点讲一下使用,网上教程都是如下图所示安装完就可以使用了,但是我安装了好几次,都没有models文件夹,也就是没有classify_image这个文件,所以郁闷了好几天,重装数次都没有,windows和树莓派下面都没有



然后就是在GitHub上面寻找一些线索吧,链接:https://github.com/tensorflow/

然后发现了梦寐以求的models,如下图

将models下载下来,真的有classify_image这个文件,哈哈,开心一会

然后将这个文件拷贝到 /usr/local/lib/python3.4/dist-packages/tensorflow

然后解压缩文件,如下图,就有了classify_image

有了这个,咱们就可以像其他小伙伴一样进行图片识别了,我们来测试一下

在home下新建文件夹 tensorflow-related,里面放入一个测试照片,如下图:

下面开始测试图片识别指令了,

进入到classify_image的目录

cd /usr/local/lib/python3.4/dist-packages/tensorflow/models-master/tutorials/image/imagenet

再输入:python3.4 classify_image.py --model_dir /home/pi/tensorflow-related/model --image_file /home/pi/tensorflow-related/panda.jpg

这样就可以识别到图片是panda了,概率0.87.就可以基本确定了,是吧

其实我们再看下 tensorflow-related 这个文件夹,如下图

咦,居然多了个文件夹啊

看下文件夹里面,下载了识别模型图库 inception-2015-12-05.tgz,并解压缩了

贴出来 classify_image.py的源码

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================="""Simple image classification with Inception.Run image classification with Inception trained on ImageNet 2012 Challenge data
set.This program creates a graph from a saved GraphDef protocol buffer,
and runs inference on an input JPEG image. It outputs human readable
strings of the top 5 predictions along with their probabilities.Change the --image_file argument to any jpg image to compute a
classification of that image.Please see the tutorial and website for a detailed description of how
to use this script to perform image recognition.https://tensorflow.org/tutorials/image_recognition/
"""from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport argparse
import os.path
import re
import sys
import tarfileimport numpy as np
from six.moves import urllib
import tensorflow as tfFLAGS = None# pylint: disable=line-too-long
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-longclass NodeLookup(object):"""Converts integer node ID's to human readable labels."""def __init__(self,label_lookup_path=None,uid_lookup_path=None):if not label_lookup_path:label_lookup_path = os.path.join(FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')if not uid_lookup_path:uid_lookup_path = os.path.join(FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')self.node_lookup = self.load(label_lookup_path, uid_lookup_path)def load(self, label_lookup_path, uid_lookup_path):"""Loads a human readable English name for each softmax node.Args:label_lookup_path: string UID to integer node ID.uid_lookup_path: string UID to human-readable string.Returns:dict from integer node ID to human-readable string."""if not tf.gfile.Exists(uid_lookup_path):tf.logging.fatal('File does not exist %s', uid_lookup_path)if not tf.gfile.Exists(label_lookup_path):tf.logging.fatal('File does not exist %s', label_lookup_path)# Loads mapping from string UID to human-readable stringproto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()uid_to_human = {}p = re.compile(r'[n\d]*[ \S,]*')for line in proto_as_ascii_lines:parsed_items = p.findall(line)uid = parsed_items[0]human_string = parsed_items[2]uid_to_human[uid] = human_string# Loads mapping from string UID to integer node ID.node_id_to_uid = {}proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()for line in proto_as_ascii:if line.startswith('  target_class:'):target_class = int(line.split(': ')[1])if line.startswith('  target_class_string:'):target_class_string = line.split(': ')[1]node_id_to_uid[target_class] = target_class_string[1:-2]# Loads the final mapping of integer node ID to human-readable stringnode_id_to_name = {}for key, val in node_id_to_uid.items():if val not in uid_to_human:tf.logging.fatal('Failed to locate: %s', val)name = uid_to_human[val]node_id_to_name[key] = namereturn node_id_to_namedef id_to_string(self, node_id):if node_id not in self.node_lookup:return ''return self.node_lookup[node_id]def create_graph():"""Creates a graph from saved GraphDef file and returns a saver."""# Creates graph from saved graph_def.pb.with tf.gfile.FastGFile(os.path.join(FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:graph_def = tf.GraphDef()graph_def.ParseFromString(f.read())_ = tf.import_graph_def(graph_def, name='')def run_inference_on_image(image):"""Runs inference on an image.Args:image: Image file name.Returns:Nothing"""if not tf.gfile.Exists(image):tf.logging.fatal('File does not exist %s', image)image_data = tf.gfile.FastGFile(image, 'rb').read()# Creates graph from saved GraphDef.create_graph()with tf.Session() as sess:# Some useful tensors:# 'softmax:0': A tensor containing the normalized prediction across#   1000 labels.# 'pool_3:0': A tensor containing the next-to-last layer containing 2048#   float description of the image.# 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG#   encoding of the image.# Runs the softmax tensor by feeding the image_data as input to the graph.softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0': image_data})predictions = np.squeeze(predictions)# Creates node ID --> English string lookup.node_lookup = NodeLookup()top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]for node_id in top_k:human_string = node_lookup.id_to_string(node_id)score = predictions[node_id]print('%s (score = %.5f)' % (human_string, score))def maybe_download_and_extract():"""Download and extract model tar file."""dest_directory = FLAGS.model_dirif not os.path.exists(dest_directory):os.makedirs(dest_directory)filename = DATA_URL.split('/')[-1]filepath = os.path.join(dest_directory, filename)if not os.path.exists(filepath):def _progress(count, block_size, total_size):sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename, float(count * block_size) / float(total_size) * 100.0))sys.stdout.flush()filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)print()statinfo = os.stat(filepath)print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')tarfile.open(filepath, 'r:gz').extractall(dest_directory)def main(_):maybe_download_and_extract()image = (FLAGS.image_file if FLAGS.image_file elseos.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))run_inference_on_image(image)if __name__ == '__main__':parser = argparse.ArgumentParser()# classify_image_graph_def.pb:#   Binary representation of the GraphDef protocol buffer.# imagenet_synset_to_human_label_map.txt:#   Map from synset ID to a human readable string.# imagenet_2012_challenge_label_map_proto.pbtxt:#   Text representation of a protocol buffer mapping a label to synset ID.parser.add_argument('--model_dir',type=str,default='/tmp/imagenet',help="""\Path to classify_image_graph_def.pb,imagenet_synset_to_human_label_map.txt, andimagenet_2012_challenge_label_map_proto.pbtxt.\""")parser.add_argument('--image_file',type=str,default='',help='Absolute path to image file.')parser.add_argument('--num_top_predictions',type=int,default=5,help='Display this many predictions.')FLAGS, unparsed = parser.parse_known_args()tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

树莓派3B使用tensorflow的classify_image进行物体识别相关推荐

  1. 基于树莓派和tensorflow的物体识别

    『1』对深度学习(Deep Learning)的简单介绍 以下解释来自维基百科: 深度学习是机器学习拉出的分支,它试图使用包含复杂结构或由多重非线性变换构成的多个处理层对数据进行高层抽象的算法. 深度 ...

  2. 树莓派3B+TensorFlow Python3.7

    树莓派踩坑记 安装系统 备份文件 ext2explore-2.2.71 可以读取linux里的文件 只能读不能写!!!备份文件也用这个! 还有个 Etcher-v1.4.4 能读写 试了没成功 保存下 ...

  3. 树莓派3 搭建tensorflow并进行物体识别

    一.踩了一天在树莓派3 搭建tensorflow并进行物体识别验证成功 步骤: 1. 更新国内源 2. 安装tensorflow直接用下载的whl文件 3. 利用手头现成的classify.py 文件 ...

  4. 树莓派python物体识别_基于树莓派和Tensowflow的物体识别

    近来这篇文章很火:How to build a robot that "sees" with $100 and TensorFlow (作者是Lukas,CrowdFlower创始 ...

  5. 树梅派上搭建tensorflow+opencv+pi camera的物体识别

    树梅派上搭建tensorflow+opencv的物体识别 前言 硬件及软件版本 安装及环境配置 模型配置 连接摄像头 树莓派显示 识别截图 前言 此教程参考自https://www.jianshu.c ...

  6. 树莓派3b+目标检测: tflite 运行 mobilenet ssd

    1. 硬件环境:树莓派3b+和USB摄像头 2. 操作系统:2019-09-26-raspbian-buster.zip https://downloads.raspberrypi.org/raspb ...

  7. 在树莓派3B+ 上使用YOLO v3 Tiny进行实时对象检测

    主要参考文章:http://funofdiy.blogspot.com/2018/08/deep-learning-with-raspberry-pi-real.html(需要vpn) https:/ ...

  8. 树莓派3B+、opencv3+PyQt5实现人脸识别门禁系统

    前言 总结.干货.知识点.注意实现.无个人背景(别人不会关心,捂脸) 效果展示 没点效果,没兴趣往下看了吧(反正我是这样) 下面是两个界面:主页和人脸检测界面,主页可以密码锁.以及其他操作(自己按需) ...

  9. python 图片中物体识别_使用TensorFlow识别照片中的物体

    1.环境ubuntu14.04.5 安装TensorFlow sudo pip install --upgrade https://storage.googleapis.com/tensorflow/ ...

最新文章

  1. 独家 | 一文了解强化学习的商业应用2
  2. View绘制原理 —— 画在哪?
  3. selenium一些基本语句
  4. Cassandra-Java(增删查改)
  5. pandas 提取股票价格
  6. 坚持使用GNU/Linux
  7. 【Linux系统编程】fork()函数详解
  8. Java——去除字符串中的中文
  9. 网络技术等级考试知识点
  10. 2020年安卓学习笔记目录
  11. 第七部分:小插曲,Deferred
  12. 1013 数素数 (20 分)—PAT (Basic Level) Practice (中文)
  13. 一文搞定十大排序算法(细)
  14. json-server 模拟数据
  15. 物联网应用开发实践案例-智慧农业
  16. 4年亏损超6亿,摩贝化学赴美上市能否输血成功?
  17. 愤世嫉俗的程序员,总在网上发表言论,当起了“键盘侠”
  18. 解决typescript 提示 Object is possibly ‘null‘
  19. FPGA的六层电梯控制器Verilog语言(二)
  20. 已下载TensorFlow却为什么无法调用?

热门文章

  1. Oracle表复杂查询
  2. PI API 基础函数(一)
  3. ggplot2图形排版:patchwork包简单入门
  4. Apple Pay 在线远程支付
  5. orgchart实现组织结构图
  6. 华为鸿蒙2系统harmonyOS,华为鸿蒙系统明年目标覆盖1亿台以上设备
  7. 【GStreamer】基于NTP+SEI的视频流传输时延测量
  8. useEffect-副作用函数的返回值-清理副作用的写法
  9. 享受知识饕餮盛宴,尽在近期课程安排
  10. 阿里云-网站备案基本流程(2019.7)