TensorFlow图像数据处理

TensorFlow之图像数据处理 在上一章中详细介绍了卷积神经网络,并提到通过卷积神经网络给图像识别技术带来了突破性进展。这一章将从另外一个维度来进一步提升图像识别的精度以及训练的速度。喜欢摄影的读者都知道图像的亮度、对比度等属性对图像的影响是非常大的,相同物体在不同亮度、对比度下差别非常大。然而在很多图像识别问题中,这些因素都不应该影响最后的识别结果。所以本章将介绍如何对图像数据进行预处理使训练得到的神经网络模型尽可能小地减少... 阅读详情

TensorFlow图像数据处理


作者: 大树先生
博客: http://blog.youkuaiyun.com/koala_tree
GitHub:https://github.com/KoalaTree
2017 年 09 月 18 日


–自《TensorFlow实战Google》

在卷积神经网络的训练过程中,图片的很多因素都会对训练数据产生很大的影响,进而影响神经网络模型的训练;同时也需要在。对图片进行预处理的过程中,减小预处理对于训练速度的影响。

一、TFRecord输入数据格式

TensorFlow读取数据,总共有三种方法:

  • 供给数据(Feeding):在TensorFlow程序运行的过程中,使用Python代码来供给数据;
  • 从文件读取数据:在TensorFlow图的起始,让一个输入管线从文件中读取数据;
  • 预加载数据:在TensorFlow图中定义常量或者变量来保存所有数据(仅适用于数据量比较小的情况)。

对于数据量较小的情况下,一般选择直接将数据加载进内存,然后再分batch输入网络进行训练。但是,如果数据量较大,这样的方法太耗内存,这时最好使用tensorflow提供的队列queue,也就是第二种方法从文件读取数据。

1. 输入保存为TFRecord文件

TFRecords文件包含了tf.train.Example 协议内存块(protocol buffer)(协议内存块包含了字段 Features)。

过程:

  • 获取需要保存的数据;
  • 将数据填入到Example协议内存块(protocol buffer);
  • 将协议内存块序列化为一个字符串;
  • 通过tf.python_io.TFRecordWriter写入到TFRecords文件。

其中,一个Example中包含Features,Features里包含Feature的字典,Feature里包含有一个FloatList或ByteList或Int64List。

例程:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np

# 定义函数转化变量类型。
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]))

# 读取mnist数据。
mnist = input_data.read_data_sets("../../datasets/MNIST_data",dtype=tf.uint8, one_hot=True)
images = mnist.train.images
labels = mnist.train.labels
pixels = images.shape[1]
num_examples = mnist.train.num_examples

# 输出TFRecord文件的地址。
filename = "Records/output.tfrecords"
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
    image_raw = images[index].tostring()

    example = tf.train.Example(features=tf.train.Features(feature={
        'pixels': _int64_feature(pixels),
        'label': _int64_feature(np.argmax(labels[index])),
        'image_raw': _bytes_feature(image_raw)
    }))
    writer.write(example.SerializeToString())
writer.close()
print "TFRecord文件已保存。"

2. 读取TFRecord文件

在生成了TFRecords文件后,为了高效地读取数据,在TensorFlow中使用队列(queue)读取数据。

过程:

  • 使用tf.train.string_input_producer获取tfrecords文件;
  • 使用tf.TFRecordReader对文件进行读取;
  • 利用tf.parse_single_example解析器对数据例进行解析;
  • 对feature进行解析;
  • 启动多线程处理输入数据

这个操作可以将Example协议内存块(protocol buffer)解析为张量。

例程:

# 读取文件。
reader = tf.TFRecordReader()
filename_queue = tf.train.string_input_producer(["Records/output.tfrecords"])
_,serialized_example = reader.read(filename_queue)

# 解析读取的样例。
features = tf.parse_single_example(
    serialized_example,
    features={
        'image_raw':tf.FixedLenFeature([],tf.string),
        'pixels':tf.FixedLenFeature([],tf.int64),
        'label':tf.FixedLenFeature([],tf.int64)
    })

