InvalidArgumentError(请参见上面的回溯):您必须使用dtype float和shape [360,480,3]

时间:2018-09-13 05:46:38

标签: python tensorflow placeholder

我将使用以下代码进行测试,以在实时网络摄像头上测试基于Tensorflow的E-Net。

但是,在第78行代码中会出现占位符错误。

如果使用以下代码对图像进行前缀处理,则占位符将发生错误。

该实验的视频文件是(480,360)尺寸的彩色图像(360,480,3)和MJPG编解码器的avi文件。

占位符是什么? 我该怎么解决?

请帮助我。

这是错误代码。

True
HERE (1, 360, 480)
WARNING:tensorflow:From predict_video.py:102: Supervisor.__init__ (from tensorflow.python.training.supervisor) is deprecated and will be removed in a future version.
Instructions for updating:
Please switch to tf.train.MonitoredTrainingSession
2018-09-13 14:11:41.510826: I c:\users\user\source\repos\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2018-09-13 14:11:42.140975: I c:\users\user\source\repos\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1356] Found device 0 with properties:
name: GeForce GTX 960M major: 5 minor: 0 memoryClockRate(GHz): 1.176
pciBusID: 0000:01:00.0
totalMemory: 4.00GiB freeMemory: 3.34GiB
2018-09-13 14:11:42.162310: I c:\users\user\source\repos\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1435] Adding visible gpu devices: 0
2018-09-13 14:11:43.001599: I c:\users\user\source\repos\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix:
2018-09-13 14:11:43.013639: I c:\users\user\source\repos\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:929]      0
2018-09-13 14:11:43.020308: I c:\users\user\source\repos\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:942] 0:   N
2018-09-13 14:11:43.029139: I c:\users\user\source\repos\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 3075 MB memory) -> physical GPU (device: 0, name: GeForce GTX 960M, pci bus id: 0000:01:00.0, compute capability: 5.0)
WARNING:tensorflow:Standard services need a 'logdir' passed to the SessionManager
Traceback (most recent call last):
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1322, in _do_call
    return fn(*args)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1307, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1409, in _call_tf_sessionrun
    run_metadata)
**tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [360,480,3]**
         [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[360,480,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
         [[Node: Placeholder/_2837 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_4_Placeholder", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "predict_video.py", line 113, in <module>
    print('~~~~~~~~~~~~~~',sess.run(image_tensor))
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 900, in run
    run_metadata_ptr)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1135, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1316, in _do_run
    run_metadata)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1335, in _do_call
    raise type(e)(node_def, op, message)
**tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [360,480,3]**
         [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[360,480,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
         [[Node: Placeholder/_2837 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_4_Placeholder", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op 'Placeholder', defined at:
  File "predict_video.py", line 78, in <module>
    image_tensor = tf.placeholder(tf.float32, shape=[H,W,3])
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\array_ops.py", line 1808, in placeholder
    return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\gen_array_ops.py", line 5835, in placeholder
    "Placeholder", dtype=dtype, shape=shape, name=name)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\ops.py", line 3392, in create_op
    op_def=op_def)
  File "C:\Users\zmqp1\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\ops.py", line 1718, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

**InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [360,480,3]**
         [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[360,480,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
         [[Node: Placeholder/_2837 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_4_Placeholder", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

这是我的代码。

import tensorflow as tf
import os
import matplotlib.pyplot as plt
from enet import ENet, ENet_arg_scope
from preprocessing import preprocess
from scipy.misc import imsave
import numpy as np
import cv2
import time

slim = tf.contrib.slim

os.environ["CUDA_VISIBLE_DEVICES"]="0"

W = 480
H = 360

batch_size = 1
num_classes = 7

video_dir = './data/'
fname = 'bottom.avi'

checkpoint_dir = "./log/original/"
checkpoint = tf.train.latest_checkpoint(checkpoint_dir)

cap = cv2.VideoCapture(video_dir+fname)
print(cap.isOpened())

num_initial_blocks = 1
skip_connections = False
stage_two_repeat = 2

label_to_colours =  {0: [0,255,0],
                     1: [0,255,255],
                     2: [0,0,255],
                     3: [0,150,150],
                     4: [255,255,0],
                     5: [255,0,0],
                     6: [255,255,255]}

#Create the photo directory
photo_dir = checkpoint_dir + "/test_images"
if not os.path.exists(photo_dir):
    os.mkdir(photo_dir)

def vis_segmentation(image, seg_map):
    """Visualizes input image, segmentation map and overlay view."""
    image_width, image_height = image.size
    colored_label = label_to_color_image(seg_map).astype(np.uint8)
    image_empty = np.zeros((image_height,2*image_width,3),np.uint8)
    image_empty[:image_height,:image_width] = image.copy()
    image_empty[:image_height,image_width:] = colored_label.copy()
    image_empty[:image_height,:image_width] = image.copy()
    image_empty[:image_height,image_width:] = colored_label.copy()

    alpha = 0.35
    beta = 1-alpha
    gamma = 0
    img_add = cv2.addWeighted(np.array(image), alpha, seg_map, beta, gamma)
    return img_add

#Create a function to convert each pixel label to colour.
def grayscale_to_colour(image):
    print('Converting image...')
    image = image.reshape((H, W, 1))
    image = np.repeat(image, 3, axis=-1)
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            label = int(image[i][j][0])
            image[i][j] = np.array(label_to_colours[label])

    return image

def model_run(image):   
    return predictions   
with tf.Graph().as_default() as graph:
    image_tensor = tf.placeholder(tf.float32, shape=[H,W,3])
    #image_tensor = tf.reshape(image_tensor, shape=(H,W,3))
    images = tf.expand_dims(image_tensor, 0)

    #Create the model inference
    with slim.arg_scope(ENet_arg_scope()):
        logits, probabilities = ENet(images,
                                 num_classes=num_classes,
                                 batch_size=batch_size,
                                 is_training=False,
                                 reuse=None,
                                 num_initial_blocks=num_initial_blocks,
                                 stage_two_repeat=stage_two_repeat,
                                 skip_connections=skip_connections)

    variables_to_restore = slim.get_variables_to_restore()
    saver = tf.train.Saver(variables_to_restore)
    def restore_fn(sess):
        return saver.restore(sess, checkpoint)

    predictions = tf.argmax(probabilities, -1)
    predictions = tf.cast(predictions, tf.float32)
    print('HERE', predictions.get_shape())

    sv = tf.train.Supervisor(logdir=None, init_fn=restore_fn)

    with sv.managed_session() as sess:
        now = 0.0
        while(cap.isOpened()):
            ret, frame = cap.read()
            if (ret == False):
                print('~~~~~~~~~~~~~~~~~~did not get any frame~~~~~~~~~~~~~~~~~~')
                break  
            image = frame.copy()             
            image = np.asarray(image, np.float32)/255          
            print('~~~~~~~~~~~~~~',sess.run(image_tensor))
            segmentations = sess.run(predictions, feed_dict={image_tensor:image})

            cv2.imshow('pre',segmentations[0])
            cv2.waitKey(0)

            #T = time.time() - now
            #print(int(1/T))
            #now = time.time()

cap.release()
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:0)

错误是您违反了在TensorFlow中使用占位符的基本原则。

占位符用于填充,不像其他操作那样进行评估。

清除错误代码很容易,因为它会转到代码中的以下行:

    print('~~~~~~~~~~~~~~',sess.run(image_tensor))

这始终是不一致的,因为您可以直接打印image