Skip to content

Instantly share code, notes, and snippets.

@SametSahin10
Created January 8, 2024 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SametSahin10/ba6749879209e2b4a95768ddc5f937e4 to your computer and use it in GitHub Desktop.
Save SametSahin10/ba6749879209e2b4a95768ddc5f937e4 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
from matplotlib import pyplot as plt
def slice_matrix(matrix, row_start, col_start, size):
col_end = col_start + size
row_end = row_start + size
return [row[col_start:col_end] for row in matrix[row_start:row_end]]
def convolve2d(kernel, matrix):
# Flip the kernel 180 degrees.
# Horizontal flip
horizontal_flip = [row[::-1] for row in kernel]
# Vertical flip of the already horizontally flipped kernel
flipped_kernel = horizontal_flip[::-1]
output_matrix = np.zeros_like(matrix)
for m, row in enumerate(matrix):
for n, _ in enumerate(row):
sum = 0
for k, kernel_row in enumerate(flipped_kernel):
for l, _ in enumerate(kernel_row):
sum += flipped_kernel[k][l] * matrix[m - k][n - l]
output_matrix[m][n] = sum
return output_matrix
image = cv2.imread('assets/house_pixel_art.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
print("Shape of the image:", gray_image.shape)
image_height, image_width = gray_image.shape[:2]
kernel = np.array(
[[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]]
)
output_image = np.zeros_like(gray_image)
for i in range(1, image_height - 2):
for j in range(1, image_width - 2):
sliced_matrix = slice_matrix(
matrix=gray_image, row_start=i, col_start=j, size=3
)
sliced_matrix_as_np_array = np.array(sliced_matrix)
result_of_convolution = convolve2d(kernel, sliced_matrix_as_np_array)
output_image[i + 1][j + 1] = result_of_convolution[0, 0]
plt.imshow(output_image, cmap='gray')
plt.title('OutDönüşümü'), plt.xticks([]), plt.yticks([])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment