Skip to content

Instantly share code, notes, and snippets.

@guissalustiano
Created July 28, 2020 14:21
Show Gist options
  • Save guissalustiano/515732ba1dd4f75b6d83f00b261c0aa6 to your computer and use it in GitHub Desktop.
Save guissalustiano/515732ba1dd4f75b6d83f00b261c0aa6 to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
def rgbToGray(img):
# Baseado em https://pillow.readthedocs.io/en/3.2.x/reference/Image.html#PIL.Image.Image.convert
return np.matmul(img, [0.2989, 0.5870, 0.1140]).astype(np.uint())
def convolution(img: np.ndarray, filt: np.ndarray):
iw, ih = img.shape
kw, kh = filt.shape
assert(kw % 2 == 1 and kh % 2 == 1) # Garante que o filtro tenha um centro
kcx, kcy = kw//2, kh//2 # Calcula a posição central
out = np.zeros(img.shape)
for x, y in np.ndindex(*out.shape):
#Pega os pixels que serão usados na operação com o filtro
sub_img = img[max(0, x-kcx): min(iw, x-kcx + (kw)),
max(0, y-kcy): min(ih, y-kcy + (kh))]
# Pega o filtro com pixels removendo os que estão de fora da imagem
sub_filt = filt[max(0,kcx-x): (kw if iw > x+kcx else iw-(x+kcx)-1),
max(0, kcy-y): (kh if ih > y+kcy else ih-(y+kcy)-1)]
# Multiplica cada pixel pelo seu respectivo peso e divide pela soma dos pesos
out[x, y] = np.vdot(sub_img, sub_filt)/np.sum(sub_filt.flatten())
out = np.abs(out) # Explicação disso vem logo
return out.astype(np.uint8)
def gaussian_kernel(size, sigma=1):
center = size//2
x, y = np.mgrid[-center:center+1, -center:center+1]
return np.exp(-((x**2 + y**2) / (2*sigma**2)))
if __name__ == '__main__':
img = plt.imread('arara.jpg')
img = rgbToGray(img)
filt = np.ones(25**2).reshape(25,25)
img = convolution(img, filt)
plt.imsave('araraBlured.jpg', img, cmap=cm.gray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment