我试图将一个简单的拉普拉斯滤波器 (3x3) 应用于图像,但输出非常嘈杂
import tensorflow as tf
import PIL.Image as pil
import numpy as np
k = tf.constant([[1, 1, 1],[1, -8, 1],[1, 1, 1]], dtype=tf.float32)
image = tf.placeholder(dtype=tf.float32, shape=[None, None, None, 1])
kernel = tf.reshape(k, [3, 3, 1, 1], name='kernel')
res = tf.squeeze(tf.nn.conv2d(image, kernel, [1, 1, 1, 1], "SAME"))
with tf.Session() as sess:
img = pil.open('grey.png')
array = np.asarray(img).reshape(1, img.size[0], img.size[1], 1)
out = sess.run(res, feed_dict={image:array})
reverted = ((pil.fromarray(np.uint8(out))).convert('L')).save('testing.png')
正确应用了卷积。问题在于图像反向转换。也就是说,您正在应用带有一些负值的过滤器,中间是-8。这意味着许多卷积像素将具有负的结果值,然后np.uint8
在完成后转换为负值。因此-1将变为255,因此1和-1将具有与之关联的截然不同的光值。这导致模式。
更改以下两行:
array = np.asarray(img, dtype = np.float32 ).reshape(1, img.size[0], img.size[1], 1) / 2
和
reverted = ((pil.fromarray(np.uint8(out + 128))).convert('L')).save('testing.png')
你会得到一个有意义的图像。当然,您可能会想出更好的想法来处理负值,将原始像素转换为[0, 127.5]然后将128添加到结果中是一个快速而肮脏的解决方案,但它解决了问题。您确实需要考虑这一点,因为如果中间像素为零而其他像素具有重要值,您也可能会溢出。
使用更改后的代码,随机的安吉丽娜·朱莉图像会产生:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句