images = tf.decode_raw(features['image_raw'],tf.uint8)
labels = tf.cast(features['label'],tf.int32)
pixels = tf.cast(features['pixels'],tf.int32)

sess = tf.Session()

# 启动多线程处理输入数据。
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess,coord=coord)

for i in range(10):
    image, label, pixel = sess.run([images, labels, pixels])

二、图像预处理

1. 图像编码处理

彩色图片不是直接存储三维矩阵的数字,而是记录经过压缩编码后的结果,所以如果想要将一张图像还原成一个三维矩阵,需要解码的过程。

TensorFlow提供了对jpeg和png格式图像的编码/解码函数。

图片读取
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

image_raw_data = tf.gfile.FastGFile("datasets/cat.jpg", 'r').read()

with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(image_raw_data)

    # 输出解码之后的三维矩阵
    print(img_data.eval())

    # 打印图片
    plt.imshow(img_data.eval())
    plt.show()

这里写图片描述

图片转存

将一张图片的三维矩阵重新按照jpeg格式编码并存入指定的文件中。

with tf.Session() as sess:
    # 将图像数据重新编码存储
    encoded_image = tf.image.encode_jpeg(img_data)
    with tf.gfile.GFile("output/1restore_cat.jpg", "wb") as f:
        f.write(encoded_image.eval())

2. 图片大小调整

将载入的图片调整为制定的大小。

第一种:使用算法调整图片大小,并尽量保存原始图像上的所有信息。

with tf.Session() as sess:    
    resized = tf.image.resize_images(img_data, [300, 300], method=0)

    # TensorFlow的函数处理图片后存储的数据是float32格式的,需要转换成uint8才能正确打印图片。
    print "Digital type: ", resized.dtype
    cat = np.asarray(resized.eval(), dtype='uint8')
    # tf.image.convert_image_dtype(rgb_image, tf.float32)
    plt.imshow(cat)
    plt.show()

这里写图片描述

其中,tf.image.resize_images函数的method参数取值对应的图像大小调整算法。

Method取值图像大小调整算法
0双线性插值法(Bilinear interpolation)
1最近邻居法(Nearest neighbor interpolation)
2双三次插值法(Bicubic interpolation)
3面积插值法(Area interpolation)

第二种:通过API对图像进行剪裁或者填充进行图片大小调整。

通过tf.image.resize_image_with_crop_or_pad函数来调整图像大小。

  • 如果原始图像的尺寸大于目标图像,那么这个函数就会自动截取原始图像中居中的部分;
  • 如果目标图像大于原始图像,那么这个函数会自动在原始图像的四周填充全0背景。
with tf.Session() as sess:    
    croped = tf.image.resize_image_with_crop_or_pad(img_data, 1000, 1000)
    padded = tf.image.resize_image_with_crop_or_pad(img_data, 2000, 2000)
    plt.imshow(croped.eval())
    plt.show()
    plt.imshow(padded.eval())
    plt.show()

这里写图片描述

这里写图片描述

利用 tf.image.central_crop来截取中间50%的图片。

with tf.Session() as sess:   
    central_cropped = tf.image.central_crop(img_data, 0.5)
    plt.imshow(central_cropped.eval())
    plt.show()

这里写图片描述

3. 图像翻转

with tf.Session() as sess: 
    # 上下翻转
    #flipped1 = tf.image.flip_up_down(img_data)
    # 左右翻转
    #flipped2 = tf.image.flip_left_right(img_data)

    #对角线翻转
    transposed = tf.image.transpose_image(img_data)
    plt.imshow(transposed.eval())
    plt.show()

    # 以一定概率上下翻转图片。
    #flipped = tf.image.random_flip_up_down(img_data)
    # 以一定概率左右翻转图片。
    #flipped = tf.image.random_flip_left_right(img_data)

这里写图片描述

4. 图像色彩调整

