如何创建Python卷积核?

8

我试图创建一个卷积核,中间的值将会是1.5。不幸的是,我一直在考虑如何实现这个想法。我试图创建类似于这个的东西:

Array = [
        [0 , 1 , 0]
        [1 , 1.5 , 1]
        [0 , 1 , 0]
]
1个回答

17

由于OpenCV使用Numpy显示图像,因此您可以使用Numpy轻松创建卷积核。

import numpy as np

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

这是核心代码。请注意,类型为<class 'numpy.ndarray'>

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

要将核与图像卷积,可以使用cv2.filter2D()。就像这样

import cv2

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

如果想了解更多有关内核构建的信息,请查看这里。以下是一些常见的内核和卷积后的结果。使用此输入图像:

enter image description here

锐化内核

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

图片描述

拉普拉斯核

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

enter image description here

浮雕卷积核

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

这里输入图片描述

概述内核

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

这里输入图片描述

底部Sobel算子

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

enter image description here

左Sobel算子

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

在此输入图像描述

右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]])

输入图像描述


非常抱歉,我的问题表述过于模糊。数组的大小将会变化,因此它可以是任何参数指定的大小,它将创建一个NxN的数组,并且中间必须有1.5。 - user12180143
2
根据您希望内核包含的内容,您可以执行 a = np.ones((N, N)); a[N//2, N//2] = 1.5。还可以查看 scipy.signalscipy.ndimage - Matt Hall
我发现这个答案既有帮助性又有启发性,感谢您抽出时间这么好地发布它! - uhoh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接