Tensorflow加载模型实现图像分类识别流程详解

 更新时间:2022年09月21日 10:04:18   作者:技术老匠  
在视觉领域可以分为:1、图像分类 2、语义分割 3、实例分割 4、目标检测(跟踪) 5、关键点检测。该篇主要讲解利用Tensorflow 对图像进行图像分类

前言

深度学习框架在市面上有很多。比如Theano、Caffe、CNTK、MXnet 、Tensorflow等。今天讲解的就是主角Tensorflow。Tensorflow的前身是Google大脑项目的一个分布式机器学习训练框架,它是一个十分基础且集成度很高的系统,它的目标就是为研究超大型规模的视觉项目,后面延申到各个领域。Tensorflow 在2015年正式开源,开源的一个月内就收获到1w多的starts,这足以说明Tensorflow的优越性以及Google的影响力。在Api方面Tensorflow为了满足绝大部分的开发者需求,这也是Google的一贯作风,集成了Java、Go、Python、C++等编程语言。

正文

图像识别是一件很有趣的事,话不多说,咱们先了解下特征提取VGG in Tensorflow。官网地址:VGG in TensorFlow · Davi Frossard

VGG 是牛津大学的 K. Simonyan 和 A. Zisserman 在论文“Very Deep Convolutional Networks for Large-Scale Image Recognition”中提出的卷积神经网络模型。该模型在 ImageNet 中实现了 92.7% 的 top-5 测试准确率,这是一个包含 1000 个类别的超过 1400 万张图像的数据集。 在这篇简短的文章中,我们提供了 VGG16 的实现以及从原始 Caffe 模型转换为 TensorFlow 的权重。这句话是VGGNet官方的介绍,直接从它提供的数字可以看出来,它的识别率是十分高的,是不是很激动,动起手来吧。

开发步骤分4步,如下所示:

a) 依赖加载

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import scipy.io
import scipy.misc
from imagenet_classes import class_names

b)定义卷积、池化等函数

def _conv_layer(input,weight,bias):
    conv = tf.nn.conv2d(input,weight,strides=[1,1,1,1],padding="SAME")
    return tf.nn.bias_add(conv,bias)
def _pool_layer(input):
    return tf.nn.max_pool(input,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
def preprocess(image,mean_pixel):
    '''简单预处理,全部图片减去平均值'''
    return image-mean_pixel
def unprocess(image,mean_pixel):
    return image+mean_pixel

c)图像的读取以及保存

def imread(path):
    return scipy.misc.imread(path)
def imsave(image,path):
    img = np.clip(image,0,255).astype(np.int8)
    scipy.misc.imsave(path,image)

d) 定义网络结构,这里使用的是VGG19

def net(data_path,input_image,sess=None):
    """
    读取VGG模型参数,搭建VGG网络
    :param data_path: VGG模型文件位置
    :param input_image: 输入测试图像
    :return:
    """
    layers = (
        'conv1_1', 'conv1_2', 'pool1',
        'conv2_1', 'conv2_2', 'pool2',
        'conv3_1', 'conv3_2', 'conv3_3','conv3_4', 'pool3',
        'conv4_1', 'conv4_2', 'conv4_3','conv4_4', 'pool4',
        'conv5_1', 'conv5_2', 'conv5_3','conv5_4', 'pool5',
          'fc1'  ,   'fc2'  ,   'fc3'  ,
        'softmax'
    )
    data = scipy.io.loadmat(data_path)
    mean = data["normalization"][0][0][0][0][0]
    input_image = np.array([preprocess(input_image, mean)]).astype(np.float32)#去除平均值
    net = {}
    current = input_image
    net["src_image"] = tf.constant(current)  # 存储数据
    count = 0 #计数存储
    for i in range(43):
        if str(data['layers'][0][i][0][0][0][0])[:4] == ("relu"):
            continue
        if str(data['layers'][0][i][0][0][0][0])[:4] == ("pool"):
            current = _pool_layer(current)
        elif str(data['layers'][0][i][0][0][0][0]) == ("softmax"):
            current = tf.nn.softmax(current)
        elif i == (37):
            shape = int(np.prod(current.get_shape()[1:]))
            current = tf.reshape(current, [-1, shape])
            kernels, bias = data['layers'][0][i][0][0][0][0]
            kernels = np.reshape(kernels,[-1,4096])
            bias = bias.reshape(-1)
            current = tf.nn.relu(tf.add(tf.matmul(current,kernels),bias))
        elif i == (39):
            kernels, bias = data['layers'][0][i][0][0][0][0]
            kernels = np.reshape(kernels,[4096,4096])
            bias = bias.reshape(-1)
            current = tf.nn.relu(tf.add(tf.matmul(current,kernels),bias))
        elif i == 41:
            kernels, bias = data['layers'][0][i][0][0][0][0]
            kernels = np.reshape(kernels, [4096, 1000])
            bias = bias.reshape(-1)
            current = tf.add(tf.matmul(current, kernels), bias)
        else:
            kernels,bias = data['layers'][0][i][0][0][0][0]
            #注意VGG存储方式为[,]
            #kernels = np.transpose(kernels,[1,0,2,3])
            bias = bias.reshape(-1)#降低维度
            current = tf.nn.relu(_conv_layer(current,kernels,bias))
        net[layers[count]] = current #存储数据
        count += 1
    return net, mean

