如何正确应用带有卷积层的 3x3 过滤器?
How to apply a 3x3 filter with a convolutional layer correctly?
我正在尝试对图像应用简单的拉普拉斯滤波器 (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 结果是一个快速而肮脏的解决方案,但它解决了问题。你真的需要考虑这一点,因为如果中间像素为零而其他像素具有重要值,你也可能会溢出。
使用更改后的代码,安吉丽娜·朱莉的随机图像生成:
我正在尝试对图像应用简单的拉普拉斯滤波器 (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 结果是一个快速而肮脏的解决方案,但它解决了问题。你真的需要考虑这一点,因为如果中间像素为零而其他像素具有重要值,你也可能会溢出。
使用更改后的代码,安吉丽娜·朱莉的随机图像生成: