ubuntu 下 anaconda安装环境跑通Tensorflow Object Detection API

本文详细介绍了如何使用Anaconda在Linux环境下创建独立的虚拟环境,避免环境间的相互影响,并逐步指导如何搭建TensorFlow Object Detection API所需的所有依赖,包括安装COCO API、编译Protobuf以及设置GPU模式。

由于本人linux环境比较多,为了避免互相影响,使用anaconda进行环境管理

目录

anaconda安装及环境搭建

软件下载:

创建虚拟环境

激活环境

Tensorflow Object Detection API 环境搭建

下载tensorflow Models:

安装相关环境:

安装tensorflow

COCO API 安装

Protobuf 编译

Protobuf手动安装编译方式

将 slim库目录添加到python路径

测试安装

GPU模式

cuda安装

cudnn安装


 

anaconda安装及环境搭建

软件下载:

anaconda官网下载地址

ubuntu下安装的anaconda3 为了避免影响其他环境,我没有把anaconda加入系统目录

 

创建虚拟环境

用conda创建虚拟环境 在anconda3安装目录里使用命令

./anconda3/bin/conda create --name py35tf python=3.5

 

激活环境

source anaconda3/bin/activate py35tf

如果想退出环境 运行

source deactivate

 

Tensorflow Object Detection API 环境搭建

下载tensorflow Models

linux 终端运行命令:

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

 

安装相关环境:

按照官方说明,安装如下环境

  1. Protobuf 3.0.0
  2. Python-tk
  3. Pillow 1.0
  4. lxml
  5. tf Slim (which is included in the "tensorflow/models/research/" checkout)
  6. Jupyter notebook
  7. Matplotlib
  8. Tensorflow (>=1.9.0)
  9. Cython
  10. contextlib2
  11. cocoapi

安装tensorflow

# For CPU

pip install tensorflow==1.9.0

# For GPU

pip install tensorflow-gpu==1.9.0

 

COCO API 安装

git clone https://github.com/cocodataset/cocoapi.git

cd cocoapi/PythonAPI

make

make成功后生成pycocotools文件夹 将其拷贝到 /models/research/文件夹内

cp -r pycocotools <path_to_tensorflow>/models/research/

 

Protobuf 编译

在 tensorflow/models/research/ 目录下运行 protoc object_detection/protos/*.proto --python_out=.

我测试没有编译成功 改用手动安装编译方式

 

Protobuf手动安装编译方式

下载protobuf.zip并解压,在 tensorflow/models/research/ 目录运行

wget -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.0.0/protoc-3.0.0-linux-x86_64.zip

unzip protobuf.zip

在 tensorflow/models/research/目录运行

./bin/protoc object_detection/protos/*.proto --python_out=.

编译成功

 

将 slim库目录添加到python路径

在 tensorflow/models/research/ 目录运行

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

这句话每次重新进入终端环境都要运行一次

 

测试安装

在 tensorflow/models/research/目录运行

python object_detection/builders/model_builder_test.py

测试成功

 

GPU模式

GPU模式需要安装 cuda 及cudnn

cuda安装

搜索cuda版本

conda search cuda

我这里安装了9.0版本

conda install cudatoolkit==9.0

cudnn安装

搜索cudnn版本

conda search cudnn

cudnn版本要和cuda版本对应上,这里选择安装 7.3.1版本

conda install cudnn==7.3.1

 

anaconda可以直接安装cuda及cudnn到虚拟环境,不会影响其它环境,还是比较方便的。

 


### 如何在Ubuntu上使用TensorFlow实现目标检测 #### 安装必要的软件和库 为了确保能够顺利安装运行TensorFlow的目标检测API,在Ubuntu环境中需要先准备一些基本组件。对于操作系统的支持情况,建议确认当前使用的Ubuntu版本是否兼容所要安装TensorFlow版本。 卸载已有的`tensorflow-gpu`和`keras`以防止版本冲突: ```bash pip uninstall tensorflow-gpu keras ``` 接着按照需求重新安装特定版本的`tensorflow-gpu`以及`keras`: ```bash pip install tensorflow-gpu==1.4.0 keras ``` 这一步骤有助于避免由于不同版本之间的不兼容而导致的问题[^1]。 #### 配置Anaconda环境(可选) 虽然可以直接利用系统自带的Python环境来部署项目,但是考虑到后续可能会涉及到多个项目的开发维护工作,推荐创建独立的工作空间。Anaconda可以轻松管理各个虚拟环境中的包及其依赖关系。可以从官方网站获取适合个人电脑的操作系统对应的Python 3.7版Anaconda发行版,完成安装过程。之后可以根据实际情况决定是否建立新的名为tensorflow的新环境或是继续沿用现有的base环境来进行下一步操作[^3]。 #### 下载设置TensorFlow Object Detection API 访问官方GitHub仓库克隆最新的Object Detection API源代码到本地计算机中。此步骤完成后还需要执行一系列脚本来编译Protobuf文件、安装额外所需的Python模块等前置条件才能使整个工具链正常运作。 ```bash git clone https://github.com/tensorflow/models.git cd models/research/ protoc object_detection/protos/*.proto --python_out=. export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim python setup.py build python setup.py install ``` 上述命令序列完成了对Object Detection API的基础构建任务,使得可以在接下来的任务里调用其功能接口。 #### 运行预训练模型进行快速测试 为了让开发者尽快熟悉这套框架的应用方式,提供了几种已经过充分训练的对象识别模型供即时体验。这些模型覆盖了多种应用场景,比如人物追踪、交标志分类等等。挑选任意一款感兴趣的产品作为起点,加载至程序内即可立即观察效果。 假设选择了MobileNet V2 SSD架构为例,则可以过下面的方式启动预测流程: ```python import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image from IPython.display import display # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") from object_detection.utils import ops as utils_ops from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util # What model to download. MODEL_NAME = 'ssd_mobilenet_v2_coco_2018_03_29' MODEL_FILE = MODEL_NAME + '.tar.gz' DOWNLOAD_BASE = \ 'http://download.tensorflow.org/models/object_detection/' # Path to frozen detection graph. This is the actual model that is used for the object detection. PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb' # List of the strings that is used to add correct label for each box. PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt') NUM_CLASSES = 90 opener = urllib.request.URLopener() opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE) tar_file = tarfile.open(MODEL_FILE) for file in tar_file.getmembers(): file_name = os.path.basename(file.name) if 'frozen_inference_graph.pb' in file_name: tar_file.extract(file, os.getcwd()) detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') 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) def load_image_into_numpy_array(image): (im_width, im_height) = image.size return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8) # For the sake of simplicity we will use only two images: # image1.jpg # image2.jpg # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS. PATH_TO_TEST_IMAGES_DIR = 'test_images' TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ] IMAGE_SIZE = (12, 8) with detection_graph.as_default(): with tf.Session() as sess: # Get handles to input and output tensors ops = tf.get_default_graph().get_operations() all_tensor_names = {output.name for op in ops for output in op.outputs} tensor_dict = {} for key in [ 'num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks' ]: tensor_name = key + ':0' if tensor_name in all_tensor_names: tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name) while True: for image_path in TEST_IMAGE_PATHS: image = Image.open(image_path) # the array based representation of the image will be used later in order to prepare the result image with boxes and labels on it. image_np = load_image_into_numpy_array(image) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Actual detection. output_dict = sess.run(tensor_dict, feed_dict={tf.get_default_graph().get_tensor_by_name('image_tensor:0'): image_np_expanded}) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜡笔小心点

你的鼓励是我创造的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值