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)
一、经过tf.python_io.TFRecordWriter(地址)返回一个做者对象
二、读取图片地址
三、经过地址将文件信息读取出来
四、从新设置一下图片的大小
五、将文件信息转化为二进制
六、将全部关于图片的东西转化为一个例子
七、将例子序列化
八、将例子写入文件
九、让做者休息
(2)、将数据集放入队列中
一、建立能读取文件内容的对象
二、调用对象中的阅读函数
三、使用阅读函数返回的value值
四、调用能返回字典(包含文件信息,名字)对象
五、将read读取的二进制转化了
六、这里注意再转码时候,要与以前的类型要同样,所以decode_raw函 数的第二参数是:tf.uint8.
七、记住转化为咱们以前的图片的形式,即为三通道的图片
八、转化图片信息的张量
九、转化标签类型
十、调用将文件而且与文件相对应的标签分批处理
十一、因为他们是使用线程的方式调用,所以咱们须要用到线程