Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 17945

Can't seem to recreate Gaussian blur using Numpy

$
0
0

I want to implement Gaussian Blur (similar to cv2.GaussianBlur) using only Numpy but I can't seem to understand how to tackle the alpha channel. My code:

# 1D Gaussian PD Functiondef gauss(x, sigma):    g= (1/(((2*np.pi)**0.5)*sigma))* np.exp((-x**2)/(2*sigma**2))    return g
def gaussian_filter(image, sigma, padding=True):    ks= 2*(3*sigma)+1    #Height/ Width of Kernel. Using a Rule of Thumb explained in one of the books.    image_result= np.zeros((image.shape[0], image.shape[1], image.shape[2]))    if padding == True   #Using the appropriate padding to preserve dimensions        pad= int((ks-1)/2)        image= np.pad(image, ((pad,pad),(pad,pad),(0,0)))    k= np.arange(-(ks-1)/2, ks/2)   # A simple array of size ks centred around 0     kernel= gauss(k, sigma)         # The corresponding Gaussian PD values with mean 0.    kernel= kernel[:, np.newaxis]       kernel= kernel@kernel.T         #Using property of 2D Gaussian i.e product of two 1D Gaussians     kernel=kernel[:,:, np.newaxis]      h= kernel     #Adding another dimension to match the number of channels of img    for i in range(image.shape[2]-1):        kernel= np.concatenate((kernel, h), axis=2)    for i in range(image_result.shape[0]):    #Convolution step        for j in range(image_result.shape[1]):            temp= image[i:i+ks, j:j+ks, :]            temp= temp*kernel            image_result[i,j] = (1/(ks*ks))*np.sum(np.sum(temp, axis= 0), axis=0)'''    ad= np.ones((image_result.shape[0], image_result.shape[1],1))     # Not sure about alpha channel. Tried setting it to maximum value.    image_result= np.concatenate((image_result[:,:,0:3],ad), axis=2)'''    return image_result

I read through CV docs and Wikipedia to come up with this implementation. But as I increase the standard deviation, the image gets darker. Also, the result is not inline with produced by cv2.GaussianBlur which seeems to preserve the alpha channel and not convolve it. My results

Any help is deeply appreciated :D


Viewing all articles
Browse latest Browse all 17945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>