如何在 tensorflow 中实现自定义不可训练的卷积过滤器?
How do you implement a custom non-trainable Convolution filter in tensorflow?
以 x 方向 sobel 滤波器为例,如何实现一个不可训练的卷积滤波器,权重为:[[-1, 0, +1],[-2, 0, +2], [-1, 0, +1]] 在张量流中?
如果您想要完全灵活地应用过滤器,我建议使用 tf.nn.conv2d
:
import tensorflow as tf
import matplotlib.pyplot as plt
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
seed=123,
image_size=(180, 180),
shuffle=False,
batch_size=2)
images, _ = next(iter(ds.take(1)))
sobel_filter = tf.tile(tf.reshape(tf.constant([[-1, 0, +1],[-2, 0, +2],[-1, 0, +1]], dtype=tf.float32), (3, 3, 1, 1)), [1, 1, 3, 3])
y = tf.nn.conv2d(tf.expand_dims(images[0], axis=0), sobel_filter, strides=[1, 1, 1, 1], padding='SAME')
plt.figure()
f, axarr = plt.subplots(1,2)
axarr[0].imshow(images[0]/ 255)
axarr[1].imshow(y[0] / 255)
以 x 方向 sobel 滤波器为例,如何实现一个不可训练的卷积滤波器,权重为:[[-1, 0, +1],[-2, 0, +2], [-1, 0, +1]] 在张量流中?
如果您想要完全灵活地应用过滤器,我建议使用 tf.nn.conv2d
:
import tensorflow as tf
import matplotlib.pyplot as plt
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
seed=123,
image_size=(180, 180),
shuffle=False,
batch_size=2)
images, _ = next(iter(ds.take(1)))
sobel_filter = tf.tile(tf.reshape(tf.constant([[-1, 0, +1],[-2, 0, +2],[-1, 0, +1]], dtype=tf.float32), (3, 3, 1, 1)), [1, 1, 3, 3])
y = tf.nn.conv2d(tf.expand_dims(images[0], axis=0), sobel_filter, strides=[1, 1, 1, 1], padding='SAME')
plt.figure()
f, axarr = plt.subplots(1,2)
axarr[0].imshow(images[0]/ 255)
axarr[1].imshow(y[0] / 255)