图像与内核卷积给出白色输出

时间:2019-01-25 06:04:40

标签: image image-processing convolution gaussian

我有一个代码可以过滤3x3高斯内核的图像,但是输出是白色的。 GuassianFilter函数起作用(输出正确),但是卷积函数有问题。

会有什么问题?我再次检查了代码,但无法解决。

import math
import numpy as np
import cv2
path="funny_hats.jpg"
inputImage = cv2.imread(path,cv2.IMREAD_GRAYSCALE)


def GaussianFilter(img): 
    #generating 3x3 kernel
    kernel = np.ones((3,3), dtype='float64')
    size = 3
    mean = int(size/2)
    sigma = 1 # standart deviation is 1
    sumAll = 0
    for i in range(size):
        for j in range(size):
            kernel[i,j] = math.exp(-1* ((math.pow( (i-mean)/sigma, 2.0) + (math.pow((j-mean)/sigma, 2.0)) ) / (2* math.pow(sigma,2)) )) / (sigma * math.pow(2*math.pi, 1/2))
            sumAll += kernel[i,j]
    # normalizing kernel
    for i in range(size):
        for j in range(size):
            kernel[i,j] /= sumAll
    # Filter image with created kernel   
    img = convolution(img, kernel) # filtered image
    print(img)
    cv2.imshow('aa', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def convolution(img, dest):
    res = img
    [h,w] = img.shape
    [kh, kw] = dest.shape # kernel shape
    kr = int(kh/2) # kernel radius
    res = np.zeros(img.shape)

    for i in range(0+kr,h-kr):
        for j in range(0+kr,w-kr):
            for k in range(-1 * kr, kr + 1):
                for m in range(-1 * kr, kr + 1):
                    res[i,j] += dest[k,m]*img[i+k, j+m]
    res[:,0] = res[:, 1]
    res[:,w-1] = res[:, w-2]
    res[0,:] = res[1,:]
    res[h-1,:] = res[h-2,:]
    return res


GaussianFilter(inputImage)

1 个答案:

答案 0 :(得分:0)

res = img

这是错误的。您必须创建所有像素均为零(黑色)的图像。