Home > Net >  How do you implement a custom non-trainable Convolution filter in tensorflow?
How do you implement a custom non-trainable Convolution filter in tensorflow?

Time:04-06

Using the x-direction sobel filter as an example, how do you implement a non-trainable Convolutional Filter with weights : [[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]] in tensorflow?

CodePudding user response:

I would recommend using tf.nn.conv2d if you want full flexibility in applying filters:

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)

enter image description here

  • Related