'How to create a Python convolution kernel?

I'm trying to create a convolution kernel, and the middle is going to be 1.5. Unfortunately I keep running in to ideas on how to do that. I'm trying to create something similar to this

Array = [
        [0 , 1 , 0]
        [1 , 1.5 , 1]
        [0 , 1 , 0]
]


Solution 1:[1]

Since OpenCV uses Numpy to display images, you can simply create a convolution kernel using Numpy.

import numpy as np

convolution_kernel = np.array([[0, 1, 0], 
                               [1, 1.5, 1], 
                               [0, 1, 0]])

Here's the kernel. Note the type is <class 'numpy.ndarray'>

[[0.  1.  0. ]
 [1.  1.5 1. ]
 [0.  1.  0. ]]

To convolve a kernel with an image, you can use cv2.filter2D(). Something like this

import cv2

image = cv2.imread('1.png')
result = cv2.filter2D(image, -1, convolution_kernel)

For more information about kernel construction, look at this. Here are some common kernels and the result after convolving. Using this input image:

enter image description here

Sharpen kernel

sharpen = np.array([[0, -1, 0], 
                    [-1, 5, -1], 
                    [0, -1, 0]])

enter image description here

Laplacian kernel

laplacian = np.array([[0, 1, 0], 
                      [1, -4, 1], 
                      [0, 1, 0]])

enter image description here

Emboss kernel

emboss = np.array([[-2, -1, 0], 
                   [-1, 1, 1], 
                   [0, 1, 2]])

enter image description here

Outline kernel

outline = np.array([[-1, -1, -1], 
                    [-1, 8, -1], 
                    [-1, -1, -1]])

enter image description here

Bottom sobel

bottom_sobel = np.array([[-1, -2, -1], 
                         [0, 0, 0], 
                         [1, 2, 1]])

enter image description here

Left sobel

left_sobel = np.array([[1, 0, -1], 
                       [2, 0, -2], 
                       [1, 0, -1]])

enter image description here

Right sobel

right_sobel = np.array([[-1, 0, 1], 
                        [-2, 0, 2], 
                        [-1, 0, 1]])

enter image description here

Top sobel

top_sobel = np.array([[1, 2, 1], 
                      [0, 0, 0], 
                      [-1, -2, -1]])

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1