import tensorflow as tf
import os
import numpy as np
def picture_read(file_list):
# 1、创建文件名队列,file_list为路径加文件名,tensorflow能将其转换为一阶张量
file_queue = tf.train.string_input_producer(file_list)
# 2、创建文件读取器
file_reader = tf.WholeFileReader()
# 3、读取图片文件
# key为文件名,value为读取图片的原始编码形式
key, value = file_reader.read(file_queue)
# print(key, value)
# 4、解码文件
image = tf.image.decode_jpeg(value)
print("image:", image)
# 5、对图像文件的形状和类型进行修改
# resize操作仅能对height与width进行修改,而无法修改通道数,故不能直接进行批处理
image_resized = tf.image.resize_images(image, size=[299, 299])
# print(image_resize)
# 静态形状修改(即对通道数修改)
image_resized.set_shape(shape=[299, 299, 3])
print("image_resized:", image_resized)
# 6、批处理文件(其中第一个参数tensors要用列表形式输入)
image_batch = tf.train.batch([image_resized], batch_size=100, num_threads=1, capacity=20)
print("image_batch:", image_batch)
with tf.compat.v1.Session() as sess:
# (1)开启线程
# 创建线程协调员
coord = tf.train.Coordinator()
# 开启线程(接收返回的线程列表,方便后续回收线程)
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
key_val, value_val, image_val, image_batch_val = sess.run([key, value, image_resized, image_batch])
# print("key:", key_val)
# print("value:", value_val)
print("image:", image_val)
print("image_batch:", image_batch_val)
print("shape of image:\n", np.shape(image_val))
print("shape of image_batch:\n", np.shape(image_batch_val))
# print("type of image:\n", type(image_val))
# print(key.eval(), "\n", value.eval())
# (2)回收线程
coord.request_stop()
coord.join(threads=threads)
return None
if __name__ == "__main__":
# r是保持字符串原始值的意思,就是说不对其中的符号进行转义。
# 读取文件名
file_name_list = os.listdir(r"E:\GameDownload\dataset_DogRaw\哈士奇")
# print(file_name_list)
# 拼接路径名和文件名,作为创建文件名队列时的参数
file_list = [os.path.join(r"E:\GameDownload\dataset_DogRaw\哈士奇", file_name) for file_name in file_name_list]
# print(file_list)
picture_read(file_list)