这个是采用soble算子进行滤波
import tensorflow as tf
import os
import matplotlib.pyplot as plt
filename = 'XXX.jpg'
img = tf.gfile.FastGFile(filename, 'rb').read() # 读取三通道图片
image_data = tf.image.decode_jpeg(img) # 进行编码
image_show = tf.image.convert_image_dtype(image_data, dtype=tf.float32)#tensorflow中操作多为浮点型,而图片多为int型,故作此转化
# grayscale = tf.image.rgb_to_grayscale(image_show)
image_batch = tf.expand_dims(image_show, 0)#原来的单张图片为三维(height,width,channel)而下文中卷积核定义为四维(batchsize,height,width,channel),因此通过该方法在0维添加一维,相当于将原来的单张图片三维数据放在一个另一个集合中从而形成四维
#边缘检测滤波器
kernel = 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],dtype=tf.float32)
with tf.Session() as sess:
sess.run(image_show)
# plt.imshow(image_show.eval())
# plt.show()#读入tensorflow后画出原图
conv2d=tf.nn.conv2d(image_batch,kernel,[1,1,1,1],padding='SAME')
activation_map=sess.run(tf.minimum(tf.nn.relu(conv2d),255))#激活措施加均值操作将颜色值置于(0~255)以内的区间
print(activation_map.shape)
encoded_image=activation_map.reshape([250, 200, 1])#注意该步骤将得到的四维np.array数据还原为三维。plt显示的前提
#encoded_image = tf.image.encode_jpeg(activation_map)
#with tf.gfile.GFile('/home/ubuntu/images/output.jpg', 'wb') as f:
#plt(encoded_image.eval())
#plt.show()
#f.write(encoded_image.eval())
active= tf.image.convert_image_dtype(1-encoded_image, dtype = tf.float32)
print('dimensions', active)
grayscale_reshape = tf.reshape(active, [250, 200])
plt.imshow(grayscale_reshape.eval(), cmap='gray')
plt.show()
也有代码是采用这样的滤波器,暂时还不清楚这个滤波器如何得到的!
tf.constant([
[
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]]
],
[
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[8.,0.,0.],[0.,8.,0.],[0.,0.,8.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]]
],
[
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]],
[[-1.,0.,0.],[0.,-1.,0.],[0.,0.,-1.]]
]
])
对这个滤波器进行实现时,发现噪声太多。