Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data_path1 = 'C:/tensorflow1/models/research/object_detection/images/csv1.tfrecords' # address to save the hdf5 file
- with tf.Session() as sess:
- feature = {'image/encoded': tf.FixedLenFeature([], tf.string),
- 'image/object/class/label': tf.FixedLenFeature([], tf.int64)}
- # Create a list of filenames and pass it to a queue
- filename_queue = tf.train.string_input_producer([data_path1], num_epochs=1)
- # Define a reader and read the next record
- reader = tf.TFRecordReader()
- _, serialized_example = reader.read(filename_queue)
- # Decode the record read by the reader
- features = tf.parse_single_example(serialized_example, features=feature)
- # Convert the image data from string back to the numbers
- image = tf.decode_raw(features['image/encoded'], tf.int64)
- # Cast label data into int32
- label = tf.cast(features['image/object/class/label'], tf.int32)
- # Reshape image data into the original shape
- image = tf.reshape(image, [150, 150, 1])
- images, labels = tf.train.shuffle_batch([image, label], batch_size=10, capacity=30, num_threads=1, min_after_dequeue=10)
- with tf.Session() as sess:
- # Initialize all global and local variables
- init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
- # sess = tf.Session()
- sess.run(init_op)
- # Create a coordinator and run all QueueRunner objects
- coord = tf.train.Coordinator()
- threads = tf.train.start_queue_runners(coord=coord)
- for batch_index in range(5):
- img, lbl = sess.run([images, labels])
- img = img.astype(np.uint8)
- for j in range(6):
- plt.subplot(2, 3, j+1)
- plt.imshow(img[j, ...])
- plt.show()
- # Stop the threads
- coord.request_stop()
- # Wait for threads to stop
- coord.join(threads)
- sess.close()
- from __future__ import division
- from __future__ import print_function
- from __future__ import absolute_import
- import os
- import io
- import pandas as pd
- import tensorflow as tf
- from PIL import Image
- from object_detection.utils import dataset_util
- from collections import namedtuple, OrderedDict
- flags = tf.app.flags
- flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
- flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
- FLAGS = flags.FLAGS
- # TO-DO replace this with label map
- def class_text_to_int(row_label):
- if row_label == 'car':
- return 1
- else:
- return 0
- def split(df, group):
- data = namedtuple('data', ['filename', 'object'])
- gb = df.groupby(group)
- return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
- def create_tf_example(group, path):
- with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)+'.jpg'), 'rb') as fid:
- print(fid)
- encoded_jpg = fid.read()
- encoded_jpg_io = io.BytesIO(encoded_jpg)
- image = Image.open(encoded_jpg_io)
- width, height = image.size
- filename = group.filename.encode('utf8')
- image_format = b'jpg'
- xmins = []
- xmaxs = []
- ymins = []
- ymaxs = []
- classes_text = []
- classes = []
- for index, row in group.object.iterrows():
- xmins.append(row['xmin'] / width)
- xmaxs.append(row['xmax'] / width)
- ymins.append(row['ymin'] / height)
- ymaxs.append(row['ymax'] / height)
- classes_text.append(row['class'].encode('utf8'))
- classes.append(class_text_to_int(row['class']))
- tf_example = tf.train.Example(features=tf.train.Features(feature={
- 'image/height': dataset_util.int64_feature(height),
- 'image/width': dataset_util.int64_feature(width),
- 'image/filename': dataset_util.bytes_feature(filename),
- 'image/source_id': dataset_util.bytes_feature(filename),
- 'image/encoded': dataset_util.bytes_feature(encoded_jpg),
- 'image/format': dataset_util.bytes_feature(image_format),
- 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
- 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
- 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
- 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
- 'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
- 'image/object/class/label': dataset_util.int64_list_feature(classes),
- }))
- return tf_example
- def main(_):
- writer = tf.python_io.TFRecordWriter('csv1.tfrecords')
- path = os.path.join(os.getcwd(), 'thermal')
- examples = pd.read_csv('thermal_labels.csv')
- grouped = split(examples, 'filename')
- for group in grouped:
- tf_example = create_tf_example(group, path)
- writer.write(tf_example.SerializeToString())
- writer.close()
- output_path = os.path.join(os.getcwd(), 'csv1.tfrecords')
- print('Successfully created the TFRecords: {}'.format(output_path))
- if __name__ == '__main__':
- tf.app.run()
- INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.InvalidArgumentError'>, Input to DecodeRaw has length 224949 that is not a multiple of 8, the size of int64
- [[Node: DecodeRaw = DecodeRaw[little_endian=true, out_type=DT_INT64, _device="/job:localhost/replica:0/task:0/device:CPU:0"](ParseSingleExample/ParseSingleExample)]]
- ---------------------------------------------------------------------------
- OutOfRangeError Traceback (most recent call last)
- c:anaconda3envstf18libsite-packagestensorflowpythonclientsession.py in _do_call(self, fn, *args)
- 1321 try:
- -> 1322 return fn(*args)
- 1323 except errors.OpError as e:
- c:anaconda3envstf18libsite-packagestensorflowpythonclientsession.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
- 1306 return self._call_tf_sessionrun(
- -> 1307 options, feed_dict, fetch_list, target_list, run_metadata)
- 1308
- c:anaconda3envstf18libsite-packagestensorflowpythonclientsession.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
- 1408 self._session, options, feed_dict, fetch_list, target_list,
- -> 1409 run_metadata)
- 1410 else:
- OutOfRangeError: RandomShuffleQueue '_37_shuffle_batch_2/random_shuffle_queue' is closed and has insufficient elements (requested 10, current size 0)
- [[Node: shuffle_batch_2 = QueueDequeueManyV2[component_types=[DT_INT64, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](shuffle_batch_2/random_shuffle_queue, shuffle_batch_2/n)]]
- During handling of the above exception, another exception occurred:
- OutOfRangeError Traceback (most recent call last)
- <ipython-input-16-b8d05859b312> in <module>()
- 8 threads = tf.train.start_queue_runners(coord=coord)
- 9 for batch_index in range(5):
- ---> 10 img, lbl = sess.run([images, labels])
- 11 img = img.astype(np.uint8)
- 12 for j in range(6):
- c:anaconda3envstf18libsite-packagestensorflowpythonclientsession.py in run(self, fetches, feed_dict, options, run_metadata)
- 898 try:
- 899 result = self._run(None, fetches, feed_dict, options_ptr,
- --> 900 run_metadata_ptr)
- 901 if run_metadata:
- 902 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
- c:anaconda3envstf18libsite-packagestensorflowpythonclientsession.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
- 1133 if final_fetches or final_targets or (handle and feed_dict_tensor):
- 1134 results = self._do_run(handle, final_targets, final_fetches,
- -> 1135 feed_dict_tensor, options, run_metadata)
- 1136 else:
- 1137 results = []
- c:anaconda3envstf18libsite-packagestensorflowpythonclientsession.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
- 1314 if handle is None:
- 1315 return self._do_call(_run_fn, feeds, fetches, targets, options,
- -> 1316 run_metadata)
- 1317 else:
- 1318 return self._do_call(_prun_fn, handle, feeds, fetches)
- c:anaconda3envstf18libsite-packagestensorflowpythonclientsession.py in _do_call(self, fn, *args)
- 1333 except KeyError:
- 1334 pass
- -> 1335 raise type(e)(node_def, op, message)
- 1336
- 1337 def _extend_graph(self):
- OutOfRangeError: RandomShuffleQueue '_37_shuffle_batch_2/random_shuffle_queue' is closed and has insufficient elements (requested 10, current size 0)
- [[Node: shuffle_batch_2 = QueueDequeueManyV2[component_types=[DT_INT64, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](shuffle_batch_2/random_shuffle_queue, shuffle_batch_2/n)]]
- Caused by op 'shuffle_batch_2', defined at:
- File "c:anaconda3envstf18librunpy.py", line 193, in _run_module_as_main
- "__main__", mod_spec)
- File "c:anaconda3envstf18librunpy.py", line 85, in _run_code
- exec(code, run_globals)
- File "c:anaconda3envstf18libsite-packagesipykernel_launcher.py", line 16, in <module>
- app.launch_new_instance()
- File "c:anaconda3envstf18libsite-packagestraitletsconfigapplication.py", line 658, in launch_instance
- app.start()
- File "c:anaconda3envstf18libsite-packagesipykernelkernelapp.py", line 486, in start
- self.io_loop.start()
- File "c:anaconda3envstf18libsite-packagestornadoplatformasyncio.py", line 127, in start
- self.asyncio_loop.run_forever()
- File "c:anaconda3envstf18libasynciobase_events.py", line 422, in run_forever
- self._run_once()
- File "c:anaconda3envstf18libasynciobase_events.py", line 1432, in _run_once
- handle._run()
- File "c:anaconda3envstf18libasyncioevents.py", line 145, in _run
- self._callback(*self._args)
- File "c:anaconda3envstf18libsite-packagestornadoplatformasyncio.py", line 117, in _handle_events
- handler_func(fileobj, events)
- File "c:anaconda3envstf18libsite-packagestornadostack_context.py", line 276, in null_wrapper
- return fn(*args, **kwargs)
- File "c:anaconda3envstf18libsite-packageszmqeventloopzmqstream.py", line 450, in _handle_events
- self._handle_recv()
- File "c:anaconda3envstf18libsite-packageszmqeventloopzmqstream.py", line 480, in _handle_recv
- self._run_callback(callback, msg)
- File "c:anaconda3envstf18libsite-packageszmqeventloopzmqstream.py", line 432, in _run_callback
- callback(*args, **kwargs)
- File "c:anaconda3envstf18libsite-packagestornadostack_context.py", line 276, in null_wrapper
- return fn(*args, **kwargs)
- File "c:anaconda3envstf18libsite-packagesipykernelkernelbase.py", line 283, in dispatcher
- return self.dispatch_shell(stream, msg)
- File "c:anaconda3envstf18libsite-packagesipykernelkernelbase.py", line 233, in dispatch_shell
- handler(stream, idents, msg)
- File "c:anaconda3envstf18libsite-packagesipykernelkernelbase.py", line 399, in execute_request
- user_expressions, allow_stdin)
- File "c:anaconda3envstf18libsite-packagesipykernelipkernel.py", line 208, in do_execute
- res = shell.run_cell(code, store_history=store_history, silent=silent)
- File "c:anaconda3envstf18libsite-packagesipykernelzmqshell.py", line 537, in run_cell
- return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
- File "c:anaconda3envstf18libsite-packagesIPythoncoreinteractiveshell.py", line 2662, in run_cell
- raw_cell, store_history, silent, shell_futures)
- File "c:anaconda3envstf18libsite-packagesIPythoncoreinteractiveshell.py", line 2785, in _run_cell
- interactivity=interactivity, compiler=compiler, result=result)
- File "c:anaconda3envstf18libsite-packagesIPythoncoreinteractiveshell.py", line 2903, in run_ast_nodes
- if self.run_code(code, result):
- File "c:anaconda3envstf18libsite-packagesIPythoncoreinteractiveshell.py", line 2963, in run_code
- exec(code_obj, self.user_global_ns, self.user_ns)
- File "<ipython-input-8-bd671b499233>", line 23, in <module>
- images, labels = tf.train.shuffle_batch([image, label], batch_size=10, capacity=30, num_threads=1, min_after_dequeue=10)
- File "c:anaconda3envstf18libsite-packagestensorflowpythontraininginput.py", line 1300, in shuffle_batch
- name=name)
- File "c:anaconda3envstf18libsite-packagestensorflowpythontraininginput.py", line 846, in _shuffle_batch
- dequeued = queue.dequeue_many(batch_size, name=name)
- File "c:anaconda3envstf18libsite-packagestensorflowpythonopsdata_flow_ops.py", line 483, in dequeue_many
- self._queue_ref, n=n, component_types=self._dtypes, name=name)
- File "c:anaconda3envstf18libsite-packagestensorflowpythonopsgen_data_flow_ops.py", line 3799, in queue_dequeue_many_v2
- component_types=component_types, timeout_ms=timeout_ms, name=name)
- File "c:anaconda3envstf18libsite-packagestensorflowpythonframeworkop_def_library.py", line 787, in _apply_op_helper
- op_def=op_def)
- File "c:anaconda3envstf18libsite-packagestensorflowpythonframeworkops.py", line 3392, in create_op
- op_def=op_def)
- File "c:anaconda3envstf18libsite-packagestensorflowpythonframeworkops.py", line 1718, in __init__
- self._traceback = self._graph._extract_stack() # pylint: disable=protected-access
- OutOfRangeError (see above for traceback): RandomShuffleQueue '_37_shuffle_batch_2/random_shuffle_queue' is closed and has insufficient elements (requested 10, current size 0)
- [[Node: shuffle_batch_2 = QueueDequeueManyV2[component_types=[DT_INT64, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](shuffle_batch_2/random_shuffle_queue, shuffle_batch_2/n)]]
Add Comment
Please, Sign In to add comment