在训练神经网络的模型时,可以随机调整训练图像的属性,如亮度、对比度、饱和度和色相等,从而使得训练得到的模型尽可能小地受到无关因素的影响。

  • 以下代码为调整图像的亮度
with tf.Session() as sess:     
    # 将图片的亮度-0.5。
    #adjusted = tf.image.adjust_brightness(img_data, -0.5)

    # 将图片的亮度-0.5
    #adjusted = tf.image.adjust_brightness(img_data, 0.5)

    # 在[-max_delta, max_delta)的范围随机调整图片的亮度。
    adjusted = tf.image.random_brightness(img_data, max_delta=0.5)

    # 将图片的对比度-5
    #adjusted = tf.image.adjust_contrast(img_data, -5)

    # 将图片的对比度+5
    #adjusted = tf.image.adjust_contrast(img_data, 5)

    # 在[lower, upper]的范围随机调整图的对比度。
    #adjusted = tf.image.random_contrast(img_data, lower, upper)

    plt.imshow(adjusted.eval())
    plt.show()

这里写图片描述

  • 以下代码为调整图像的色相和饱和度
with tf.Session() as sess:         
    adjusted = tf.image.adjust_hue(img_data, 0.1)
    #adjusted = tf.image.adjust_hue(img_data, 0.3)
    #adjusted = tf.image.adjust_hue(img_data, 0.6)
    #adjusted = tf.image.adjust_hue(img_data, 0.9)

    # 在[-max_delta, max_delta]的范围随机调整图片的色相。max_delta的取值在[0, 0.5]之间。
    #adjusted = tf.image.random_hue(image, max_delta)

    # 将图片的饱和度-5。
    #adjusted = tf.image.adjust_saturation(img_data, -5)
    # 将图片的饱和度+5。
    #adjusted = tf.image.adjust_saturation(img_data, 5)
    # 在[lower, upper]的范围随机调整图的饱和度。
    #adjusted = tf.image.random_saturation(img_data, lower, upper)

    # 将代表一张图片的三维矩阵中的数字均值变为0,方差变为1。
    #adjusted = tf.image.per_image_whitening(img_data)

    plt.imshow(adjusted.eval())
    plt.show()

这里写图片描述

5. 处理标注框

给图像中需要关注的物体加标注框,利用tf.image.draw_bounding_boxes函数。

with tf.Session() as sess:         

    # 给出图片的所有标注框,一个标注框有四个数字,分别代表[ymin,xmin,ymax,xmax]
    # 这里给出的都是凸显的相对位置。如在180X267大小的图像中,
    # [0.35, 0.47, 0.5, 0.56] 代表从(63,125)到(90,150)的图像。
    boxes = tf.constant([[[0.05, 0.05, 0.9, 0.7], [0.35, 0.47, 0.5, 0.56]]])

    begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(
        tf.shape(img_data), bounding_boxes=boxes)


    batched = tf.expand_dims(tf.image.convert_image_dtype(img_data, tf.float32), 0) 
    image_with_box = tf.image.draw_bounding_boxes(batched, bbox_for_draw)

    distorted_image = tf.slice(img_data, begin, size)
    plt.imshow(distorted_image.eval())
    plt.show()

这里写图片描述

三、多线程输入数据处理框架

Created with Raphaël 2.1.0 制定原始数据的文件列表 制定文件列表队列 从文件中读取数据 数据预处理 整理成Batch作为神经网络输入

1. 队列与多线程

创建队列
import tensorflow as tf

# 创建一个先进先出的队列,制定队列中最多可以保存两个元素,并制定元素的类型为整数
q = tf.FIFOQueue(2, "int32")

# 对队列中的元素进行初始化
init = q.enqueue_many(([0, 10],))

#将队列中的第一个元素出队列
x = q.dequeue()

# 加入新值入队列
y = x + 1
q_inc = q.enqueue([y])

with tf.Session() as sess:
    init.run()
    for _ in range(5):
        v, _ = sess.run([x, q_inc])
        print v

