Tensorflow中制作tfrecord数据集

本文介绍如何利用TensorFlow的TFRecord格式统一管理并高效处理图像数据集,通过示例代码展示了从读取图像到转换为TFRecord的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tensorflow提供统一的格式来存储数据,TFRecord。使得在之后的系统中可以更加方便的处理,实际问题的数据往往有很多格式和属性,用tfrecord格式可以统一不同原始数据格式,并且更加有效的管理不同属性。

import tensorflow as tf
import os
import cv2 as cv

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))


#打开文件夹,文件夹名称则为标签
file_path="/home/zw/数据集/flower_photos"
#os.walk()返回file_dirs地址和下属子文件夹地址
sub_dirs=[x[:] for x in os.listdir(file_path)]
sub_dirs=sub_dirs[1:]
filrname="/home/zw/数据集/flower_photos.tfrecords"
writer=tf.python_io.TFRecordWriter(filrname)
for i,sub_dir in enumerate(sub_dirs):
    picpath="/home/zw/数据集/flower_photos"+"/"+sub_dir
    sub_dir_pic=[x[:] for x in os.listdir(picpath)]
    print(sub_dir_pic)
    for j in sub_dir_pic:
        print(i,j)
        pic_path="/home/zw/数据集/flower_photos"+"/"+sub_dir+"/"+j
        image=cv.imread(pic_path)
        img=cv.resize(image,dsize=(600,600))
        #cv.imshow('img',img)
        #cv.waitKey(200)
        img_raw=img.tobytes()
        example=tf.train.Example(features=tf.train.Features(feature={
            'image':_bytes_feature(img_raw),
            'label':_int64_feature(i)
        }))
        writer.write(example.SerializeToString())
#cv.destroyAllWindows()
writer.close()







 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值