【何之源-21个项目玩转深度学习】——Chapter3-3.2 数据准备-将图像数据转为tfrecord形式

在训练自己的模型前,需要准备数据集,tfrecord作为tensorflow较为流行的数据处理格式,我们需要根据已有的图像样本来制作tfrecord格式的数据源。读者完全可按照下面文件的存放路径,调用以下两个.py文件制作自己的tfrecord文件;

何大神提供的数据源结构如下:

data_prepare/
     pic/
        train/
           wood/
           water/
           rock/
           wetland/
           glacier/
           urban/
        validation/
           wood/
           water/
           rock/
           wetland/
           glacier/
           urban/
     src/
        tfrecord.py
     data_convert.py

 

data_prepare文件夹下有个pic的文件夹,该文件夹中又包含train文件夹和validation文件夹;在train文件夹中又包含wood,water,rock,wetland,glacier,urban文件夹,这6个文件夹中分别包含各自类型图像800张,尺寸大致为256x256;

同样在validation中也包含那6个文件夹,各目录下存放了200张图像;

运行data_prepare/ 目录下的data_convert.py程序,运行指令是:

python data_convert.py -t pic/ \
  --train-shards 2 \
  --validation-shards 2 \
  --num-threads 2 \
  --dataset-name satellite

指令解释如下:

-t pic/  是指要转换格式的图像文件存放在pic文件夹下;

--train-shards 2  是指将训练图像生成的tfrecord文件分成2份(考虑数据存储的方便,具体分成几份才合理请百度吧,默认是2份)

--validation-shards 2 是指将验证图像生成的tfrecord文件分成2份(默认2)

  --num-threads 2 线程数(默认2,注意线程数必须要能整除 train-shards 和 validation-shards,来保证每个线程处理的数据块数是相同的)

