Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TensorFlow:如何对多张图像进行图像分类_Python_Numpy_Tensorflow - Fatal编程技术网

Python TensorFlow:如何对多张图像进行图像分类

Python TensorFlow:如何对多张图像进行图像分类,python,numpy,tensorflow,Python,Numpy,Tensorflow,希望有人能帮忙做一个TensorFlow查询。我相信这并不难。我只是有点缺乏关于TensorFlow和NumPy的知识 在没有任何TensorFlow经验的情况下,我已经从实现了用于图像分类的Python代码。这很有效。一旦经过训练,它就能分辨猫和狗的区别 这是目前硬连线为一个单一的形象。我希望能够对多个图像(即文件夹的内容)进行分类,并高效地进行分类。到目前为止,我为实现这一点所做的努力是简单地在所有内容周围添加一个循环,以便它为每个图像运行所有代码。然而,定时操作表明,每个连续图像的分类比前

希望有人能帮忙做一个TensorFlow查询。我相信这并不难。我只是有点缺乏关于TensorFlow和NumPy的知识

在没有任何TensorFlow经验的情况下,我已经从实现了用于图像分类的Python代码。这很有效。一旦经过训练,它就能分辨猫和狗的区别

这是目前硬连线为一个单一的形象。我希望能够对多个图像(即文件夹的内容)进行分类,并高效地进行分类。到目前为止,我为实现这一点所做的努力是简单地在所有内容周围添加一个循环,以便它为每个图像运行所有代码。然而,定时操作表明,每个连续图像的分类比前一个图像花费更长的时间。因此,存在某种增量开销。某些操作在每个循环中花费的时间更多。我不能马上看出这是什么

有两种方法可以改进这一点。要么:

(1) 保持循环基本不变,防止这种减速,或

(2) (如果可能,最好是IMHO)将图像列表传递给TensorFlow进行分类,并返回结果列表。这似乎更有效率

代码如下:

import tensorflow as tf
import numpy as np
import os,glob,cv2
import sys,argparse
import time

try:

  inputdir = [redacted - insert input dir here]

  for f in os.listdir(inputdir):

    start_time = time.time()

    filename = os.path.join(inputdir,f)

    image_size=128
    num_channels=3
    images = []
    image = cv2.imread(filename) # read image using OpenCV

    # Resize image to desired size and preprocess exactly as done during training...
    image = cv2.resize(image, (image_size, image_size),0,0, cv2.INTER_LINEAR)
    images.append(image)
    images = np.array(images, dtype=np.uint8)
    images = images.astype('float32')
    images = np.multiply(images, 1.0/255.0)

    # The input to the network is of shape [None image_size image_size num_channels]. Hence we reshape.
    x_batch = images.reshape(1, image_size,image_size,num_channels)

    sess = tf.Session() # restore the saved model
    saver = tf.train.import_meta_graph('dogs-cats-model.meta') # Step 1: Recreate the network graph. At this step only graph is created
    saver.restore(sess, tf.train.latest_checkpoint('./')) # Step 2: Load the weights saved using the restore method
    graph = tf.get_default_graph() # access the default graph which we have restored

    # Now get hold of the op that we can be processed to get the output.
    # In the original network y_pred is the tensor that is the prediction of the network
    y_pred = graph.get_tensor_by_name("y_pred:0")

    ## Feed the images to the input placeholders...
    x= graph.get_tensor_by_name("x:0") 
    y_true = graph.get_tensor_by_name("y_true:0") 
    y_test_images = np.zeros((1, 2)) 

    # Create the feed_dict that is required to be fed to calculate y_pred...
    feed_dict_testing = {x: x_batch, y_true: y_test_images}
    result=sess.run(y_pred, feed_dict=feed_dict_testing)
    # Note: result is a numpy.ndarray
    print(f + '\t' + str(result) + ' ' + '%.2f' % (time.time()-start_time) + ' seconds')

  # next image

except:
  import traceback
  tb = traceback.format_exc()
  print(tb)

finally:
  input() # keep window open until key is pressed
我试图做的是修改上面的是创建一个文件名列表使用

images.append(image)
…然后将其余代码从循环中删除。然而,这不起作用。它导致了以下错误:

ValueError:无法将大小为294912的数组重塑为形状 (1128128,3)

在这一行:

x_batch = images.reshape(1, image_size,image_size,num_channels)
显然,这种重塑方法在图像列表上不起作用(至少在实现时是这样)

因此,我的问题是:

  • 当图像被迭代时,什么会导致图像分类时间的稳步增加

  • 我是否可以一次性对多个图像执行分类,而不是在循环中逐个执行分类

  • 提前感谢。

    您的问题:

    1 a)速度如此之慢的主要原因是:您正在为每个图像重新创建图形

    1 b)增量开销来自每次创建一个新会话而不破坏旧会话。
    with
    语法有助于实现这一点。e、 g:

    with tf.Session(graph=tf.Graph()) as session:
      # do something with the session
    
    但在解决了一个问题后,这将不是一个值得注意的问题)

    当思考这个问题时,人们可能会意识到代码的哪些部分依赖于图像,哪些部分不依赖图像。每个映像不同的TensorFlow相关部分是对
    会话的调用。运行
    ,输入映像。其他一切都可以移出循环

    2) 您还可以一次性对多个图像进行分类。
    x_批次的第一个维度是批次大小。您正在指定一个。但是,如果要处理大量图像,可能会耗尽您的内存资源。

    非常感谢de1:-)理解这两点,非常感谢您的帮助。(我想知道其中一个.reformate函数参数是否是图像的数量,但在文档中找不到任何可以说明它是的。)