Skip to content

Instantly share code, notes, and snippets.

@akseltaylan
Last active March 21, 2021 20:44
Show Gist options
  • Save akseltaylan/7ba678f8ec3012c329a7abefcb1a0700 to your computer and use it in GitHub Desktop.
Save akseltaylan/7ba678f8ec3012c329a7abefcb1a0700 to your computer and use it in GitHub Desktop.
import cv2 as cv
import numpy as np
filename = "img.jpg"
img = cv.imread(filename)
def preview_img(img):
'''
Helper function which displays given
np array img to user.
'''
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
def tadd(a, b):
'''
Add two tuples together.
'''
return (a[0]+b[0], a[1]+b[1], a[2]+b[2])
def tmult(a, val):
'''
Multiply tuple by a scalar.
'''
return (a[0]*val, a[1]*val, a[2]*val)
xlow = 100
xhigh = 300
ylow = 0
yhigh = 200
img = img[xlow:xhigh, ylow:yhigh]
def apply_kernel(img, px, py):
gaussian5x5 = np.matrix([
[0.003765, 0.015019, 0.023792, 0.015019, 0.003765],
[0.015019, 0.059912, 0.094907, 0.059912, 0.015019],
[0.023792, 0.094907, 0.150342, 0.094907, 0.023792],
[0.015019, 0.059912, 0.094907, 0.059912, 0.015019],
[0.003765, 0.015019, 0.023792, 0.015019, 0.003765]
])
ix, iy = img.shape[:2]
col = (0.0, 0.0, 0.0)
gsum = 0.0
for i in range(0, 5):
for j in range(0, 5):
nx = px + i - 2
ny = py + j - 2
if nx >= 0 and nx <= ix-1 and ny >= 0 and ny <= iy-1:
elem_val = gaussian5x5[i,j] * 255.0
col = tadd(col, tmult(img[nx, ny], elem_val))
gsum += elem_val
return ( col[0]/gsum, col[1]/gsum, col[2]/gsum )
def gaussian_blur(img):
x, y = img.shape[:2]
nimg = img
for i in range (0, x):
for j in range(0, y):
nimg[i, j] = apply_kernel(img, i, j)
return img
import copy
original_img = copy.deepcopy(img)
original_img_2 = copy.deepcopy(img)
our_blurred_img = gaussian_blur(original_img)
cv_blurred_img = cv.GaussianBlur(original_img_2,(5,5),0)
imgs = np.concatenate((img, our_blurred_img), axis=1)
imgs = np.concatenate((imgs, cv_blurred_img), axis=1)
preview_img(imgs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment