Skip to content

Instantly share code, notes, and snippets.

@guissalustiano
Last active July 28, 2020 06:46
Show Gist options
  • Save guissalustiano/8e9b1333d56be43d687f7a6ceb6a7f19 to your computer and use it in GitHub Desktop.
Save guissalustiano/8e9b1333d56be43d687f7a6ceb6a7f19 to your computer and use it in GitHub Desktop.
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_img.flatten())
return out.astype(np.uint8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment