Win 10安装Tensorflow目标检测API(三大步7小步)

第一步:下载源码

1、从官网(https://github.com/tensorflow/models/tree/master)下载目标检测的源码,注意版本需要一致!!!

(本人使用的 r1.13.0版本进行下载的)

选择自己的版本

2、解压到想要安装的文件夹内,并将文件夹命名为models(不是必须)

第二步:编译文件

3、安装protoc(https://github.com/protocolbuffers/protobuf/releases),选择合适的版本解压后(位置任意)。接着将bin文件夹下的protoc.exe复制到C:\Windows\System32文件夹下。cmd打开命令行界面,输入命令protoc,若无异常信息表示安装成功!

选择合适的版本

4、编译proto文件。在models/research下运行Windows PowerShell(注意,这里必须是PowerShell,运行cmd会报错,cmd中输入powershell即可进入该命令窗口),输入如下命令:

Get-ChildItem object_detection/protos/*.proto | Resolve-Path -Relative | %{ protoc $_ --python_out=. }
运行完成后,可以检查object_detection/protos/文件夹,如果每个proto文件都成了对应的以py为后缀的python源码,就说明编译成功了。


第三步:安装测试注意:若是在Anaconda且多环境下,需要直接使用activate进入需要的环境中进行输入命令!!!


[后来发现删除了也不影响] 5、添加环境变量。在Anaconda\Lib\site-packages添加一个路径文件,如tensorflow_model.pth,必须以.pth为后缀,写上你要加入的模块文件所在的目录名称,一共两条:①models\research的绝对路径②models\research\slim的绝对路径

6、在models/research/slim下依次运行如下命令:

python setup.py buildpython setup.py install
要是slim文件下已经有了BUILD,需要先删掉这个,然后再python setup.py install
还有 在models/research下同样操作

7、安装完成测试。

进入models\research输入python object_detection/builders/model_builder_test.py
出现OK信息则表示安装成功

8、(高版本需要)安装COCO API,推荐安装

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

cd cocoapi/PythonAPI

python setup.py build

python setup.py install

9、py文件测试(Jupyter notebook测试网上很多,就不介绍了)

本人使用Pycharm打开models文件,如下图

文件结构

在models\research目录里创建一个文件夹如 my_download_pretrained用来保存预训练模型,之后创建一个文件写入下述代码: 注使用方法:
  • 下载预训练模型解压后放入创建的文件夹内(当然也可以其他地方)
  • 修改变量PATH_TO_CKPT指向对应预训练模型的frozen_inference_graph.pb文件(具体查看代码示例)
  • 运行即可(本人显示图像的方式是OpenCV,不过设置了保存到当前目录下图片,也可以手动查看图像)
# -*- coding: utf-8 -*-
"""
Created on Tue Jun  5 20:34:06 2018

@author: https://www.cnblogs.com/zyly/p/9248394.html#_label4
"""

'''
调用Object Detection API进行实物检测   需要GPU运行环境,CPU下会报错

模型下载网址(下载后的模型解压后放在预先创建的文件夹内):
https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf1_detection_zoo.md

TensorFlow  生成的  .ckpt 和  .pb 都有什么用?
https://www.cnblogs.com/nowornever-L/p/6991295.html
如何用Tensorflow训练模型成pb文件(一)——基于原始图片的读取
https://blog.csdn.net/u011463646/article/details/77918980?fps=1&locationNum=7
'''

import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
from PIL import Image

def test():
    # 重置图
    tf.reset_default_graph()
    '''
    载入模型以及数据集样本标签,加载待测试的图片文件
    '''
    # 指定要使用的模型的路径  包含图结构,以及参数
    PATH_TO_CKPT = r'./my_download_pretrained\ssd_resnet50_v1_fpn_shared_box_predictor_640x640_coco/frozen_inference_graph.pb'

    # 测试图片所在的路径
    PATH_TO_TEST_IMAGES_DIR = './object_detection/test_images'

    TEST_IMAGE_PATHS = [os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3)]

    # 数据集对应的label mscoco_label_map.pbtxt文件保存了index到类别名的映射
    PATH_TO_LABELS = os.path.join('./object_detection/data', 'mscoco_label_map.pbtxt')

    NUM_CLASSES = 90

    # 重新定义一个图
    output_graph_def = tf.GraphDef()

    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        # 将*.pb文件读入serialized_graph
        serialized_graph = fid.read()
        # 将serialized_graph的内容恢复到图中
        output_graph_def.ParseFromString(serialized_graph)
        # print(output_graph_def)
        # 将output_graph_def导入当前默认图中(加载模型)
        tf.import_graph_def(output_graph_def, name='')

    print('模型加载完成')

    # 载入coco数据集标签文件
    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)

    '''
    定义session
    '''

    def load_image_into_numpy_array(image):
        '''
        将图片转换为ndarray数组的形式
        '''
        im_width, im_height = image.size
        return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint0)

    # 设置输出图片的大小
    IMAGE_SIZE = (12, 8)

    # 使用默认图,此时已经加载了模型
    detection_graph = tf.get_default_graph()

    with tf.Session(graph=detection_graph) as sess:
        for image_path in TEST_IMAGE_PATHS:
            image = Image.open(image_path)
            # 将图片转换为numpy格式
            image_np = load_image_into_numpy_array(image)

            '''
            定义节点,运行并可视化
            '''
            # 将图片扩展一维,最后进入神经网络的图片格式应该是[1,?,?,3]
            image_np_expanded = np.expand_dims(image_np, axis=0)

            '''
            获取模型中的tensor
            '''
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

            # boxes用来显示识别结果
            boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

            # Echo score代表识别出的物体与标签匹配的相似程度,在类型标签后面
            scores = detection_graph.get_tensor_by_name('detection_scores:0')
            classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')

            # 开始检查
            boxes, scores, classes, num_detections = sess.run([boxes, scores, classes, num_detections],
                                                              feed_dict={image_tensor: image_np_expanded})

            # 可视化结果
            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                np.squeeze(boxes),
                np.squeeze(classes).astype(np.int32),
                np.squeeze(scores),
                category_index,
                use_normalized_coordinates=True,
                line_thickness=8)
            plt.figure(figsize=IMAGE_SIZE)
            print(type(image_np))
            print(image_np.shape)
            image_np = np.array(image_np, dtype=np.uint8)

            #  显示图像,其他方式也可以
            im = Image.fromarray(image_np)
            im.save("out.jpeg")

            import cv2
            img = cv2.imread("out.jpeg")
            cv2.imshow('test', img)
            cv2.waitKey(0)
            cv2.destroyWindow('test')

if __name__ == '__main__':
    test()

效果图:

参考:Windows10下Object Detection API实战记录(1)——windows10下成功安装TensorFlow Object Detection API(亲测以及踩坑记录)

全网最详细win10+anaconda+GPU+Tensorflow Object Detection API训练自己数据+新手教程+训练过程问题解决

Ubuntu18.04下安装TensorFlow Object Detection API

cl: 命令行 error D8021 :无效的数值参数“/Wno-cpp”

第三十二节,使用谷歌Object Detection API进行目标检测、训练新的模型(使用VOC 2012数据集)

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值