TensorFlow 制作自己的TFRecord数据集

TensorFlow 制作自己的TFRecord数据集

准备图片数据

网上下载了2类吉他和房子的图片, 全部 resize成64*64大小
如下图, 保存项目下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hEjO40Y6-1572314726725)(C:\Users\xiahuadong\Pictures\博客\89.png)]
现在利用这2 类 共108张图片制作TFRecord文件

制作TFRECORD文件

1 先聊一下tfrecord, 这是一种将图像数据和标签放在一起的二进制文件,能更好的利用内存,在tensorflow中快速的复制,移动,读取,存储 等等…
这里注意,tfrecord会根据你选择输入文件的类,自动给每一类打上同样的标签
如在本例中,只有0,1 两类

import os
import tensorflow as tf
from PIL import Image  #注意Image,后面会用到
import matplotlib.pyplot as plt
import numpy as np
# 制作TFRECORD文件===============================================
cwd='photo'
classes={'guitar','house'} #人为 设定 2 类
writer= tf.python_io.TFRecordWriter("train.tfrecords") #要生成的文件
for index,name in enumerate(classes):
    print('index:',index)
    # print('name:',name)
    # photo的子文件夹
    class_path=cwd+'/'+name+'/'
    # print('class_path:',class_path)
    for img_name in os.listdir(class_path):
        # print('img_name:',img_name)
        img_path=class_path+img_name #每一个图片的地址
        print('img_path:',img_path)
        img=Image.open(img_path)
        # print('img:',img)
        # 调整图片大小
        img= img.resize((64,64))
        img_raw=img.tobytes()#将图片转化为二进制字符格式
        # print('img_raw:',img_raw)
        # tf.train.Features:
        #           输入:键,值
        #                 int64_list:输入:整数
        #                 bytes_list:输入:字节(二进制数)
        #           输出:特征
        # tf.train.Example 协议内存块包含了Features字段
        # 通过feature将图片的二进制数据和label进行统一封装
        example = tf.train.Example(features=tf.train.Features(feature={
            "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
            'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
        })) #example对象对label和image数据进行封装
        writer.write(example.SerializeToString())  #序列化为字符串
writer.close()

tf.train.Example 协议内存块包含了Features字段,通过feature将图片的二进制数据和label进行统一封装, 然后将example协议内存块转化为字符串, tf.python_io.TFRecordWriter 写入到TFRecords文件中。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a7PjMNvz-1572314726726)(C:\Users\xiahuadong\Pictures\博客\90.png)]

读取TFRECORD文件

在制作完tfrecord文件后, 将该文件读入到数据流中。
代码如下

# 读取TFRECORD文件=======================================================
def read_and_decode(filename): # 读入train.tfrecords
    filename_queue = tf.train.string_input_producer([filename])#生成一个queue队列
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)#返回文件名和文件
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'label': tf.FixedLenFeature([], tf.int64),
                                           'img_raw' : tf.FixedLenFeature([], tf.string),
                                       })#将image数据和label取出来
# 注意,feature的属性“label”和“img_raw”名称要和制作时统一 ,返回的img数据和label数据一一对应。
    img = tf.decode_raw(features['img_raw'], tf.uint8)
    img = tf.reshape(img, [128, 128, 3])  #reshape为128*128的3通道图片
    img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 #在流中抛出img张量
    label = tf.cast(features['label'], tf.int32) #在流中抛出label张量
    return img, label

注意,feature的属性“label”和“img_raw”名称要和制作时统一 ,返回的img数据和label数据一一对应。返回的img和label是2个 tf 张量

显示tfrecord格式的图片

有些时候我们希望检查分类是否有误,或者在之后的网络训练过程中可以监视,输出图片,来观察分类等操作的结果,那么我们就可以session回话中,将tfrecord的图片从流中读取出来,再保存。 紧跟着一开始的代码写:

# 显示tfrecord格式的图片=========================================================
# 读入流中
filename_queue = tf.train.string_input_producer(["train.tfrecords"])
reader = tf.TFRecordReader()
# 返回文件名和文件
_, serialized_example = reader.read(filename_queue)
# 解析单个例子
features = tf.parse_single_example(serialized_example,
                                   features={
                                       'label': tf.FixedLenFeature([], tf.int64),
                                       'img_raw' : tf.FixedLenFeature([], tf.string),
                                   })  #取出包含image和label的feature对象
# 解码
image = tf.decode_raw(features['img_raw'], tf.uint8)
# 大小转化
image = tf.reshape(image, [64, 64, 3])
label = tf.cast(features['label'], tf.int32)
with tf.Session() as sess: #开始一个会话
    init_op = tf.initialize_all_variables()
    sess.run(init_op)
    coord=tf.train.Coordinator()
    threads= tf.train.start_queue_runners(coord=coord)
    # 54副图片
    for i in range(108):
        example, l = sess.run([image,label])#在会话中取出image和label
        img=Image.fromarray(example, 'RGB')#这里Image是之前提到的
        # print('path:',cwd+str(i)+'_''Label_'+str(l)+'.jpg')
        img.save(cwd+str(i)+'_''Label_'+str(l)+'.jpg')#存下图片
        # print(example, l)
    coord.request_stop()
    coord.join(threads)