output:
0
10
1
11
2
  • FIFOQueue:实现一个先进先出的队列;
  • RandomShuffleQueue:从队列中随机选择一个元素;
创建启动并退出多线程

tf.Coordinator主要用于协同多个线程一起停止。

import tensorflow as tf
import numpy as np
import threading
import time

def MyLoop(coord, worker_id):
    while not coord.should_stop():
        # 随机停止所有线程
        if np.random.rand()<0.1:
            print "Stoping from id: %d\n" % worker_id,
            coord.request_stop()
        else:
            print "Working on id: %d\n" % worker_id, 
        time.sleep(1)

coord = tf.train.Coordinator()
threads = [threading.Thread(target=MyLoop, args=(coord, i, )) for i in range(5)]
for t in threads:t.start()
coord.join(threads)

oytput:
Working on id: 0
Working on id: 1
Working on id: 2
Working on id: 3
Working on id: 4
Working on id: 4
Working on id: 3
Working on id: 2
Working on id: 1
Stoping from id: 0
多线程队列操作
import tensorflow as tf

queue = tf.FIFOQueue(100,"float")
enqueue_op = queue.enqueue([tf.random_normal([1])])

# tf.train.QueueRunner创建多个线程运行队列的入队操作。这里启动5个线程,每个线程中运行的是enqueue_op操作。
qr = tf.train.QueueRunner(queue, [enqueue_op] * 5)
tf.train.add_queue_runner(qr)
out_tensor = queue.dequeue()

with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    for _ in range(3): print sess.run(out_tensor)[0]
    coord.request_stop()
    coord.join(threads)

output:
0.747078
-1.50487
0.209827

2. 输入文件队列

tf.train.string_input_producer函数会使用初始化时提供的文件列表创建一个输入队列,输入队列中原始的元素为文件列表中的所有文件。

生成文件存储样例数据
import tensorflow as tf

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
num_shards = 2
instances_per_shard = 2
for i in range(num_shards):
    filename = ('Records/data.tfrecords-%.5d-of-%.5d' % (i, num_shards)) 
    # 将Example结构写入TFRecord文件。
    writer = tf.python_io.TFRecordWriter(filename)
    for j in range(instances_per_shard):
    # Example结构仅包含当前样例属于第几个文件以及是当前文件的第几个样本。
        example = tf.train.Example(features=tf.train.Features(feature={
            'i': _int64_feature(i),
            'j': _int64_feature(j)}))
        writer.write(example.SerializeToString())
    writer.close()

运行程序后,在Records文件夹下生成两个文件:

读取文件
files = tf.train.match_filenames_once("Records/data.tfrecords-*")
filename_queue = tf.train.string_input_producer(files, shuffle=False)
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
      serialized_example,
      features={
          'i': tf.FixedLenFeature([], tf.int64),
          'j': tf.FixedLenFeature([], tf.int64),
      })
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(sess.run(files))
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    for i in range(6):
        print(sess.run([features['i'], features['j']]))
    coord.request_stop()
    coord.join(threads)

output:
['Records/data.tfrecords-00000-of-00002'
 'Records/data.tfrecords-00001-of-00002']
[0, 0]
[0, 1]
[1, 0]
[1, 1]
[0, 0]
[0, 1]
组合训练数据

将输入样例组织成一个batch传输给神经网络可以提高模型训练的效率。

  • tf.train.batch:顺序打batch;
  • tf.train.shuffle_batch:将数据顺序打乱。
example, label = features['i'], features['j']
batch_size = 2

# 设置队列的大小和每个batch大小相关
capacity = 1000 + 3 * batch_size
example_batch, label_batch = tf.train.batch([example, label], batch_size=batch_size, capacity=capacity)

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    for i in range(3):
        cur_example_batch, cur_label_batch = sess.run([example_batch, label_batch])
        print(cur_example_batch, cur_label_batch)
    coord.request_stop()
    coord.join(threads)

