TensorFlow详解猫狗识别(一)--读取自己的数据集

数据集下载
链接: https://pan.baidu.com/s/1SlNAPf3NbgPyf93XluM7Fg 密码: hpn4

数据集分别有12500张cat,12500张dog

读取数据集
数据集的读取,查阅了那么多文档,大致了解到,数据集的读取方法大概会分为两种

1、先生成图片list,和标签list,把图片名称和标签对应起来,再读取制作迭代器(个人认为此方法一般用在,图片名称上可以明确的知道label的)

2、直接生成TFRecord文件,用tf.TFRecordReader()来读取,个人认为,当图片量很大的时候(如:ImageNet)很使用,保存了TFRecord文件后,一劳永逸,省去了生成list的过程

下面贴出代码,简单介绍两种读取数据集的方式。

方法一:
import os
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import cv2
 
# os模块包含操作系统相关的功能,
# 可以处理文件和目录这些我们日常手动需要做的操作。因为我们需要获取test目录下的文件,所以要导入os模块。
#
# 数据构成,在训练数据中,There are 12500 cat,There are 12500 dogs,共25000张
# 获取文件路径和标签
def get_files(file_dir):
    # file_dir: 文件夹路径
    # return: 乱序后的图片和标签
 
    cats = []
    label_cats = []
    dogs = []
    label_dogs = []
    # 载入数据路径并写入标签值
    for file in os.listdir(file_dir):
        name = file.split(sep='.')
        # name的形式为['dog', '9981', 'jpg']
        # os.listdir将名字转换为列表表达
        if name[0] == 'cat':
            cats.append(file_dir + file)
            # 注意文件路径和名字之间要加分隔符,不然后面查找图片会提示找不到图片
            # 或者在后面传路径的时候末尾加两//  'D:/Python/neural network/Cats_vs_Dogs/data/train//'
            label_cats.append(0)
        else:
            dogs.append(file_dir + file)
            label_dogs.append(1)
        # 猫为0,狗为1
 
    print("There are %d cats\nThere are %d dogs" % (len(cats), len(dogs)))
 
    # 打乱文件顺序
    image_list = np.hstack((cats, dogs))
    label_list = np.hstack((label_cats, label_dogs))
    # np.hstack()方法将猫和狗图片和标签整合到一起,标签也整合到一起
 
    temp = np.array([image_list, label_list])
    # 这里的数组出来的是2行10列,第一行是image_list的数据,第二行是label_list的数据
    temp = temp.transpose()  # 转置
    # 将其转换为10行2列,第一列是image_list的数据,第二列是label_list的数据
    np.random.shuffle(temp)
    # 对应的打乱顺序
    image_list = list(temp[:, 0])  # 取所有行的第0列数据
    label_list = list(temp[:, 1])  # 取所有行的第1列数据,并转换为int
    label_list = [int(i) for i in label_list]
 
    return image_list, label_list
 
 
# 生成相同大小的批次
def get_batch(image, label, image_W, image_H, batch_size, capacity):
    # image, label: 要生成batch的图像和标签list
    # image_W, image_H: 图片的宽高
    # batch_size: 每个batch有多少张图片
    # capacity: 队列容量
    # return: 图像和标签的batch
 
    # 将原来的python.list类型转换成tf能够识别的格式
    image = tf.cast(image, tf.string)#强制类型转换
    label = tf.cast(label, tf.int32)
 
    # 生成队列。我们使用slice_input_producer()来建立一个队列,将image和label放入一个list中当做参数传给该函数
    input_queue = tf.train.slice_input_producer([image, label])
 
    image_contents = tf.read_file(input_queue[0])
    # 按队列读数据和标签
    label = input_queue[1]
    image = tf.image.decode_jpeg(image_contents, channels=3)
    # 要按照图片格式进行解码。本例程中训练数据是jpg格式的,所以使用decode_jpeg()解码器,
    # 如果是其他格式,就要用其他geshi具体可以从官方API中查询。
    # 注意decode出来的数据类型是uint8,之后模型卷积层里面conv2d()要求输入数据为float32类型
 
    # 统一图片大小
    # 通过裁剪统一,包括裁剪和扩充
    # image = tf.image.resize_image_with_crop_or_pad(image, image_W, image_H)
    # 我的方法,通过缩小图片,采用NEAREST_NEIGHBOR插值方法
    image = tf.image.resize_images(image, [image_H, image_W], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,
                                   align_corners=False)
    image = tf.cast(image, tf.float32)
    # 因为没有标准化,所以需要转换类型
    # image = tf.image.per_image_standardization(image)   # 标准化数据
    image_batch, label_batch = tf.train.batch([image, label],
                                              batch_size=batch_size,
                                              num_threads=64,  # 线程
                                              capacity=capacity)
    # image_batch是一个4D的tensor,[batch, width, height, channels],
    # label_batch是一个1D的tensor,[batch]。
    # 这行多余?
    label_batch = tf.reshape(label_batch, [batch_size])
 
    return image_batch, label_batch
 
 
 
