1. 程式人生 > 程式設計 >tensorflow生成多個tfrecord檔案例項

tensorflow生成多個tfrecord檔案例項

我就廢話不多說了,直接上程式碼吧!

import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import os
i = 0
j = 0
num_shards = 100#總共寫入的檔案個數
instances_per_shard = 2#每個檔案中的資料個數
sess=tf.InteractiveSession()
cwd = "F:/寒假/google--data/新建資料夾/" #圖片資料所在目錄位置(讀者自己去改就好了)
classes = {'daisy','rose'} #預先自己定義的類別,根據自己的需要修改


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]))
   
for index,name in enumerate(classes):#列舉函式
  class_path = cwd + name + "/"#選取具體資料目錄
  for img_name in os.listdir(class_path):#遍歷檔案列表
    img_path = class_path + img_name#圖片路徑
    img = Image.open(img_path)
    img = img.resize((299,299)) #影象reshape大小設定,根據自己的需要修改
    img_raw = img.tobytes()
      
    example = tf.train.Example(features=tf.train.Features(feature={
          'label': _int64_feature(index),'img_raw': _bytes_feature(img_raw),'i': _int64_feature(i),'j': _int64_feature(j)
        }))
    filename = ("F:/寒假/google--data/data.tfrecords-%.5d-of-%.5d"%(i,num_shards))
    if j == instances_per_shard-1:
      i+=1
    j+=1
    if j == instances_per_shard:
      j=0
    writer = tf.python_io.TFRecordWriter(filename)
      
    writer.write(example.SerializeToString())#將一個example寫入tfrecord檔案
writer.close()

以上這篇tensorflow生成多個tfrecord檔案例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。