output:
[0 0] [0 1]
[1 1] [0 1]
[0 0] [0 1]

3. 输入数据处理框架

展示一个处理输入数据的完整框架流程程序。

import tensorflow as tf

# 创建文件列表,通过文件列表创建输入文件队列,读取文件为“一、TFRecord输入数据格式”创建的文件。
files = tf.train.match_filenames_once("Records/output.tfrecords")
filename_queue = tf.train.string_input_producer(files, shuffle=False) 

# 解析TFRecord文件里的数据

# 读取文件
reader = tf.TFRecordReader()
_,serialized_example = reader.read(filename_queue)

# 解析读取的样例
features = tf.parse_single_example(
    serialized_example,
    features={
        'image_raw':tf.FixedLenFeature([],tf.string),
        'pixels':tf.FixedLenFeature([],tf.int64),
        'label':tf.FixedLenFeature([],tf.int64)
    })

decoded_images = tf.decode_raw(features['image_raw'],tf.uint8)
retyped_images = tf.cast(decoded_images, tf.float32)
labels = tf.cast(features['label'],tf.int32)
#pixels = tf.cast(features['pixels'],tf.int32)
images = tf.reshape(retyped_images, [784])

# 将文件以100个为一组打包
min_after_dequeue = 10000
batch_size = 100
capacity = min_after_dequeue + 3 * batch_size

image_batch, label_batch = tf.train.shuffle_batch([images, labels], 
                                                    batch_size=batch_size, 
                                                    capacity=capacity, 
                                                    min_after_dequeue=min_after_dequeue)

# 训练模型
def inference(input_tensor, weights1, biases1, weights2, biases2):
        layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)
        return tf.matmul(layer1, weights2) + biases2

# 模型相关的参数
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500
REGULARAZTION_RATE = 0.0001   
TRAINING_STEPS = 5000        

weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))
biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))

weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))
biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))

y = inference(image_batch, weights1, biases1, weights2, biases2)

# 计算交叉熵及其平均值
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=label_batch)
cross_entropy_mean = tf.reduce_mean(cross_entropy)

# 损失函数的计算
regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)
regularaztion = regularizer(weights1) + regularizer(weights2)
loss = cross_entropy_mean + regularaztion

# 优化损失函数
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

# 初始化回话并开始训练过程。
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    # 循环的训练神经网络。
    for i in range(TRAINING_STEPS):
        if i % 1000 == 0:
            print("After %d training step(s), loss is %g " % (i, sess.run(loss)))

        sess.run(train_step) 
    coord.request_stop()
    coord.join(threads) 


output:
After 0 training step(s), loss is 367.683 
After 1000 training step(s), loss is 2.29646 
After 2000 training step(s), loss is 2.09075 
After 3000 training step(s), loss is 1.95369 
After 4000 training step(s), loss is 1.91504

下图展示了一个输入数据处理流程的示意图:

这里写图片描述

下面是一个动态解释图:

这里写图片描述

首先,我们先创建数据流图,这个数据流图由一些流水线的阶段组成,阶段间用队列连接在一起。第一阶段将生成文件名,我们读取这些文件名并且把他们排到文件名队列中。第二阶段从文件中读取数据(使用Reader),产生样本,而且把样本放在一个样本队列中。根据你的设置,实际上也可以拷贝第二阶段的样本,使得他们相互独立,这样就可以从多个文件中并行读取。在第二阶段的最后是一个排队操作,就是入队到队列中去,在下一阶段出队。因为我们是要开始运行这些入队操作的线程,所以我们的训练循环会使得样本队列中的样本不断地出队。

tensorflow实现图像的裁剪和填充方法 tensorflow里面提供了实现图像进行裁剪和填充的函数,就是tf.image.resize_image_with_crop_or_pad(img,height,width )。img表示需要改变的图像,height是改变后图像的高度,width是宽度。 例如: import matplotlib.pyplot as plt; import tensorflow as tf; image_raw_data_jpg = tf.gfile.FastGFile('11.jpg', 'r').read() with tf.Session() as sess: img_data_jpg = tf. 立即下载

相关推荐

软件各项会议评审意见模版

读梅老师主编的书,觉得评审意见模板很有参考价值和实用价值,帮梅老师安利一波,顺便记一下笔记。 《系统/子系统规格说明》评审意见模板 20XX年XX月XX日,XXX(主管机关)在XXX(会议地点)主持召开了“《XXX(产品名称)系统规格说明》评审会”。参加会议的有XXX机关,XXX院校,XXX研究所共XX名代表(名单见附件1),会议成立了评审组(名单见附件2),听取了XXX(单位)做的《XXXX报告》。经讨论质询,形成评审意见如下: 系统规格说明对系统的研制目标和范围、工作状态、运行方式以及所要满足的能力需

赵星汉同学的博客 1万+

使用tf.image.resize() 和tf.image.resize_with_pad()调整图像大小

tf.image.resize() 和tf.image.resize_with_pad()的作用和区别

Erosion_ww的博客 4819

数学建模更新10(蒙特卡罗模拟)

蒙特卡罗模拟一.目录二.引例1:布丰投针实验1.投针步骤2.思路3. 历史实验者二.蒙特卡罗模拟概述1.定义2.提出3.原理4.讨论三.应用实例1.三门问题【1】问题【2】代码2.模拟排队问题【1】题目【2】引入参数【3】总结题目信息【4】过程可视化【5】一些推导公式【6】代码3.有约束的非线性规划问题【1】问题的分类【2】例子【3】推导过程【4】代码 一.目录 二.引例1:布丰投针实验 1.投针步骤 步骤: 1:取一张白纸,在上面画出许多条间距为a的平行线 2:去一根长度为l的针,随机的向纸张上投掷n次

沉晨尘宸的博客 3040

tensorflow2.x 图片填充式不失真的resize

在图片预处理的时候往往需要保证原始图像的长宽尺寸保持不变,达到resize前后不失真的效果,但是数据集中很难保证每个样本图像长宽比例相等。为了保证不失真,在图像周围做0填充是不错的选择。 tensorflow2.x提供了很多图片预处理的API,实现填充式resize我们使用的是 tf.image.resize_with_pad( image, target_height, target_width, method=ResizeMethod.BILINEAR, antialias=Fal...

qq_39197555的博客 2049

手把手教你用Xilinx SelectIO IP核搞定ADS42LB69高速ADC的DDR数据采集(附仿真调试技巧)

本文详细介绍了如何使用Xilinx SelectIO IP核实现ADS42LB69高速ADC的DDR数据采集,包括IP核配置、仿真验证和硬件调试技巧。通过精准的时序控制和实战调试方法,解决高速数据采集中的时序对齐问题,提升系统稳定性和可靠性。特别适合FPGA工程师和高速ADC接口设计者参考。

weixin_42533622的博客 153

如何使用 Python 爬取 58 同城招聘信息

职位名称:招聘的岗位名称,如“前端开发”、“数据分析师”等。公司名称:招聘公司的名称。薪资待遇:职位的薪资范围,通常以“面议”、“10k-20k”这样的形式表示。工作地点:公司所在的城市及具体地址。公司福利:例如五险一金、带薪年假、绩效奖金等。发布时间:职位信息的发布时间。一个典型的招聘页面 URL 格式通常如下:在这个页面上,职位信息会分页展示,爬虫需要模拟翻页,获取多个页面的招聘信息。

2201_76125261的博客 1291

tensorflow实现图像色彩的调整

实现图像的调整包括以下几个方面: 调整图像的亮度:tf.image.adjust_brightness(img, p)。img是表示目标图像,p表示对比度,大于零变亮,反之变暗 调整图像的对比度。tf.image.adjust_contrast,用法同上 调整色相。tf.image.adjust_hue。用法同上 调整饱和度:tf.image.adjust_saturation。用法同上

UESTC_C2_403的博客 1760

CKS-CN考试之路----03

这题不需要去生成image和生成deployment所以只需要去检测对应的值即可。编辑/cks/docker/Dockerfile,修改最后第二行的值。编辑/cks/docker/deployment.yaml。

Q先生 824

Tensorflow调用tf.train.shuffle_batch函数报错“OutOfRangeError: RandomShuffleQueue”

1.报错内容: OutOfRangeError (see above for traceback): RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 3, current size 0) [[Node: shuffle_ba...

也许有一天我们再相逢 睁开眼睛看清楚 我才是英雄! 2194

乌鸦搜索算法(CSA)详解:从鸟类智能到优化引擎

乌鸦搜索算法(Crow Search Algorithm,CSA)是2016年由Askarzadeh等人提出的一种新型元启发式优化算法,该算法灵感来源于自然界中乌鸦群体的智能觅食行为。这一创新性算法已成为群体智能优化算法家族中的重要成员,与粒子群优化、遗传算法等传统算法相比,CSA具有原理新颖、参数设置简单、全局搜索能力强等特点。

qq_42212808的博客 1278

037、有源钳位反激变换器(ACF)原理

文章摘要 有源钳位反激变换器(ACF)是一种克服常规反激电路漏感能量处理瓶颈的高效解决方案。文章从实际炸机案例切入,指出RCD钳位电路在高压、宽范围、高功率场景下的局限性。ACF通过增加钳位管和钳位电容,将漏感能量回收而非消耗,实现效率提升2-3%、精准电压钳位和更好EMI性能。文章详细解析了ACF四阶段工作过程、关键波形特征,并指出设计陷阱:漏感需保持1%-3%特定范围、钳位电容ESR要求严格、需专用控制IC支持互补驱动。最后给出实用调试建议,强调ACF适用于65W+功率场景,低压验证后再逐步升压的调试方

Jack010169的博客 260

Tensorflow调用tf.train.shuffle_batch函数报错“OutOfRangeError: RandomShuffleQueue

Tensorflow调用tf.train.shuffle_batch函数报错“OutOfRangeError: RandomShuffleQueue is closed and has insufficient elements (requested , current size ) 我是运行的中间出现这个问题, 1,网上的各种说法,我都试过了,发现任然无法解决; 2,我这边是运行到第7个文件左右出现这个报错(已经验证过不是文件问题),经过查看是因为,运行中不断的在往网络中添加节点,导致运行到一定时间后

zlc0324的博客 1348

ubuntu20.04屏幕亮度无法调节(亮度条调节无效)的简单靠谱解决方案及踩坑历程

0 前言   网上关于ubuntu系统亮度无法调节的问题的解决方法有很多,但是绝大部分并没有什么用(这也是我自己的亲身体会),或者并不靠谱。在遍尝各路方法过后,我终于解决了这一棘手的问题(毕竟最大亮度真的非常刺眼,无法长时间直视),在此记录一下踩坑历程以及最后的解决方案。 1 Naive方法   由于使用需要,最近在电脑原有的win10基础上安装了ubuntu双系统。我安装的是当前新版的ubuntu20.04.2.0,靠谱的安装教程可以参考这里。   之前师兄说双ssd安装双系统会有系统启动引导的问题出现,

zeeq的博客 4万+

tensorflow图像数据处理

今天学到tensorflow图像数据处理,所以写个笔记。1 首先是导入库import matplotlib.pyplot as pltimport tensorflow as tf import numpy as np2 读取图片image_raw_dat...

monk1992的博客 270

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

图像数据处理tensorflow

tensorflow提供了几类简单的图像数据处理函数,下面我们会对其做一些简单的介绍。 ​图像编解码处理 一副RGB色彩模式的图像可以看成是一个三维矩阵, 矩阵中每一个数都代表了图像上的不同位置、不同颜色的亮度,但是图像在存储的时候并没有直接记录这些矩阵中的数字,而是记录了经过压缩编码之后的结果,所以要通过解码把一副图像还原成一个三维矩阵。Tensorflow提供了一些函数可以对一些图像进行编码/...

Ftwhale的博客 571

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Tensorflow——图像数据处理

1 TFrecord输入数据格式

chang的博客 389

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

TensorFlow 图像数据处理

TensorFlow提供了全面的图像处理工具,包括基础操作(加载、调整大小、归一化)、数据增强技术(旋转、亮度/对比度调整)以及高效数据管道构建方法。文章介绍了使用tf.data.Dataset处理图像数据集、高级技巧(gamma调整、边缘检测)以及TFRecord格式存储大规模数据。还涵盖了Keras预处理层集成、自定义处理层实现,以及性能优化方法(缓存、预取、并行处理)和多GPU训练策略。这些功能为深度学习模型的图像数据预处理提供了完整解决方案。

usaccn的博客 541

TensorFlow 核心模块详解:图像数据处理工具

本文介绍了TensorFlow中图像处理的核心流程与工具,包括从文件读取、解码到格式转换、数据增强的完整步骤。通过tf.io读取文件字节,tf.image进行解码和预处理(如归一化、尺寸调整、裁剪填充),并结合tf.data.Dataset构建高效数据管道。重点讲解了数据增强技术(如随机翻转、亮度调整等)以提升模型泛化能力。文章提供了代码示例和实用技巧,帮助开发者掌握图像数据处理的实战方法,为计算机视觉任务奠定数据基础。

没事学AI的博客 992

TensorFlow学习笔记——图像数据处理

主要介绍TensorFlow的图像处理、多线程数据处理框架和数据集的概念及应用。

日积月累,天道酬勤 3109

Tensorflow入门——图像数据处理之必背方法合集

参考资料:《Tensorflow实战Google深度学习框架(第2版)》。本文展示代码运行结果,进行适当分析,并记录实践过程中遇到的所有问题。 一、读取图像、解码并转换成三维矩阵 import tensorflow as tf # 以下函数参数是我用的图片的相对目录 image_raw_data = tf.gfile.FastGFile(&amp;amp;amp;amp;quot;flower_photos/daisy/5547758_...

umbrellalalalala的博客 1016

【TensorFlow】笔记5:图像数据处理

文章目录一、TFRecords输入数据格式1、TFRecord格式介绍2、TFRecord样例程序(1)生成TFRecords文件(2)读取TFRecord文件 目标:如何对图像数据进行预处理使得训练得到的神经网络模型尽可能小地被无关因素所影响。同时,为减小预处理对训练速度的影响,使用多线程处理。 一、TFRecords输入数据格式 TF统一存储数据的格式:TFRecords,二进制文件,可更好利...

盛夏光年 889

tensorflow--图像数据处理

import tensorflow as tf import matplotlib.pyplot as plt import os image_path=os.path.join(os.getcwd(),'9.png') image=tf.gfile.FastGFile(image_path,'rb').read() with tf.Session() as sess: img_after...

qestion_yz_10086的博客 214

TensorFlow图像数据处理之图像预处理,如何对图像进行预处理?

TensorFlow图像数据处理之图像预处理 文章目录TensorFlow图像数据处理之图像预处理TFRecord输入数据格式为什么要把数据转化为TFRecord格式TFRecord样例程序图像数据处理TensorFlow图像处理函数输出原始矩阵和原始图像对图像进行大小调整对图像进行按百分比的剪裁对图片的亮度进行处理对图像添加标记框总结 TFRecord输入数据格式 为什么要把数据转化为TFRec...

JMU_Ma的博客 4162
上一篇: 迁移学习的TensorFlow实现
下一篇: 吴恩达Coursera深度学习课程 DeepLearning.ai 提炼笔记(1-2)-- 神经网络基础
大树先生的博客
博客等级 码龄9年 2692粉丝 200原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值