V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cralison
V2EX  ›  TensorFlow

学习笔记 TF015:加载图像、图像格式、图像操作、颜色

  •  1
     
  •   cralison · 2017-05-28 07:36:33 +08:00 · 3891 次点击
    这是一个创建于 2519 天前的主题,其中的信息可能已经有所发展或是发生改变。

    TensorFlow 支持 JPG、PNG 图像格式,RGB、RGBA 颜色空间。图像用与图像尺寸相同(heightwidthchnanel)张量表示。通道表示为包含每个通道颜色数量标量秩 1 张量。图像所有像素存在磁盘文件,需要被加载到内存。

    图像加载与二进制文件相同。图像需要解码。输入生成器(tf.train.string_input_producer)找到所需文件,加载到队列。tf.WholeFileReader 加载完整图像文件到内存,WholeFileReader.read 读取图像,tf.image.decode_jpeg 解码 JPEG 格式图像。图像是三阶张量。RGB 值是一阶张量。加载图像格式为[batch_size,image_height,image_width,channels]。批数据图像过大过多,占用内存过高,系统会停止响应。

    大尺寸图像输入占用大量系统内存。训练 CNN 需要大量时间,加载大文件增加更多训练时间,也难存放多数系统 GPU 显存。大尺寸图像大量无关本征属性信息,影响模型泛化能力。

    tf.image.decode_jpeg 解码 JPEG 格式图像。tf.image.decode_png 解码 PNG 格式图像。 差别在 alpha(透明度)信息。移除区域 alpha 值设 0,有助于标识。JPEG 图像频繁操作会留下伪影(atrifact)。PNG 格式无损压缩,保留原始文件全部信息(被缩放或降采样除外),文件体积较大。

    TensorFlow 内置文件格式 TFRecord,二进制数据和训练类别标签数据存储在同一文件。模型训练前图像转换为 TFRecord 格式。TFRecord 文件是 protobuf 格式。数据不压缩,可快速加载到内存。

    独热编码(one-hot encoding)格式,表示多类分类(单)标签数据。图像加载到内存,转换为字节数组,添加到 tf.train.Example 文件,SerializeToString 序列化为二进制字符,保存到磁盘。序列化将内存对象转换为可安全传输文件格式,可被加载,可被反序列化为样本格式。直接加载 TFRecord 文件,可以节省训练时间。支持写入多个样本。

    TFRecordReader 对象读取 TFRecord 文件。tf.parse_single_example 不解码图像,解析 TFRecord,图像按原始字节读取(tf.decode-raw)。tf.reshape 调整形状,使布局符合 tf.nn.conv2d 要求([image_height,image_width,image_channels])。tf.expand 扩展维数,把 batch_size 维添加到 input_batch。tf.equal 检查是否加载同一图像。sess.run(tf.cast(tf_record_features['label'], tf.string))查看从 TFRecord 文件加载的标签。使用图像数据推荐使用 TFRecord 文件存储数据与标签。做好图像预处理并保存结果。

    最好在预处理阶段完成图像操作,裁剪、缩放、灰度调整等。图像加载后,翻转、扭曲,使输入网络训练信息多样化,缓解过拟合。Python 图像处理框架 PIL、OpenCV。TensorFlow 提供部分图像处理方法。裁剪,tf.image.central_crop,移除图像区域,完全丢弃其中信息,与 tf.slice(移除张量分量)类似,基于图像中心返回结果。训练时,如果背景有用,tf.image.crop_to_bounding_box(只接收确定形状张量,输入图像需要事先在数据流图运行) 随机裁剪区域起始位置到图像中心的偏移量。

    tf.image.pad_to_bounding_box 用 0 填充边界,使输入图像符合期望尺寸。尺寸过大过小图像,边界填充灰度值 0 像素。tf.image.resize_image_with_crop_or_pad,相对图像中心,裁剪或填充同时进行。

    翻转,每个像素位置沿水平或垂真方向翻转。随机翻转图像,可以防止过拟合。tf.slice 选择图像数据子集。tf.image.flip_left_right 完成水平翻转。tf.image.flip_up_down 完成垂直翻转。seed 参数控制翻转随机性。

    编辑过图像训练,误导 CNN 模型。属性随机修改,使 CNN 精确匹配编辑过或不同光照图像特征。tf.image.adjust_brightness 调整灰度。tf.image.adjust_contrast 调整对比度。调整对比度,选择较小增量,避免“过曝”,达到最大值无法恢复,可能全白全黑。tf.slice 突出改变像素。tf.image.adjust_hue 调整色度,色彩更丰富。delta 参数控制色度数量。tf.image.adjust_saturation 调整饱和度,突出颜色变化。

    单一颜色图像,灰度颜色空间,单颜色通道,只需要单个分量秩 1 张量。缩减颜色空间可以加速训练。灰度图具有单个分量,取值范围[0,255]。tf.image.rgb_to_grayscale 把 RGB 图像转换为灰度图。灰度变换,每个像素所有颜色值取平均。tf.image.rgb_to_hsv RGB 图像转换为 HSV, 色度、饱和度、灰度构成 HSV 颜色空间,3 个分量秩 1 张量。更贴近人类感知属性。HSB,B 亮度值。tf.image.hsv_to_rgb HSV 图像转换为 RGB,tf.image.grayscale_to_rgb 灰度图像转换为 RGB。python-colormath 提供 LAB 颜色空间,颜色差异映射贴近人类感知,两个颜色欧氏距离反映人类感受的颜色差异。

    tf.image.convert_image_dtype(image, dtype,saturate=False) 图像数据类型变化,像素值比例变化。

    import tensorflow as tf
    sess = tf.Session()
    red = tf.constant([255, 0, 0])
    file_names = ['./images/chapter-05-object-recognition-and-classification/working-with-images/test-input-image.jpg']
    filename_queue = tf.train.string_input_producer(file_names)
    image_reader = tf.WholeFileReader()
    _, image_file = image_reader.read(filename_queue)
    image = tf.image.decode_jpeg(image_file)
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess,coord=coord)
    print sess.run(image)
    filename_queue.close(cancel_pending_enqueues=True)
    coord.request_stop()
    coord.join(threads)
    print "------------------------------------------------------"
    image_label = b'\x01'
    image_loaded = sess.run(image)
    image_bytes = image_loaded.tobytes()
    image_height, image_width, image_channels = image_loaded.shape
    writer = tf.python_io.TFRecordWriter("./output/training-image.tfrecord")
    example = tf.train.Example(features=tf.train.Features(feature={
            'label': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_label])),
            'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_bytes]))
        }))
    print example
    writer.write(example.SerializeToString())
    writer.close()
    print "------------------------------------------------------"
    tf_record_filename_queue = tf.train.string_input_producer(["./output/training-image.tfrecord"])
    tf_record_reader = tf.TFRecordReader()
    _, tf_record_serialized = tf_record_reader.read(tf_record_filename_queue)
    tf_record_features = tf.parse_single_example(
    tf_record_serialized,
    features={
        'label': tf.FixedLenFeature([], tf.string),
        'image': tf.FixedLenFeature([], tf.string),
        })
    tf_record_image = tf.decode_raw(
        tf_record_features['image'], tf.uint8)
    tf_record_image = tf.reshape(
        tf_record_image,
        [image_height, image_width, image_channels])
    print tf_record_image
    tf_record_label = tf.cast(tf_record_features['label'], tf.string)
    print tf_record_label
    print "------------------------------------------------------"
    sess.close()
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess,coord=coord)
    print sess.run(tf.equal(image, tf_record_image))
    sess.run(tf_record_label)
    coord.request_stop()
    coord.join(threads)
    print "------------------------------------------------------"
    print sess.run(tf.image.central_crop(image, 0.1))
    real_image = sess.run(image)
    bounding_crop = tf.image.crop_to_bounding_box(
        real_image, offset_height=0, offset_width=0, target_height=2, target_width=1)
    print sess.run(bounding_crop)
    print "------------------------------------------------------"
    real_image = sess.run(image)
    pad = tf.image.pad_to_bounding_box(
        real_image, offset_height=0, offset_width=0, target_height=4, target_width=4)
    print sess.run(pad)
    print "------------------------------------------------------"
    crop_or_pad = tf.image.resize_image_with_crop_or_pad(
        real_image, target_height=2, target_width=5)
    print sess.run(crop_or_pad)
    print "------------------------------------------------------"
    sess.close()
    sess = tf.Session()
    top_left_pixels = tf.slice(image, [0, 0, 0], [2, 2, 3])
    flip_horizon = tf.image.flip_left_right(top_left_pixels)
    flip_vertical = tf.image.flip_up_down(flip_horizon)
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess,coord=coord)
    print sess.run([top_left_pixels, flip_vertical])
    print "------------------------------------------------------"
    top_left_pixels = tf.slice(image, [0, 0, 0], [2, 2, 3])
    random_flip_horizon = tf.image.random_flip_left_right(top_left_pixels)
    random_flip_vertical = tf.image.random_flip_up_down(random_flip_horizon)
    print sess.run(random_flip_vertical)
    print "------------------------------------------------------"
    example_red_pixel = tf.constant([254., 2., 15.])
    adjust_brightness = tf.image.adjust_brightness(example_red_pixel, 0.2)
    print sess.run(adjust_brightness)
    print "------------------------------------------------------"
    adjust_contrast = tf.image.adjust_contrast(image, -.5)
    print sess.run(tf.slice(adjust_contrast, [1, 0, 0], [1, 3, 3]))
    print "------------------------------------------------------"
    adjust_hue = tf.image.adjust_hue(image, 0.7)
    print sess.run(tf.slice(adjust_hue, [1, 0, 0], [1, 3, 3]))
    print "------------------------------------------------------"
    adjust_saturation = tf.image.adjust_saturation(image, 0.4)
    print sess.run(tf.slice(adjust_saturation, [1, 0, 0], [1, 3, 3]))
    print "------------------------------------------------------"
    gray = tf.image.rgb_to_grayscale(image)
    print sess.run(tf.slice(gray, [0, 0, 0], [1, 3, 1]))
    print "------------------------------------------------------"
    hsv = tf.image.rgb_to_hsv(tf.image.convert_image_dtype(image, tf.float32))
    print sess.run(tf.slice(hsv, [0, 0, 0], [3, 3, 3]))
    print "------------------------------------------------------"
    rgb_hsv = tf.image.hsv_to_rgb(hsv)
    rgb_grayscale = tf.image.grayscale_to_rgb(gray)
    print rgb_hsv, rgb_grayscale
    print "------------------------------------------------------"
    

    参考资料: 《面向机器智能的 TensorFlow 实践》

    欢迎加我微信交流:qingxingfengzi

    我的微信公众号:qingxingfengzigz

    我老婆张幸清的微信公众号:qingqingfeifangz

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2610 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 10:41 · PVG 18:41 · LAX 03:41 · JFK 06:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.