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
JavaScript
x
6
1
Array = [
2
[0 , 1 , 0]
3
[1 , 1.5 , 1]
4
[0 , 1 , 0]
5
]
6
Advertisement
Answer
Since OpenCV uses Numpy to display images, you can simply create a convolution kernel using Numpy.
JavaScript
1
6
1
import numpy as np
2
3
convolution_kernel = np.array([[0, 1, 0],
4
[1, 1.5, 1],
5
[0, 1, 0]])
6
Here’s the kernel. Note the type is <class 'numpy.ndarray'>
JavaScript
1
4
1
[[0. 1. 0. ]
2
[1. 1.5 1. ]
3
[0. 1. 0. ]]
4
To convolve a kernel with an image, you can use cv2.filter2D()
. Something like this
JavaScript
1
5
1
import cv2
2
3
image = cv2.imread('1.png')
4
result = cv2.filter2D(image, -1, convolution_kernel)
5
For more information about kernel construction, look at this. Here are some common kernels and the result after convolving. Using this input image:
Sharpen kernel
JavaScript
1
4
1
sharpen = np.array([[0, -1, 0],
2
[-1, 5, -1],
3
[0, -1, 0]])
4
Laplacian kernel
JavaScript
1
4
1
laplacian = np.array([[0, 1, 0],
2
[1, -4, 1],
3
[0, 1, 0]])
4
Emboss kernel
JavaScript
1
4
1
emboss = np.array([[-2, -1, 0],
2
[-1, 1, 1],
3
[0, 1, 2]])
4
Outline kernel
JavaScript
1
4
1
outline = np.array([[-1, -1, -1],
2
[-1, 8, -1],
3
[-1, -1, -1]])
4
Bottom sobel
JavaScript
1
4
1
bottom_sobel = np.array([[-1, -2, -1],
2
[0, 0, 0],
3
[1, 2, 1]])
4
Left sobel
JavaScript
1
4
1
left_sobel = np.array([[1, 0, -1],
2
[2, 0, -2],
3
[1, 0, -1]])
4
Right sobel
JavaScript
1
4
1
right_sobel = np.array([[-1, 0, 1],
2
[-2, 0, 2],
3
[-1, 0, 1]])
4
Top sobel
JavaScript
1
4
1
top_sobel = np.array([[1, 2, 1],
2
[0, 0, 0],
3
[-1, -2, -1]])
4