试图制作一个应用高斯滤波器的函数,但我得到了相同的图像

Trying to make a function that applys a gaussian filter, but I get the same image

原始图像和高斯图像:

我的代码用于对图像应用高斯滤波器,但它不起作用,给我的图像与我开始使用的图像相同。作为参考,内核的大小为 (5,5),西格玛为 1.0

不允许我使用任何 opencv 函数,所以这就是我手动执行的原因

我的内核:

[[0.00296902 0.01330621 0.02193823 0.01330621 0.00296902]
 [0.01330621 0.0596343  0.09832033 0.0596343  0.01330621]
 [0.02193823 0.09832033 0.16210282 0.09832033 0.02193823]
 [0.01330621 0.0596343  0.09832033 0.0596343  0.01330621]
 [0.00296902 0.01330621 0.02193823 0.01330621 0.00296902]]

def apply_filter(img, kernel):
    kernel_length = len(kernel)
    imx = len(img)
    imy = len(img[0])
    new_image = img[::, ::]
    start = time.time()
    print("Applying filter --> This may take a while")
    for i in range(kernel_length, imx - kernel_length):
        for j in range(kernel_length, imy - kernel_length):
            acc = 0
            for ki in range(kernel_length):
                for kj in range(kernel_length):
                    acc += img[i][j] * kernel[ki][kj]
            new_image[i][j] = acc
    end = time.time()
    print("Application of this filter done! Time taken is ", end - start)
    return new_image

问题在于您计算 acc 值的方式,因此是新像素。您需要将内核应用于当前 i,j 像素的周围像素。

def apply_filter(img, kernel):
    kernel_length = len(kernel)
    imx, imy = img.shape[0:2]
    print(imx)
    print(imy)
    new_image = img[::, ::]
    start = time.time()
    print("Applying filter --> This may take a while")
    for i in range(kernel_length, imx - kernel_length):
        for j in range(kernel_length, imy - kernel_length):
            acc = 0
            for ki in range(kernel_length):
                for kj in range(kernel_length):
                    acc += img[i+ki-2][j+kj-2] * kernel[ki][kj]
            new_image[i][j] = acc
    end = time.time()
    print("Application of this filter done! Time taken is ", end - start)
    return new_image