zoukankan      html  css  js  c++  java
  • TensorFlow学习笔记之 bmp格式、txt格式数据转换成tfrecord 格式

    一、前言

    之前我们讲过了关于 tfrecord 格式的相关内容,在这个博客——【超分辨率】30分钟学会TensorFlow高效处理数据的方法 - TFRecords 格式,这里我们来说一下如何将bmp 格式、txt 格式数据转换成 tfrecord 格式

    二、bmp 格式数据转换成 tfrecord 格式的代码

    import tensorflow as tf
    import os
    from PIL import Image
    import numpy as np
    
    filepath_list = []
    root = os.walk('./traindatasets/').__next__()[0]
    folder_names = os.walk(root).__next__()[1]
    for folder_name in folder_names:
        folder_path = os.path.join(root, folder_name)
        image_names = os.walk(folder_path).__next__()[2]
        for image_name in image_names:
            image_path = folder_path + '/' + image_name
            filepath_list.append(image_path)
    
    # 创建向 TFRecords 文件写数据记录的 writer
    writer = tf.python_io.TFRecordWriter('train.tfrecord')
    
    for filepath in filepath_list:
        label_path = root + filepath.split('/')[-2] + '/label/label.bmp'
        
        img = Image.open(filepath)
        img = img.resize((512, 512))
        # 将参数使用UTF-8的编码格式转换成byte[]
        img_raw = img.tobytes()
        
        label = Image.open(label_path)
        label = label.resize((512, 512))
        label_raw = label.tobytes()
    
    	# tf.train.Example 协议内存块(protocol buffer)(协议内存块包含了字段 Features)
        example = tf.train.Example(
            features=tf.train.Features(
                feature={
                    'label_raw': tf.train.Feature(
                        bytes_list=tf.train.BytesList(
                            value=[label_raw])), 
                     'img_raw': tf.train.Feature(
                        bytes_list=tf.train.BytesList(
                            value=[img_raw]))}))
        # 将样例序列化为字符串后,写入stat.tfrecord文件
        writer.write(example.SerializeToString())
    # 关闭输出流
    writer.close()
    

    数据集是十张.bmp格式的图片。
    在这里插入图片描述
    运行代码后.bmp格式的图片生成 .tfrecord 格式文件。
    在这里插入图片描述
    由于存储中的精度问题,转换格式前后的数据信息存在可以忽略的差别,-8次的数量级的差别。

    三、txt 格式数据转换成 tfrecord 格式的代码

    整体上和bmp的代码相同,除了txt格式的读取和数据格式,使用np.txt函数进行txt数据的读取;由于是浮点数类型,使用float_listFloatList进行操作,即可。
    在这里插入图片描述
    读取和使用的在之前的博客中讲过,可以自行查看这个博客——【超分辨率】30分钟学会TensorFlow高效处理数据的方法 - TFRecords 格式,使用tfrecord格式文件进行读取和处理的速度和效率都更高。

    如果想要更多的资源,欢迎关注 @我是管小亮,文字强迫症MAX~

    回复【福利】即可获取我为你准备的大礼,包括C++,编程四大件,NLP,深度学习等等的资料。

    想看更多文(段)章(子),欢迎关注微信公众号「程序员管小亮」~

    在这里插入图片描述

  • 相关阅读:
    【Vim】多文件操作
    TC(Traffic Control)命令—linux自带高级流控
    【ceph | 运维】亲和性
    【Vim】Vim分屏基本操作
    Dubbo常用功能06集群容错
    Dubbo负载均衡策略轮询
    Redis知识体系
    Dubbo常用功能09参数回调
    Dubbo负载均衡策略最少活跃调用数
    Dubbo常用功能10异步调用
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13302760.html
Copyright © 2011-2022 走看看