zoukankan      html  css  js  c++  java
  • 学习笔记TF015:加载图像、图像格式、图像操作、颜色

    TensorFlow支持JPG、PNG图像格式,RGB、RGBA颜色空间。图像用与图像尺寸相同(height*width*chnanel)张量表示。通道表示为包含每个通道颜色数量标量秩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

  • 相关阅读:
    11月2日
    Rain和小爱的幸福山洞
    乍冷初寒
    支付宝接口源代码
    因没有设置文件夹权限导致的发布的页面不能在文本中写人数据
    asp.net真的是并行处理request的吗?
    Javascript学习笔记
    .net Windows服务程序和安装程序制作图解
    String.Trim()真相大揭秘
    c#基础知识总结学习
  • 原文地址:https://www.cnblogs.com/libinggen/p/6914962.html
Copyright © 2011-2022 走看看