tensorflow进行图片边缘检测

这个是采用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.]]
]
])

对这个滤波器进行实现时,发现噪声太多。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值