--dataset-name satellite  数据集名,默认为satellite(根据读者自己的数据集更改,何大神用的是卫星航拍图,给生成的数据集起一个名字。这里将数据集起名 叫“satellite'’,最后生成文件的开头就是 satellite_train 和 satellite_validation)


data_convert.py的代码如下:


 
 
  1. # coding:utf-8
  2. from __future__ import absolute_import
  3. import argparse
  4. import os
  5. import logging
  6. from src.tfrecord import main
  7. def parse_args():
  8. parser = argparse.ArgumentParser()
  9. parser.add_argument( '-t', '--tensorflow-data-dir', default= 'pic/')
  10. parser.add_argument( '--train-shards', default= 2, type=int)
  11. parser.add_argument( '--validation-shards', default= 2, type=int)
  12. parser.add_argument( '--num-threads', default= 2, type=int)
  13. parser.add_argument( '--dataset-name', default= 'satellite', type=str)
  14. return parser.parse_args()
  15. if __name__ == '__main__':
  16. logging.basicConfig(level=logging.INFO)
  17. args = parse_args()
  18. args.tensorflow_dir = args.tensorflow_data_dir
  19. args.train_directory = os.path.join(args.tensorflow_dir, 'train')
  20. args.validation_directory = os.path.join(args.tensorflow_dir, 'validation')
  21. args.output_directory = args.tensorflow_dir
  22. args.labels_file = os.path.join(args.tensorflow_dir, 'label.txt')
  23. if os.path.exists(args.labels_file) is False:
  24. logging.warning( 'Can\'t find label.txt. Now create it.')
  25. all_entries = os.listdir(args.train_directory)
  26. dirnames = []
  27. for entry in all_entries:
  28. if os.path.isdir(os.path.join(args.train_directory, entry)):
  29. dirnames.append(entry)
  30. with open(args.labels_file, 'w') as f:
  31. for dirname in dirnames:
  32. f.write(dirname + '\n')
  33. main(args)

读者可根据作者的数据存放目录结构存放数据,然后根据自己的数据集更改名字;其中上面这个.py文件调用了src文件夹中的tfrecord.py文件(其源码如下);


 
 
  1. # coding:utf-8
  2. # Copyright 2016 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # ==============================================================================
  16. """Converts image data to TFRecords file format with Example protos.
  17. The image data set is expected to reside in JPEG files located in the
  18. following directory structure.
  19. data_dir/label_0/image0.jpeg
  20. data_dir/label_0/image1.jpg
  21. ...
  22. data_dir/label_1/weird-image.jpeg
  23. data_dir/label_1/my-image.jpeg
  24. ...
  25. where the sub-directory is the unique label associated with these images.
  26. This TensorFlow script converts the training and evaluation data into
  27. a sharded data set consisting of TFRecord files
  28. train_directory/train-00000-of-01024
  29. train_directory/train-00001-of-01024
  30. ...
  31. train_directory/train-00127-of-01024
  32. and
  33. validation_directory/validation-00000-of-00128
  34. validation_directory/validation-00001-of-00128
  35. ...
  36. validation_directory/validation-00127-of-00128
  37. where we have selected 1024 and 128 shards for each data set. Each record
  38. within the TFRecord file is a serialized Example proto. The Example proto
  39. contains the following fields:
  40. image/encoded: string containing JPEG encoded image in RGB colorspace
  41. image/height: integer, image height in pixels
  42. image/width: integer, image width in pixels
  43. image/colorspace: string, specifying the colorspace, always 'RGB'
  44. image/channels: integer, specifying the number of channels, always 3
  45. image/format: string, specifying the format, always'JPEG'
  46. image/filename: string containing the basename of the image file
  47. e.g. 'n01440764_10026.JPEG' or 'ILSVRC2012_val_00000293.JPEG'
  48. image/class/label: integer specifying the index in a classification layer. start from "class_label_base"
  49. image/class/text: string specifying the human-readable version of the label
  50. e.g. 'dog'
  51. If you data set involves bounding boxes, please look at build_imagenet_data.py.
  52. """
  53. from __future__ import absolute_import
  54. from __future__ import division
  55. from __future__ import print_function
  56. from datetime import datetime
  57. import os
  58. import random
  59. import sys
  60. import threading
  61. import numpy as np
  62. import tensorflow as tf
  63. import logging
  64. def _int64_feature(value):
  65. """Wrapper for inserting int64 features into Example proto."""
  66. if not isinstance(value, list):
  67. value = [value]
  68. return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
  69. def _bytes_feature(value):
  70. value=tf.compat.as_bytes(value)
  71. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
  72. def _convert_to_example(filename, image_buffer, label, text, height, width):
  73. """Build an Example proto for an example.
  74. Args:
  75. filename: string, path to an image file, e.g., '/path/to/example.JPG'
  76. image_buffer: string, JPEG encoding of RGB image
  77. label: integer, identifier for the ground truth for the network
  78. text: string, unique human-readable, e.g. 'dog'
  79. height: integer, image height in pixels
  80. width: integer, image width in pixels
  81. Returns:
  82. Example proto
  83. """
  84. colorspace = 'RGB'
  85. channels = 3
  86. image_format = 'JPEG'
  87. example = tf.train.Example(features=tf.train.Features(feature={
  88. 'image/height': _int64_feature(height),
  89. 'image/width': _int64_feature(width),
  90. 'image/colorspace': _bytes_feature(colorspace),
  91. 'image/channels': _int64_feature(channels),
  92. 'image/class/label': _int64_feature(label),
  93. 'image/class/text': _bytes_feature(text),
  94. 'image/format': _bytes_feature(image_format),
  95. 'image/filename': _bytes_feature(os.path.basename(filename)),
  96. 'image/encoded': _bytes_feature(image_buffer)}))
  97. return example
  98. class ImageCoder(object):
  99. """Helper class that provides TensorFlow image coding utilities."""
  100. def __init__(self):
  101. # Create a single Session to run all image coding calls.
  102. self._sess = tf.Session()
  103. # Initializes function that converts PNG to JPEG data.
  104. self._png_data = tf.placeholder(dtype=tf.string)
  105. image = tf.image.decode_png(self._png_data, channels= 3)
  106. self._png_to_jpeg = tf.image.encode_jpeg(image, format= 'rgb', quality= 100)
  107. # Initializes function that decodes RGB JPEG data.
  108. self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
  109. self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels= 3)
  110. def png_to_jpeg(self, image_data):
  111. return self._sess.run(self._png_to_jpeg,
  112. feed_dict={self._png_data: image_data})
  113. def decode_jpeg(self, image_data):
  114. image = self._sess.run(self._decode_jpeg,
  115. feed_dict={self._decode_jpeg_data: image_data})
  116. assert len(image.shape) == 3
  117. assert image.shape[ 2] == 3
  118. return image
  119. def _is_png(filename):
  120. """Determine if a file contains a PNG format image.
  121. Args:
  122. filename: string, path of the image file.
  123. Returns:
  124. boolean indicating if the image is a PNG.
  125. """
  126. return '.png' in filename
  127. def _process_image(filename, coder):
  128. """Process a single image file.
  129. Args:
  130. filename: string, path to an image file e.g., '/path/to/example.JPG'.
  131. coder: instance of ImageCoder to provide TensorFlow image coding utils.
  132. Returns:
  133. image_buffer: string, JPEG encoding of RGB image.
  134. height: integer, image height in pixels.
  135. width: integer, image width in pixels.
  136. """
  137. # Read the image file.
  138. with open(filename, 'rb') as f: # need change r to rb
  139. image_data = f.read()
  140. # Convert any PNG to JPEG's for consistency.
  141. if _is_png(filename):
  142. logging.info( 'Converting PNG to JPEG for %s' % filename)
  143. image_data = coder.png_to_jpeg(image_data)
  144. # Decode the RGB JPEG.
  145. image = coder.decode_jpeg(image_data)
  146. # Check that image converted to RGB
  147. assert len(image.shape) == 3
  148. height = image.shape[ 0]
  149. width = image.shape[ 1]
  150. assert image.shape[ 2] == 3
  151. return image_data, height, width
  152. def _process_image_files_batch(coder, thread_index, ranges, name, filenames,
  153. texts, labels, num_shards, command_args):
  154. """Processes and saves list of images as TFRecord in 1 thread.
  155. Args:
  156. coder: instance of ImageCoder to provide TensorFlow image coding utils.
  157. thread_index: integer, unique batch to run index is within [0, len(ranges)).
  158. ranges: list of pairs of integers specifying ranges of each batches to
  159. analyze in parallel.
  160. name: string, unique identifier specifying the data set
  161. filenames: list of strings; each string is a path to an image file
  162. texts: list of strings; each string is human readable, e.g. 'dog'
  163. labels: list of integer; each integer identifies the ground truth
  164. num_shards: integer number of shards for this data set.
  165. """
  166. # Each thread produces N shards where N = int(num_shards / num_threads).
  167. # For instance, if num_shards = 128, and the num_threads = 2, then the first
  168. # thread would produce shards [0, 64).
  169. num_threads = len(ranges)
  170. assert not num_shards % num_threads
  171. num_shards_per_batch = int(num_shards / num_threads)
  172. shard_ranges = np.linspace(ranges[thread_index][ 0],
  173. ranges[thread_index][ 1],
  174. num_shards_per_batch + 1).astype(int)
  175. num_files_in_thread = ranges[thread_index][ 1] - ranges[thread_index][ 0]
  176. counter = 0
  177. for s in range(num_shards_per_batch): #xrange used only in python 2.X ;so use range instend by csq
  178. # Generate a sharded version of the file name, e.g. 'train-00002-of-00010'
  179. shard = thread_index * num_shards_per_batch + s
  180. output_filename = '%s_%s_%.5d-of-%.5d.tfrecord' % (command_args.dataset_name, name, shard, num_shards)
  181. output_file = os.path.join(command_args.output_directory, output_filename)
  182. writer = tf.python_io.TFRecordWriter(output_file)
  183. shard_counter = 0
  184. files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)
  185. for i in files_in_shard:
  186. filename = filenames[i]
  187. label = labels[i]
  188. text = texts[i]
  189. image_buffer, height, width = _process_image(filename, coder)
  190. example = _convert_to_example(filename, image_buffer, label,
  191. text, height, width)
  192. writer.write(example.SerializeToString())
  193. shard_counter += 1
  194. counter += 1
  195. if not counter % 1000:
  196. logging.info( '%s [thread %d]: Processed %d of %d images in thread batch.' %
  197. (datetime.now(), thread_index, counter, num_files_in_thread))
  198. sys.stdout.flush()
  199. writer.close()
  200. logging.info( '%s [thread %d]: Wrote %d images to %s' %
  201. (datetime.now(), thread_index, shard_counter, output_file))
  202. sys.stdout.flush()
  203. shard_counter = 0
  204. logging.info( '%s [thread %d]: Wrote %d images to %d shards.' %
  205. (datetime.now(), thread_index, counter, num_files_in_thread))
  206. sys.stdout.flush()
  207. def _process_image_files(name, filenames, texts, labels, num_shards, command_args):
  208. """Process and save list of images as TFRecord of Example protos.
  209. Args:
  210. name: string, unique identifier specifying the data set
  211. filenames: list of strings; each string is a path to an image file
  212. texts: list of strings; each string is human readable, e.g. 'dog'
  213. labels: list of integer; each integer identifies the ground truth
  214. num_shards: integer number of shards for this data set.
  215. """
  216. assert len(filenames) == len(texts)
  217. assert len(filenames) == len(labels)
  218. # Break all images into batches with a [ranges[i][0], ranges[i][1]].
  219. spacing = np.linspace( 0, len(filenames), command_args.num_threads + 1).astype(np.int)
  220. ranges = []
  221. for i in range(len(spacing) - 1): #xrange used only in python 2.X ;so use range instend by csq
  222. ranges.append([spacing[i], spacing[i + 1]])
  223. # Launch a thread for each batch.
  224. logging.info( 'Launching %d threads for spacings: %s' % (command_args.num_threads, ranges))
  225. sys.stdout.flush()
  226. # Create a mechanism for monitoring when all threads are finished.
  227. coord = tf.train.Coordinator()
  228. # Create a generic TensorFlow-based utility for converting all image codings.
  229. coder = ImageCoder()
  230. threads = []
  231. for thread_index in range(len(ranges)): #xrange used only in python 2.X ;so use range instend by csq
  232. args = (coder, thread_index, ranges, name, filenames,
  233. texts, labels, num_shards, command_args)
  234. t = threading.Thread(target=_process_image_files_batch, args=args)
  235. t.start()
  236. threads.append(t)
  237. # Wait for all the threads to terminate.
  238. coord.join(threads)
  239. logging.info( '%s: Finished writing all %d images in data set.' %
  240. (datetime.now(), len(filenames)))
  241. sys.stdout.flush()
  242. def _find_image_files(data_dir, labels_file, command_args):
  243. """Build a list of all images files and labels in the data set.
  244. Args:
  245. data_dir: string, path to the root directory of images.
  246. Assumes that the image data set resides in JPEG files located in
  247. the following directory structure.
  248. data_dir/dog/another-image.JPEG
  249. data_dir/dog/my-image.jpg
  250. where 'dog' is the label associated with these images.
  251. labels_file: string, path to the labels file.
  252. The list of valid labels are held in this file. Assumes that the file
  253. contains entries as such:
  254. dog
  255. cat
  256. flower
  257. where each line corresponds to a label. We map each label contained in
  258. the file to an integer starting with the integer 0 corresponding to the
  259. label contained in the first line.
  260. Returns:
  261. filenames: list of strings; each string is a path to an image file.
  262. texts: list of strings; each string is the class, e.g. 'dog'
  263. labels: list of integer; each integer identifies the ground truth.
  264. """
  265. logging.info( 'Determining list of input files and labels from %s.' % data_dir)
  266. unique_labels = [l.strip() for l in tf.gfile.FastGFile(
  267. labels_file, 'r').readlines()]
  268. labels = []
  269. filenames = []
  270. texts = []
  271. # Leave label index 0 empty as a background class.
  272. """非常重要,这里我们调整label从0开始以符合定义"""
  273. label_index = command_args.class_label_base
  274. # Construct the list of JPEG files and labels.
  275. for text in unique_labels:
  276. jpeg_file_path = '%s/%s/*' % (data_dir, text)
  277. matching_files = tf.gfile.Glob(jpeg_file_path)
  278. labels.extend([label_index] * len(matching_files))
  279. texts.extend([text] * len(matching_files))
  280. filenames.extend(matching_files)
  281. if not label_index % 100:
  282. logging.info( 'Finished finding files in %d of %d classes.' % (
  283. label_index, len(labels)))
  284. label_index += 1
  285. # Shuffle the ordering of all image files in order to guarantee
  286. # random ordering of the images with respect to label in the
  287. # saved TFRecord files. Make the randomization repeatable.
  288. shuffled_index = list(range(len(filenames))) #add list() by ciky
  289. random.seed( 12345)
  290. random.shuffle(shuffled_index)
  291. filenames = [filenames[i] for i in shuffled_index]
  292. texts = [texts[i] for i in shuffled_index]
  293. labels = [labels[i] for i in shuffled_index]
  294. logging.info( 'Found %d JPEG files across %d labels inside %s.' %
  295. (len(filenames), len(unique_labels), data_dir))
  296. # print(labels)
  297. return filenames, texts, labels
  298. def _process_dataset(name, directory, num_shards, labels_file, command_args):
  299. """Process a complete data set and save it as a TFRecord.
  300. Args:
  301. name: string, unique identifier specifying the data set.
  302. directory: string, root path to the data set.
  303. num_shards: integer number of shards for this data set.
  304. labels_file: string, path to the labels file.
  305. """
  306. filenames, texts, labels = _find_image_files(directory, labels_file, command_args)
  307. _process_image_files(name, filenames, texts, labels, num_shards, command_args)
  308. def check_and_set_default_args(command_args):
  309. if not(hasattr(command_args, 'train_shards')) or command_args.train_shards is None:
  310. command_args.train_shards = 5
  311. if not(hasattr(command_args, 'validation_shards')) or command_args.validation_shards is None:
  312. command_args.validation_shards = 5
  313. if not(hasattr(command_args, 'num_threads')) or command_args.num_threads is None:
  314. command_args.num_threads = 5
  315. if not(hasattr(command_args, 'class_label_base')) or command_args.class_label_base is None:
  316. command_args.class_label_base = 0
  317. if not(hasattr(command_args, 'dataset_name')) or command_args.dataset_name is None:
  318. command_args.dataset_name = ''
  319. assert not command_args.train_shards % command_args.num_threads, (
  320. 'Please make the command_args.num_threads commensurate with command_args.train_shards')
  321. assert not command_args.validation_shards % command_args.num_threads, (
  322. 'Please make the command_args.num_threads commensurate with '
  323. 'command_args.validation_shards')
  324. assert command_args.train_directory is not None
  325. assert command_args.validation_directory is not None
  326. assert command_args.labels_file is not None
  327. assert command_args.output_directory is not None
  328. def main(command_args):
  329. """
  330. command_args:需要有以下属性:
  331. command_args.train_directory 训练集所在的文件夹。这个文件夹下面,每个文件夹的名字代表label名称,再下面就是图片。
  332. command_args.validation_directory 验证集所在的文件夹。这个文件夹下面,每个文件夹的名字代表label名称,再下面就是图片。
  333. command_args.labels_file 一个文件。每一行代表一个label名称。
  334. command_args.output_directory 一个文件夹,表示最后输出的位置。
  335. command_args.train_shards 将训练集分成多少份。
  336. command_args.validation_shards 将验证集分成多少份。
  337. command_args.num_threads 线程数。必须是上面两个参数的约数。
  338. command_args.class_label_base 很重要!真正的tfrecord中,每个class的label号从多少开始,默认为0(在models/slim中就是从0开始的)
  339. command_args.dataset_name 字符串,输出的时候的前缀。
  340. 图片不可以有损坏。否则会导致线程提前退出。
  341. """
  342. check_and_set_default_args(command_args)
  343. logging.info( 'Saving results to %s' % command_args.output_directory)
  344. # Run it!
  345. _process_dataset( 'validation', command_args.validation_directory,
  346. command_args.validation_shards, command_args.labels_file, command_args)
  347. _process_dataset( 'train', command_args.train_directory,
  348. command_args.train_shards, command_args.labels_file, command_args)

