Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16418

Custom 2D Convolution not sharpening Image

$
0
0

I have written my own 2D Convolution function as follows

def TwoD_convolution(img, kernel):    # Flipping the kernel by 180 degrees    kernel = kernel[::-1]    for i in range(len(kernel)):        kernel[i] = kernel[i][::-1]    # Filling the new image with zeroes    convolve = np.zeros((img.shape[0]+len(kernel)-1, img.shape[1]+len(kernel[0])-1, 3), np.uint8)    midx = len(kernel)//2    midy = len(kernel[0])//2    # Trying to fill each cell one by one, and RGB values    for i in range(convolve.shape[0]):        for j in range(convolve.shape[1]):            for k in range(3):                cur = 0 #current sum                for x in range(-midx,midx+1):                    for y in range(-midy,midy+1):                        if i+x >= 0 and i+x < img.shape[0] and j+y >= 0 and j+y < img.shape[1]:                            # going through every neighbour of the middle cell                            cur += ((img[i+x][j+y][k])*(kernel[midx+x][midy+y]))                convolve[i][j][k] = cur    return convolve

To get a sharpened image, I am calling the function as follows:

display_image(TwoD_convolution(img,[[-0.5,-1,-0.5],[-1,7,-1],[-0.5,-1,-0.5]]))

Where display_image is defined as follows:

 plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB)) plt.show()

It is displaying this image:

enter image description here

I am sure it is getting sharpened on some pixels..but why are the colors at the edges so random ? Where am I going wrong ?

Thanks


Viewing all articles
Browse latest Browse all 16418

Trending Articles



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