Tensorflow框架tf.nn.conv2d函数

最近学习了tensorglow框架,今天主要学习了下conv2d函数。

conv2d函数实现了卷积运算,声明如下:

tf.nn.conv2d( input, filter, strides, padding, use_cudnn_on_gpu=True, data_format='NHWC', dilations=[1, 1, 1, 1], name=None )

input:即输入,是一个维度为[batch,height,weight,in_channel]的tensor;

filter:即卷积核,是一个维度为[height,weight,in_channel,out_channels]的tensor;

strides:步长,是一个4维tensor,每一维均表示input输入对应的4个维度方向的移动步长;

padding:string类型,可以是:"SAME", "VALID",要使用的填充算法的类型。

代码如下:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

g1 = tf.Graph()

with g1.as_default():
    # 读入二进制文件
    image_raw = tf.gfile.FastGFile('./flow1.jpg','rb').read()
 
    # 解码为tf中的图像格式
    img = tf.image.decode_jpeg(image_raw)  #Tensor
    
    M = tf.reshape(img,[1, 375,500, 3])
    M = tf.to_float(M) 

    x = tf.placeholder('float32', [1, None, None, 3])    
    filter_weight = tf.get_variable('weights', [3, 3, 3, 3], 
                                initializer = tf.constant_initializer([[[0,-1, 0],[-1,4, -1],[0,-1, 0]],[[0,-1, 0],[-1,4, -1],[0,-1, 0]],[[0,-1, 0],[-1,4, -1],[0,-1, 0]]]))
    biases = tf.get_variable('biases', [3], initializer = tf.constant_initializer(1))
    
    conv = tf.nn.conv2d(x, filter_weight, strides = [1, 2, 2, 1], padding = 'SAME')
    bias = tf.nn.bias_add(conv, biases)

    init = tf.global_variables_initializer()

with tf.Session(graph=g1) as sess:
    sess.run(init)
    rel_M = M.eval()
    print(rel_M.shape)

    conv_rel = sess.run(bias,feed_dict={x:rel_M})
    new = np.reshape(conv_rel,(188,250,3))
    print(new.shape)

    plt.figure(1)
    plt.imshow(new)
    plt.show()

输出:

注意:如果filter_weight的维度为[3, 3, 3, 1],那卷积运算后得到的图像只有一个通道。因为,卷积核会在各个通道做相同的卷积,然后各像素后的卷积值求和。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值