Matika/convolution2D.py
2025-03-09 11:33:42 +01:00

40 lines
1.5 KiB
Python

from PIL import Image
def convolution(input_image, image_filter):
width, height = input_image.size
output_image = Image.new("RGB", (width, height))
for x in range(width):
for y in range(height):
red, green, blue = 0, 0, 0
div = 0
filter_from = -int(len(image_filter[0])/2)
filter_to = len(image_filter[0]) + filter_from
for i in range(filter_from, filter_to):
for j in range(filter_from, filter_to):
if x + i > 0 and x + i < width-1 and y + j > 0 and y + j < height-1:
neighbor_pixel = input_image.getpixel((x + i, y + j))
red += image_filter[i + 1][j + 1] * neighbor_pixel[0]
green += image_filter[i + 1][j + 1] * neighbor_pixel[1]
blue += image_filter[i + 1][j + 1] * neighbor_pixel[2]
div += image_filter[i + 1][j + 1]
if div > 0:
red = int(red/div)
blue = int(blue/div)
green = int(green/div)
output_image.putpixel((x, y), (red, green, blue))
output_image.save("moucha3.jpg")
output_image.close()
input_image.close()
# moucha3.jpg
odsumeni = [[1, 2, 1], [2, 5, 2], [1, 2, 1]]
# moucha1.jpg
sum = [[2, 4, 5, 4, 2], [4, 9, 12, 9, 4], [5, 12, 15, 12, 5], [4, 9, 12, 9, 4], [2, 4, 6, 4, 2]]
# moucha2.jpg
hrany = [[0, 1, 0], [1, -4, 1], [0, 1, 0]]
# convolution(Image.open("pop.jpg"), sum)
convolution(Image.open("moucha.jpg"), odsumeni)