InvalidArgumentError может относиться к графу вычислений в video2tfrecord - PullRequest
0 голосов
/ 03 октября 2018

Я пытаюсь использовать только 2 видео для преобразования, поэтому нет проблем с массивом numpy, но эта проблема, надеюсь, вы поможете мне решить его. Ставка желает вам и вашему видео2tfrecord

вот мой код

import os
import unittest
import tensorflow as tf
import numpy as np
from video2tfrecord import convert_videos_to_tfrecord
from tensorflow.python.platform import gfile

height = 480
width = 480
num_depth = 3
in_path = "./example/input"
out_path = "./example/output"
n_videos_per_record = 1


class Testvideo2tfrecord(unittest.TestCase):
  def test_example1(self):
    n_frames = 5
    convert_videos_to_tfrecord(source_path=in_path, destination_path=out_path,
                               n_videos_in_record=n_videos_per_record,
                               n_frames_per_video=n_frames,
                               dense_optical_flow=True,
                               file_suffix="*.mp4")

    filenames = gfile.Glob(os.path.join(out_path, "*.tfrecords"))
    n_files = len(filenames)

    self.assertTrue(filenames)
    self.assertEqual(n_files * n_videos_per_record,
                     get_number_of_records(filenames, n_frames))

  " travis ressource exhaust, passes locally for 3.6 and 3.4"
  # def test_example2(self):
  #   n_frames = 'all'
  #   convert_videos_to_tfrecord(source_path=in_path, destination_path=out_path,
  #                              n_videos_in_record=n_videos_per_record,
  #                              n_frames_per_video=n_frames,
  #                              n_channels=num_depth, dense_optical_flow=False,
  #                              file_suffix="*.mp4")
  #
  #   filenames = gfile.Glob(os.path.join(out_path, "*.tfrecords"))
  #   n_files = len(filenames)
  #
  #   self.assertTrue(filenames)
  #   self.assertEqual(n_files * n_videos_per_record,
  #                    get_number_of_records(filenames, n_frames))


def read_and_decode(filename_queue, n_frames):
  """Creates one image sequence"""

  reader = tf.TFRecordReader()
  _, serialized_example = reader.read(filename_queue)

  image_seq = []

  if n_frames == 'all':
    n_frames = 354  # travis kills due to too large tfrecord

  for image_count in range(n_frames):
    path = 'blob' + '/' + str(image_count)

    feature_dict = {path: tf.FixedLenFeature([], tf.string),
      'height': tf.FixedLenFeature([], tf.int64),
      'width': tf.FixedLenFeature([], tf.int64),
      'depth': tf.FixedLenFeature([], tf.int64)}

    features = tf.parse_single_example(serialized_example,
                                       features=feature_dict)

    image_buffer = tf.reshape(features[path], shape=[])
    image = tf.decode_raw(image_buffer, tf.uint8)
    image = tf.reshape(image, tf.stack([height, width, num_depth]))
    image = tf.reshape(image, [1, height, width, num_depth])
    image_seq.append(image)

  image_seq = tf.concat(image_seq, 0)

  return image_seq


def get_number_of_records(filenames, n_frames):
  """
  this function determines the number of videos available in all tfrecord files. It also checks on the correct shape of the single examples in the tfrecord
  files.
  :param filenames: a list, each entry containign a (relative) path to one tfrecord file
  :return: the number of overall videos provided in the filenames list
  """

  num_examples = 0

  if n_frames == 'all':
    n_frames_in_test_video = 354
  else:
    n_frames_in_test_video = n_frames

  # create new session to determine batch_size for validation/test data
  with tf.Session() as sess_valid:
    filename_queue_val = tf.train.string_input_producer(filenames, num_epochs=1)
    image_seq_tensor_val = read_and_decode(filename_queue_val, n_frames)

    init_op = tf.group(tf.global_variables_initializer(),
                       tf.local_variables_initializer())
    sess_valid.run(init_op)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    try:
      while True:
        video = sess_valid.run([image_seq_tensor_val])
        assert np.shape(video) == (1, n_frames_in_test_video, height, width,
                                   num_depth), "shape in the data differs from the expected shape"
        num_examples += 1
    except tf.errors.OutOfRangeError as e:
      coord.request_stop(e)
    finally:
      coord.request_stop()
      coord.join(threads)

  return num_examples


if __name__ == '__main__':
  unittest.main()

тогда вот информация об ошибке

