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] ]
Advertisement
Answer
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:
Sharpen kernel
sharpen = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
Laplacian kernel
laplacian = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])
Emboss kernel
emboss = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]])
Outline kernel
outline = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
Bottom sobel
bottom_sobel = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
Left sobel
left_sobel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
Right sobel
right_sobel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
Top sobel
top_sobel = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])