注意:
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()
转载至链接:https://my.oschina.net/ahaoboy/blog/1923134