pi @ Hans: ~ / Desktop / testtrans / video2tfrecord $ python3 test.py Всего найдено видео: 2 1 из 1 видео в пакетной обработке: ./example/input/100998.mp4 Партия 1/2 завершена Запись ./example/output/batch_1_of_2.tfrecords 1 из 1 видео в партии обработано: ./example/input/100999.mp4 Пакет 2/2 завершено Запись ./example / output / batch_2_of_2.tfrecords 2018-10-03 23: 59: 48.840133: I tenorflow / core / platform / cpu_feature_guard.cc: 141] Ваш ЦП поддерживает инструкции о том, что этот двоичный файл TensorFlow не скомпилирован для использования: AVX2 FMA ПРЕДУПРЕЖДЕНИЕ: tenorflow: Из /home/pi/.local/lib/python3.6/site-packages/tensorflow/python/training/input.py:187: QueueRunner. init (из тензорного потока.python.training.queue_runner_impl) устарела и будет удален в будущей версии.Инструкции по обновлению: Для построения входных конвейеров используйте модуль tf.data.ПРЕДУПРЕЖДЕНИЕ: tenorflow: From /home/pi/.local/lib/python3.6/site-packages/tensorflow/python/training/input.py:187: add_queue_runner (from tensorflow.python.training.queue_runner_impl) устарела и будетбыть удаленным в будущей версии.Инструкции по обновлению: Для построения входных конвейеров используйте модуль tf.data.ПРЕДУПРЕЖДЕНИЕ: tenorflow: из test.py:106: start_queue_runners (из тензорного потока.python.training.queue_runner_impl) устарела и будет удалена в следующей версии.Инструкции по обновлению: Для построения входных конвейеров используйте модуль tf.data.E ============================================================================ ОШИБКА: test_example1 ( main .Testvideo2tfrecord) ---------------------------------------------------------------------- Трассировка (последний вызов был последним): файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", строка 1292, в _do_call returnfn (* args) Файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", строка 1277, в параметрах _run_fn, feed_dict, fetch_list, target_list, run_metadata) Файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", строка 1367, в _call_tf_sessionrun run_metadata) tenorsflow.python.framework.errors_impl.InvalidArgumentError: Inputизменить - это тензор с 3686400 значениями, но запрошенная форма имеет 691200 [[{{node Reshape_5}} = Reshape [T = DT_UINT8, Tshape = DT_INT32, _device = "/ job: localhost / replica: 0 / task: 0 /устройство: ЦП: 0 "] (DecodeRaw_1, Reshape_2 / shape)]]

Во время обработкивыше исключения, произошло другое исключение:

Трассировка (последний последний вызов): файл "test.py", строка 30, в test_example1 get_number_of_records (filenames, n_frames)) файл "test.py", строка 109,в файле get_number_of_records video = sess_valid.run ([image_seq_tensor_val]) "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", строка 887, в прогоне run_metadata_ptr)Файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", строка 1110, в _run feed_dict_tensor, options, run_metadata) Файл "/ home / pi /.local / lib / python3.6 / site-packages / tenorflow / python / client / session.py ", строка 1286, в _do_run run_metadata) Файл" /home/pi/.local/lib/python3.6/site-packages/tenorflow / python / client / session.py ", строка 1308, в _do_call повышают тип (e) (node_def, op, message) tenorflow.python.framework.errors_impl.InvalidArgumentError: Входными данными для изменения формы является тензор с 3686400 значениями, нозапрошенная форма имеет 691200 [[{{node Reshape_5}} = Reshape [T =DT_UINT8, Tshape = DT_INT32,_device = "/ job: localhost / replica: 0 / task: 0 / device: CPU: 0"] (DecodeRaw_1, Reshape_2 / shape)]]

Вызывается операцией 'Reshape_5', определенной в: File "test.py ", строка 123, в файле unittest.main ()" /usr/lib/python3.6/unittest/main.py ", строка 95, в файле init self.runTests ()"/usr/lib/python3.6/unittest/main.py ", строка 256, в runTests self.result = testRunner.run (self.test) Файл" /usr/lib/python3.6/unittest/runner.py ", строка 176, в рабочем тесте (результат) Файл "/usr/lib/python3.6/unittest/suite.py", строка 84, в вызов , возврат self.run (* args, ** kwds) Файл "/usr/lib/python3.6/unittest/suite.py", строка 122, в ходе выполнения теста (результат) Файл "/usr/lib/python3.6/unittest/suite.py", строка 84, в call return self.run (* args, ** kwds) Файл "/usr/lib/python3.6/unittest/suite.py", строка 122, в файле теста выполнения (результата) "/ usr/lib/python3.6/unittest/case.py ", строка 653, в вызов , возврат файла self.run (* args, ** kwds)" /usr/lib/python3.6/unittest/case.py ", строка 605, в рабочем файле testMethod ()" test.py ", строка 30, в test_example1 get_number_of_records (имена файлов, n_frames)) Файл" test.py ", строка 100, в get_number_of_records image_seq_tensor_val = read_and_decode (имя_файла_queue_val, n_frames) Файл" test.py_and ", строка 74 в коде чтения= tf.reshape (изображение, [1, высота, ширина, num_depth]) Файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", строка 6296в форме "Reshape", тензор = тензор, форма = форма, имя = имя) Файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py",строка 787, в _apply_op_helper op_def = op_def) Файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", строка 488, в функции new_func вернуть функцию (* аргументы, ** kwargs) Файл "/home/pi/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", строка 3272, в файле create_op op_def = op_def) "/ home /pi / .local / lib / python3.6 / site-packages / tenorflow / python / framework / ops.py ", строка 1768, в init self._traceback = tf_stack.[T = DT_UINT8, Tshape = DT_INT32, _device = "/ job: localhost / реплика: 0 / task: 0 / device: CPU: 0"] (DecodeRaw_1, Reshape_2 / shape)]]

---------------------------------------------------------------------- Выполнен 1 тест за 11.783 с

СБОЙ (ошибки = 1)

их вот ответ на вопросот github https://github.com/ferreirafabio/video2tfrecord/issues/5

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...