'''
下面代码为查看图片效果,主要用于观察图片是否打乱,你会可能会发现,图片显示出来的是一堆乱点,不用担心,这是因为你对图片的每一个像素进行了强制类型转化为了tf.float32,使像素值介于-1~1之间,若想看原图,可使用tf.uint8,像素介于0~255
'''
 
 
 
 
 
 
 
# print("yes")
# image_list,label_list = get_files("E:\\Pycharm\\tf-01\\Bigwork\\train\\")
# image_batch,label_batch = train_batch,train_label_batch = get_batch(image_list,label_list,208,208,4,256)
# print("ok")
#
# for i in range(4):
#     with tf.Session()  as sess:
#         i = 0
#         coord = tf.train.Coordinator()
#         threads = tf.train.start_queue_runners(coord=coord)
#         try:
#             while not coord.should_stop() and i < 1:
#                 # just plot one batch size
#                 image, label = sess.run([image_batch, label_batch])
#                 for j in np.arange(4):
#                     print('label: %d' % label[j])
#                     plt.imshow(image[j, :, :, :])
#                     plt.show()
#                 i += 1
#         except tf.errors.OutOfRangeError:
#             print('done!')
#         finally:
#             coord.request_stop()
#         coord.join(threads)
# for i in range(4):
#     sess = tf.Session()
#     image,label = sess.run([image_batch,label_batch])
#     for j in range(4):
#         print('label:%d' % label[j])
#         plt.imshow(image[j, :, :, :])
#         plt.show()
#     sess.close()
方法二
import os
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import cv2
 
 
 
cwd = "E:\\Pycharm\\tf-01\\Bigwork\\test\\"
classes = {'cat', 'dog'}  # 预先自己定义的类别
writer = tf.python_io.TFRecordWriter('test.tfrecords')  # 输出成tfrecord文件
 
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 + '\\'
    print(class_path)
    for img_name in os.listdir(class_path):
        img_path = class_path + img_name  # 每个图片的地址
        img = Image.open(img_path)
        img = img.resize((208, 208))
        img_raw = img.tobytes()  # 将图片转化为二进制格式
        example = tf.train.Example(features=tf.train.Features(feature={
            "label": _int64_feature(index),
            "img_raw": _bytes_feature(img_raw),
        }))
        writer.write(example.SerializeToString())  # 序列化为字符串
 
writer.close()
print("writed OK")
 
 
#生成tfrecord文件后,下次可以不用再执行这段代码!!!
 
 
 
def read_and_decode(filename,batch_size):  # read train.tfrecords
    filename_queue = tf.train.string_input_producer([filename])  
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)  
    features = tf.parse_single_example(serialized_example,
                                   features={
                                       'label': tf.FixedLenFeature([], tf.int64),
                                       'img_raw': tf.FixedLenFeature([], tf.string),
                                   }) 
    img = tf.decode_raw(features['img_raw'], tf.float32)
    img = tf.reshape(img, [128, 128, 3])  # reshape image to 208*208*3
#据说下面这行多余
    #img = tf.cast(img,tf.float32)*(1./255)-0.5
    label = tf.cast(features['label'], tf.int64)  
 
    img_batch, label_batch = tf.train.shuffle_batch([img, label],
                                                batch_size=batch_size,
                                                num_threads = 8,
                                                capacity = 100,
                                                min_after_dequeue = 60,)
    return img_batch, tf.reshape(label_batch, [batch_size])
 
filename = './/train.tfrecords'

 

image_batch、label_batch = read_and_decode(filename,batch_size)

--------------------- 
作者:hush_yang 
来源:CSDN 
原文:https://blog.csdn.net/qq_41004007/article/details/81987631 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值