How to add custom convolution filters in keras & tensorflow?

i want to add my custom filter in keras & tensorflow, how to do that?

Deep Learning frameworks like Tensorflow and Keras have convolutional layers with filters that are learnable.
Before deep learning, we used to handcraft (non-learnable) kernels for convolutions in CV / Image Processing.

You can just do that in Python instead of using DL frameworks like this:

If you really want to do that on those DL frameworks, what you could do is initialize the weight values of the conv2d layer yourself (according to your desired filter’s values) and freeze that layer (make it non-trainable).

I want to add leung-malik (lm) filter bank in conv2d layer how?

Check the documentation of conv2d in Tensorflow to find out the syntax to pass custom filter:


x_in = np.array([[
  [[2], [1], [2], [0], [1]],
  [[1], [3], [2], [2], [3]],
  [[1], [1], [3], [3], [0]],
  [[2], [2], [0], [1], [1]],
  [[0], [0], [3], [1], [2]], ]])
kernel_in = np.array([
 [ [[2, 0.1]], [[3, 0.2]] ],
 [ [[0, 0.3]],[[1, 0.4]] ], ])
x = tf.constant(x_in, dtype=tf.float32)
kernel = tf.constant(kernel_in, dtype=tf.float32)
tf.nn.conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID')

In the place of kernel_in, put your filter’s values.

If you’re going to train with that in your network, you can use tf.Variable instead of tf.constant for x_in and kernel_in.
To freeze the filter, you can do something like:

kernel = tf.Variable(kernel_in, trainable=False)

but if I have created a function of my filter then how to do add at the place of kernel in I am using leung-malik lm filter bank