代码运行完后, 从tfrecord中取出的文件被保存在photo文件夹了。

总代码如下:

import os
import tensorflow as tf
from PIL import Image  #注意Image,后面会用到
import matplotlib.pyplot as plt
import numpy as np
# 制作TFRECORD文件===============================================
cwd='photo'
classes={'guitar','house'} #人为 设定 2 类
writer= tf.python_io.TFRecordWriter("train.tfrecords") #要生成的文件
for index,name in enumerate(classes):
    print('index:',index)
    # print('name:',name)
    # photo的子文件夹
    class_path=cwd+'/'+name+'/'
    # print('class_path:',class_path)
    for img_name in os.listdir(class_path):
        # print('img_name:',img_name)
        img_path=class_path+img_name #每一个图片的地址
        print('img_path:',img_path)
        img=Image.open(img_path)
        # print('img:',img)
        # 调整图片大小
        img= img.resize((64,64))
        img_raw=img.tobytes()#将图片转化为二进制字符格式
        # print('img_raw:',img_raw)
        # tf.train.Features:
        #           输入:键,值
        #                 int64_list:输入:整数
        #                 bytes_list:输入:字节(二进制数)
        #           输出:特征
        # tf.train.Example 协议内存块包含了Features字段
        # 通过feature将图片的二进制数据和label进行统一封装
        example = tf.train.Example(features=tf.train.Features(feature={
            "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
            'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
        })) #example对象对label和image数据进行封装
        writer.write(example.SerializeToString())  #序列化为字符串
writer.close()
# 读取TFRECORD文件=======================================================
def read_and_decode(filename): # 读入train.tfrecords
    filename_queue = tf.train.string_input_producer([filename])#生成一个queue队列
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)#返回文件名和文件
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'label': tf.FixedLenFeature([], tf.int64),
                                           'img_raw' : tf.FixedLenFeature([], tf.string),
                                       })#将image数据和label取出来
    img = tf.decode_raw(features['img_raw'], tf.uint8)
    img = tf.reshape(img, [128, 128, 3])  #reshape为128*128的3通道图片
    img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 #在流中抛出img张量
    label = tf.cast(features['label'], tf.int32) #在流中抛出label张量
    return img, label
# 显示tfrecord格式的图片=========================================================
# 读入流中
filename_queue = tf.train.string_input_producer(["train.tfrecords"])
reader = tf.TFRecordReader()
# 返回文件名和文件
_, serialized_example = reader.read(filename_queue)
# 解析单个例子
features = tf.parse_single_example(serialized_example,
                                   features={
                                       'label': tf.FixedLenFeature([], tf.int64),
                                       'img_raw' : tf.FixedLenFeature([], tf.string),
                                   })  #取出包含image和label的feature对象
# 解码
image = tf.decode_raw(features['img_raw'], tf.uint8)
# 大小转化
image = tf.reshape(image, [64, 64, 3])
label = tf.cast(features['label'], tf.int32)
with tf.Session() as sess: #开始一个会话
    init_op = tf.initialize_all_variables()
    sess.run(init_op)
    coord=tf.train.Coordinator()
    threads= tf.train.start_queue_runners(coord=coord)
    # 54副图片
    for i in range(108):
        example, l = sess.run([image,label])#在会话中取出image和label
        img=Image.fromarray(example, 'RGB')#这里Image是之前提到的
        # print('path:',cwd+str(i)+'_''Label_'+str(l)+'.jpg')
        img.save(cwd+str(i)+'_''Label_'+str(l)+'.jpg')#存下图片
        # print(example, l)
    coord.request_stop()
    coord.join(threads)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
TensorFlow是一个强大的机器学习框架,它可以通过训练模型实现各种任务,例如图像分类、目标识别和语言处理等。制作自己的图片集是训练这些模型的第一步。 首先,您需要准备一组具有代表性的图片,这些图片应涵盖您要训练的所有类别。例如,如果您想训练一个狗品种分类器,那么您需要准备属于每个品种的多个图片。 接下来,您需要为每个图片打上标签,这将告诉模型该图片所属的类别。您可以为每个类别创建一个标签,例如“边境牧羊犬”或“松狮犬”。 然后,您需要将这些图片分成训练集和测试集。训练集用于训练模型,而测试集用于验证模型的准确性。通常,您需要将所有数据集的80%用于训练集,剩余的20%用于测试集。 接下来,您需要使用TensorFlow的API将图片集导入到模型中。您可以使用“tf.data.Dataset”API加载图片,同时使用“tf.image”API调整图片的大小和格式。 一旦您的数据集准备好了,您可以使用TensorFlow训练模型。您可以选择使用预训练模型,也可以创建自己的模型。此外,您可以使用TensorFlow的深度学习框架,如Keras和Estimator,来创建和训练模型。 最后,您需要对训练后的模型进行评估,并对其性能进行优化。您可以使用各种指标来评估模型,如准确性、精确度和召回率。您可以使用不同的技术来优化模型的性能,例如数据增强、Dropout和批标准化等。 总之,制作自己的图片集是TensorFlow训练模型的必要步骤之一。通过导入、分类和训练图像数据,可以创建具有各种应用程序的强大模型,例如图像分类、目标检测和人脸识别等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏华东的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值