这个源码与何大神提供有差异,考虑本人用的是python3,(何大神用的应该是python2),所以如不做更改会报一些错误。


直接运行

python data_convert.py -t pic/ \
  --train-shards 2 \
  --validation-shards 2 \
  --num-threads 2 \
  --dataset-name satellite

可能会报如下错误:

\data_prepare\src\tfrecord.py", line 341, in _find_image_files
random.shuffle(shuffled_index)
File "F:\Python36\lib\random.py", line 275, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'range' object does not support item assignment

 

UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

解决方法是做如下几处做更改(我上面给的tfrecord.py代码是做了更改后的):

//第一
def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
value=tf.compat.as_bytes(value)//这行需要添加    (作者给的代码这行没有)
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

//第二
def _process_image(filename, coder):
with open(filename, 'rb') as f://这里需要加个b(作者给的源码是‘r’)
image_data = f.read()

//第三
xrange需要都改为range  

//第四
_find_image_files:
shuffled_index = list(range(len(filenames)))//这里加上了list   (百度了下说python3中range不返回数组对象,而是返回range对象)

//第五
你的项目路径最好不要有中文,嗯中文路径很多问题的你懂的,拼音也比中文好。

至此,运行指令后会在data_prepare/pic/目录下生成下图5个文件;

 

 

 

 

其中label,txt中内容是

glacier
rock
urban
water
wetland
wood
这6类标签名;

而.tfrecord文件中存放的数据是包含图像数据标签统一存储的二进制文件

tfrecord格式文件使用可参考:https://blog.csdn.net/c20081052/article/details/81315774

 

参考:

https://blog.csdn.net/u010412719/article/details/47088095

https://blog.csdn.net/shijing_0214/article/details/51971734

https://blog.csdn.net/dillon2015/article/details/52987792

https://github.com/hzy46/Deep-Learning-21-Examples/issues/28

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值