欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 TensorFlow 模拟 Sobel 算子实现图像轮廓的卷积操作

最编程 2024-02-06 22:42:10
...

 

原文链接: TensorFlow 卷积操作模拟sobel算子提取图像轮廓

上一篇: TensorFlow cnn 卷积padding规则计算

下一篇: TensorFlow 池化操作

注意:

sobel算子不保证结果在0-255,需要做一次归一化处理,再乘以255

输出的数据shape与图像的shape不一样,需要一次转化

效果

 

代码

import matplotlib.pyplot as plt  # plt 用于显示图片
import matplotlib.image as mpimg  # mpimg 用于读取图片
import numpy as np
import tensorflow as tf

myimg = mpimg.imread('test.jpg')  # 读取和代码处于同一目录下的图片
plt.imshow(myimg)  # 显示图片
plt.axis('off')  # 不显示坐标轴
plt.show()
print(myimg.shape)

full = np.reshape(myimg, [1, *myimg.shape])
inputfull = tf.Variable(tf.constant(1.0, shape=[1, *myimg.shape]))

filter = tf.Variable(tf.constant([[-1.0, -1.0, -1.0], [0, 0, 0], [1.0, 1.0, 1.0],
                                  [-2.0, -2.0, -2.0], [0, 0, 0], [2.0, 2.0, 2.0],
                                  [-1.0, -1.0, -1.0], [0, 0, 0], [1.0, 1.0, 1.0]],
                                 shape=[3, 3, 3, 1]))

op = tf.nn.conv2d(inputfull, filter, strides=[1, 1, 1, 1], padding='SAME')  # 3个通道输入,生成1个feature ma
o = tf.cast(((op - tf.reduce_min(op)) / (tf.reduce_max(op) - tf.reduce_min(op))) * 255, tf.uint8)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    t, f = sess.run([o, filter], feed_dict={inputfull: full})
    print(t.shape)  # (1, 512, 512, 1)
    t = np.reshape(t, myimg.shape[:2])
    print(t.shape)  # (512, 512)
    plt.imshow(t, cmap='Greys_r')  # 显示图片
    plt.axis('off')  # 不显示坐标轴
    plt.show()