Skip to content

Instantly share code, notes, and snippets.

@mmngreco
Created September 12, 2023 09:43
Show Gist options
  • Save mmngreco/ff2448c482e8c0b8ac0c0dcfa9783529 to your computer and use it in GitHub Desktop.
Save mmngreco/ff2448c482e8c0b8ac0c0dcfa9783529 to your computer and use it in GitHub Desktop.
Gaussian Blur (filter) example from scracth
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import convolve2d
def build_filter(size, sigma):
# Construir matriz gaussiana 3x3
x = np.arange(-size / 2 + 1, size / 2 + 1)
y = x[:, np.newaxis]
x0 = y0 = size // 2
gauss = (
(1 / (2 * np.pi * sigma**2))
* np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))
)
# gauss /= np.sum(gauss)
return gauss
def build_image(size):
size = size
image = np.ones((size, size)) # 1 is Black
# Find center and paint around it
center = size // 2
white = 0
image[center, center] = white
image[center - 1, center - 1] = white
image[center + 1, center + 1] = white
image[center - 1, center] = white
image[center + 1, center] = white
image[center, center - 1] = white
image[center, center + 1] = white
return image
def plot(image, image_blur):
_, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(image, cmap='gray')
ax2.imshow(image_blur, cmap='gray')
plt.show()
size = 3
sigma = 5
im_size = 10
gauss = build_filter(size, sigma)
image = build_image(im_size)
print(f"filter: \n{gauss}")
print(f"image: \n{image}")
image_blur = convolve2d(image, gauss, mode='same')
plot(image, image_blur)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment