【Tensorflow】tensorflow张量操作

在深度学习中,我们通常是对张量进行操作,矩阵可以看成是二阶张量,而一张RGB图片,可以看成是三阶张量(长、宽、颜色)。

Tensorflow中的数据都以张量(tensor)的形式流动,本篇博客中记录一下最近用到的一些在tensorflow中的张量操作,会持续更新。

 

1. 创建值为0的张量

shape_1 = 1
shape_2 = shape_3 = 600
shape_4 = 3
v1 = tf.Variable(tf.zeros([shape_1, shape_2, shape_3, shape_4]))

2. 连接tensor

tensor_1 = tf.Variable(tf.zeros([shape_1, shape_2, shape_3, 3]))
tensor_2 = tf.Variable(tf.zeros([shape_1, shape_2, shape_3, 3]))
tensor_3 = tf.concat([tensor_1, tensor_2], 3)

3. 图片切割

tf.image.crop_to_bounding_box(image, offset_height, offset_width, height, width)

offset_height, offset_width为切割起始点, height, width为切割长度

4. 张量加减法

tf.add(x, y)
tf.subtract(x, y)
a = tf.convert_to_tensor([[1, 2, 3], [4, 5, 6]])

b = tf.convert_to_tensor([[4, 2, 3], [4, 5, 6]])

c = tf.add(a, b)

with tf.Session() as sess:
    print(sess.run(c))

5. 加载预训练模型

一般我们采用:

saver = tf.Saver()
saver.restore(sess, save_path)

或:

checkpoint = tf.train.latest_checkpoint(dir)
saver.restore(sess, checkpoint)

若使用了滑动指数平均(EMA)

tf.train.ExponentialMovingAverage

加载权重时,需要说明,否则不会加载ema参数

variables_to_restore = ema.variables_to_restore()
saver = tf.train.Saver(variables_to_restore)
saver.restore(sess, save_path)

6. 图片二值化

首先将图片转化为单通道(灰度图)

image = tf.image.rgb_to_grayscale(image)

然后使用cast函数对值进行截取

image = tf.image.rgb_to_grayscale(image)
image = tf.cast(image > 0, dtype=tf.float32)

获得01的二值图

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值