TensorFlow中如何使用训练好的模型识别猫狗图片

发布时间:2021-08-12 11:34:15 作者:小新
来源:亿速云 阅读:221

这篇文章给大家分享的是有关TensorFlow中如何使用训练好的模型识别猫狗图片的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

本文逻辑:

  1. 我从网上下载了十几张猫和狗的图片,用于检验我们训练好的模型。

  2. 处理我们下载的图片

  3. 加载模型

  4. 将图片输入模型进行检验

代码如下:

#coding=utf-8 
import tensorflow as tf 
from PIL import Image 
import matplotlib.pyplot as plt
import input_data 
import numpy as np
import model
import os 
#从指定目录中选取一张图片 
def get_one_image(train): 
  files = os.listdir(train)
  n = len(files)
  ind = np.random.randint(0,n)
  img_dir = os.path.join(train,files[ind]) 
  image = Image.open(img_dir) 
  plt.imshow(image)
  plt.show()
  image = image.resize([208, 208]) 
  image = np.array(image)
  return image 
def evaluate_one_image(): 
 #存放的是我从百度下载的猫狗图片路径
  train = '/Users/yangyibo/GitWork/pythonLean/AI/猫狗识别/testImg/' 
  image_array = get_one_image(train) 
  with tf.Graph().as_default(): 
    BATCH_SIZE = 1 # 因为只读取一副图片 所以batch 设置为1
    N_CLASSES = 2 # 2个输出神经元,[1,0] 或者 [0,1]猫和狗的概率
    # 转化图片格式
    image = tf.cast(image_array, tf.float32) 
    # 图片标准化
    image = tf.image.per_image_standardization(image)
    # 图片原来是三维的 [208, 208, 3] 重新定义图片形状 改为一个4D 四维的 tensor
    image = tf.reshape(image, [1, 208, 208, 3]) 
    logit = model.inference(image, BATCH_SIZE, N_CLASSES) 
    # 因为 inference 的返回没有用激活函数,所以在这里对结果用softmax 激活
    logit = tf.nn.softmax(logit) 
    # 用最原始的输入数据的方式向模型输入数据 placeholder
    x = tf.placeholder(tf.float32, shape=[208, 208, 3]) 
    # 我门存放模型的路径
    logs_train_dir = '/Users/yangyibo/GitWork/pythonLean/AI/猫狗识别/saveNet/'  
    # 定义saver 
    saver = tf.train.Saver() 
    with tf.Session() as sess: 
      print("从指定的路径中加载模型。。。。")
      # 将模型加载到sess 中 
      ckpt = tf.train.get_checkpoint_state(logs_train_dir) 
      if ckpt and ckpt.model_checkpoint_path: 
        global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] 
        saver.restore(sess, ckpt.model_checkpoint_path) 
        print('模型加载成功, 训练的步数为 %s' % global_step) 
      else: 
        print('模型加载失败,,,文件没有找到') 
      # 将图片输入到模型计算
      prediction = sess.run(logit, feed_dict={x: image_array})
      # 获取输出结果中最大概率的索引
      max_index = np.argmax(prediction) 
      if max_index==0: 
        print('猫的概率 %.6f' %prediction[:, 0]) 
      else: 
        print('狗的概率 %.6f' %prediction[:, 1]) 
# 测试
evaluate_one_image()

/Users/yangyibo/GitWork/pythonLean/AI/猫狗识别/testImg/ 存放的是我从百度下载的猫狗图片

TensorFlow中如何使用训练好的模型识别猫狗图片

执行结果:

因为从testimg 中选取图片是随机的,所以每次执行的结果不同

从指定的路径中加载模型。。。。
模型加载成功, 训练的步数为 11999
狗的概率 0.964047
[Finished in 6.8s]

感谢各位的阅读!关于“TensorFlow中如何使用训练好的模型识别猫狗图片”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. Java泛型的重要目的:别让猫别站在狗队里
  2. tensorflow中Dataset图片的批量读取及维度

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

tensorflow

上一篇:DIV标签的用法

下一篇:Flutter 中怎么实现一个裁剪类组件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》