e)加载模型进行识别

if __name__ == '__main__':
    VGG_PATH = "./one/imagenet-vgg-verydeep-19.mat"
    IMG_PATH = './one/3.jpg'
    input_image =imread(IMG_PATH)
    shape = (1, input_image.shape[0], input_image.shape[1], input_image.shape[2])
    with tf.Session() as sess:
        image = tf.placeholder('float', shape=shape)
        nets, mean_pixel, all_layers= net(VGG_PATH, image)
        input_image_pre=np.array([preprocess(input_image,mean_pixel)])
        layers = all_layers
        for i , layer in enumerate(layers):
            print("[%d/%d] %s" % (i+1,len(layers),layers))
            features = nets[layer].eval(feed_dict={image:input_image_pre})
            print("Type of 'feature' is ",type(features))
            print("Shape of 'features' is  %s" % (features.shape,))
            if 1:
                plt.figure(i+1,figsize=(10,5))
                plt.matshow(features[0,:,:,0],cmap=plt.cm.gray,fignum=i+1)
                plt.title(""+layer)
                plt.colorbar()
                plt.show()

VGG19网络介绍

VGG19 的宏观架构如图所示。我们在 TensorFlow 中的文件 vgg19.py 中对其进行编码。请注意,我们包含一个预处理层,它采用像素值在 0-255 范围内的 RGB 图像并减去平均图像值(在整个 ImageNet 训练集上计算)。

总结

Tensorflow是一款十分不错的深度学习框架,它在工业上得到的十分的认可并进行了实践。因此,如果你还在犹豫生产落地使用框架,不要犹豫啦。VGGNet家族是一个十分优秀的网络结构,它在处理特征提取过程中,也是得到了很多公司和研究学者的认可,比较著名的有VGG16、VGG19等。

到此这篇关于Tensorflow加载模型实现图像分类识别流程详解的文章就介绍到这了,更多相关Tensorflow图像分类识别内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python中的面向对象编程详解(上)

    Python中的面向对象编程详解(上)

    这篇文章主要介绍了Python中的面向对象编程详解(上),本文讲解了创建类、实例化类、类属性、特殊方法内建属性、静态变量属性、实例变量属性、方法属性、静态方法、类方法等内容,需要的朋友可以参考下
    2015-04-04
  • python中in和is的区别点总结

    python中in和is的区别点总结

    在本篇文章里小编给大家整理的是一篇关于python中in和is的区别点总结,有兴趣的朋友可以跟着学习下。
    2021-05-05
  • numpy数据类型dtype转换实现

    numpy数据类型dtype转换实现

    这篇文章主要介绍了numpy数据类型dtype转换实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • python中字符串前面加r的作用

    python中字符串前面加r的作用

    这篇文章主要介绍了python中字符串前面加r的作用,实例分析了Python通过字符串前面加r实现禁止字符串转义的功能,需要的朋友可以参考下
    2015-06-06
  • 基于PyQT5制作一个桌面摸鱼工具

    基于PyQT5制作一个桌面摸鱼工具

    这篇文章主要介绍了如何利用PyQT5制作一个桌面摸鱼工具,利用摸鱼,打开小说,可实行完美摸鱼,实时保存进度,快来跟随小编一起动手试一试吧
    2022-02-02
  • Python协程方式的实现及意义笔记分享

    Python协程方式的实现及意义笔记分享

    协程也被称为微线程,是一种用户态的上下文切换技术,简而言之,就是通过一个线程实现代码互相切换执行,本文主要给大家介绍实现协程的几种方法
    2021-09-09
  • python基础之并发编程(二)

    python基础之并发编程(二)

    这篇文章主要介绍了详解python的并发编程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-10-10
  • Python实现GUI图片浏览的小程序

    Python实现GUI图片浏览的小程序

    这篇文章主要介绍了Python实现GUI图片浏览程序,程序的实现需要pillow库,pillow是 Python 的第三方图像处理库,需要安装才能实用,文中通过代码示例给大家介绍的非常详细,需要的朋友可以参考下
    2023-12-12
  • 跟老齐学Python之用while来循环

    跟老齐学Python之用while来循环

    while,翻译成中文是“当...的时候”,这个单词在英语中,常常用来做为时间状语,while ... someone do somthing,这种类型的说法是有的。
    2014-10-10
  • Python最常用的20 个包总结

    Python最常用的20 个包总结

    这篇文章主要介绍了Python最常用的20 个包总结,在平时使用Python的过程中,需要用到很多有用的包,今天就来盘点一下常用的包,需要的朋友可以参考下
    2023-04-04

最新评论