import tensorflow as tf
import os
import cv2
def handle_data(photo_path):
#制作資料集
writer = tf.python_io.TFRecordWriter("data_photo.tfrecords")
cast = {"boy"}
for index,name in enumerate(cast):
# print(index,name)
for i in os.listdir(photo_path):
image_path = os.path.join(photo_path,i)
# print(image_path)
imag = cv2.imread(image_path)
# print(imag)
image = cv2.resize(imag, (128,128), interpolation=cv2.INTER_CUBIC)
# print(image)
dr_image = image.tobytes()
# print(dr_image)
exmple = 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 = [dr_image])), }))
writer.write(exmple.SerializeToString())
writer.close()
def put_fileinfo_queue(data_path):
#将檔案放進隊列中
file_queue = tf.train.string_input_producer([data_path])
reader = tf.TFRecordReader()
key,value = reader.read(file_queue)
features = tf.parse_single_example(value,features={"label":tf.FixedLenFeature([],tf.int64),
"img_raw":tf.FixedLenFeature([],tf.string)})#這個要和之前的一樣才能更好的讀取資料
img = tf.decode_raw([features["img_raw"]],tf.uint8)#要與存入資料的時候,一緻
img = tf.cast(img,tf.float32)#然後我們可以轉化為tf.float32
img = tf.reshape(img,[128,128,3])#圖檔是三通道的
lebal = tf.cast(features["label"],tf.int32)
return img,lebal
def batch_size(img,label):
#将圖檔的資訊分批化
image,label=tf.train.shuffle_batch([img,label],batch_size=2,capacity=3,min_after_dequeue=2)
return image,label
init = tf.global_variables_initializer()
if __name__=="__main__":
photo_path="E:\\temporary"
handle_data(photo_path)
file = os.listdir("E:\\da")
for i in file:
filepath = os.path.join("E:\\da",i)
img,label = put_fileinfo_queue(filepath)
image,label = batch_size(img,label)
with tf.Session()as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(3):
print(sess.run([image,label]))
coord.request_stop()
coord.join()
代碼的思路:
圖檔分批處理的方式:
(1)、制作資料集(檔案擴充名為:tfrecord)
1、通過tf.python_io.TFRecordWriter(位址)傳回一個作者對象
2、讀取圖檔位址
3、通過位址将檔案資訊讀取出來
4、重新設定一下圖檔的大小
5、将檔案資訊轉化為二進制
6、将所有關于圖檔的東西轉化為一個例子
7、将例子序列化
8、将例子寫入檔案
9、讓作者休息
(2)、将資料集放入隊列中
1、建立能讀取檔案内容的對象
2、調用對象中的閱讀函數
3、使用閱讀函數傳回的value值
4、調用能傳回字典(包含檔案資訊,名字)對象
5、将read讀取的二進制轉化了
6、這裡注意再轉碼時候,要與之前的類型要一樣,是以decode_raw函 數的第二參數是:tf.uint8.
7、記住轉化為我們之前的圖檔的形式,即為三通道的圖檔
8、轉化圖檔資訊的張量
9、轉化标簽類型
10、調用将檔案并且與檔案相對應的标簽分批處理
11、由于他們是使用線程的方式調用,是以我們需要用到線程
轉載于:https://www.cnblogs.com/MyUniverse/p/9505255.html