美文网首页
27-图像文件读取

27-图像文件读取

作者: jxvl假装 | 来源:发表于2019-10-05 11:17 被阅读0次

机器学习的算法都是输入特征值和目标值

图像的特征

图像里面用什么表示特征?
图像是由像素组成的,所以图像的特征值就是指代的像素值

对于黑白图片:称之为单通道图片;每个点只有一个值,这个值称为灰度值(0-255)

对于彩色图片:称之为三通道(RGB)图片;一个像素点有三个值

eg:对于一张200*200像素的图片,如果是黑白图片,特征数为4w;对于彩色图片,特征数为4w*3

格式
存储:uint8(节约空间)
矩阵计算:float(提高精度)

用张量表示特征

图像数字化三要素:长度、宽度、通道数

指定3-D张量:[width, height, channels],eg:200*200的彩色图片,表示成[200, 200, 3]

注意:机器学习中,每一个样本必须保持特征数量一样(像素值一样),eg:图像识别中,人是8w个特征,狗就不能是2w个特征

图像的基本操作

目的

  1. 增加图片数据的统一性
  2. 所有图片转换成指定大小
  3. 缩小图片数据量,防止增加开销

操作

  1. 缩放图片大小

图像操作的api

"""
tf.image.resize_images(images, size)
缩小图片
    images:4-D形状[batch, height, width, channels]或3-D形状的张
            ps:4-D张量,[100, 200, 200, 3]表示100张200*200像素的彩色图片
        量[height, width, channels]的图片数据
    size:1-D int32张量:new_height, new_width,图像的新尺寸
        返回4-D格式或者3-D格式图片
"""

图片读取

图片读取的流程和csv文件的读取流程是一样的

  1. 构造图片文件队列
  2. 构造图片阅读器
  3. 读取图片数据
  4. 处理图片数据

图像读取api

"""
图像读取器
tf.WholeFileReader
    将文件的全部内容作为值输出的读取器
    return:读取器实例
    read(file_queue):输出将是一个文件名(key)和该文件的内容值)

图像解码器
tf.image.decode_jpeg(contents)
    将JPEG编码的图像解码为uint8张量
    contents:文件读取器读取出来的文件内容
    return:uint8张量,3-D形状[height, width, channels]
tf.image.decode_png(contents)
    将PNG编码的图像解码为uint8或uint16张量
    return:张量类型,3-D形状[height, width, channels]
"""

读取图片案例

import os
import tensorflow as tf
def picread(filelist):
    """
    读取狗图片并转换成张量
    :param filelist: 文件路径 + 名字列表
    :return: 
    """
    #构造文件队列
    file_queue = tf.train.string_input_producer(filelist)
    print(file_queue)
    #构造阅读器去读取文件内容,默认读取一张图片
    reader = tf.WholeFileReader()
    key, value = reader.read(file_queue)
    print(value)
    #对读取的图片数据进行解码
    image = tf.image.decode_jpeg(value)
    print(image)
    #处理图片的大小
    image_resize = tf.image.resize_images(image, [200, 200])
    print(image_resize)
    #注意:一定要把样本的形状固定[200, 200, 3],在批处理的时候要求所有形状必须定义
    image_resize.set_shape([200, 200, 3])
    print(image_resize)
    #进行批处理
    image_batch = tf.train.batch([image_resize], batch_size=10, num_threads=1, capacity=10)

    return image_batch
"""
注意:因为批训练是结合子线程去做的,所以下面在会话中必须使用子线程,不然会出错
"""
if __name__ == "__main__":
    file_name = os.listdir("./pic/")
    print(file_name)
    filelist = [os.path.join("./pic/", file) for file in file_name]
    image_batch = picread(filelist)
    with tf.Session() as sess:
        #定义一个线程协调器
        coord = tf.train.Coordinator()
        #开启读文件的线程
        threads = tf.train.start_queue_runners(sess, coord=coord)
        #打印读取的内容
        print(sess.run(image_batch))
        #回收子线程
        coord.request_stop()
        coord.join()

相关文章

网友评论

      本文标题:27-图像文件读取

      本文链接:https://www.haomeiwen.com/subject/wghmuctx.html