99 lines
2.6 KiB
Python
99 lines
2.6 KiB
Python
import requests
|
|
from PIL import Image
|
|
import numpy as np
|
|
from io import BytesIO
|
|
|
|
from matplotlib import pyplot as plt
|
|
import plotly.graph_objects as go
|
|
|
|
|
|
def apply_convolution_operator(operator, image):
|
|
if isinstance(image, str):
|
|
image = Image.open(image)
|
|
if isinstance(image, Image.Image):
|
|
x_pixel, y_pixel = image.size
|
|
|
|
# turn into editable list of colors
|
|
data = np.asarray(image, dtype=np.uint8)
|
|
# storage for the convoluted image
|
|
data_new = np.zeros([y_pixel, x_pixel, 3], dtype=np.uint8)
|
|
|
|
for i in range(1, y_pixel - 1):
|
|
for j in range(1, x_pixel - 1):
|
|
for k in range(3):
|
|
new_value = (
|
|
operator[0, 0] * data[i - 1, j - 1, k] +
|
|
operator[0, 1] * data[i - 1, j, k] +
|
|
operator[0, 2] * data[i - 1, j + 1, k] +
|
|
operator[1, 0] * data[i, j - 1, k] +
|
|
operator[1, 1] * data[i, j, k] +
|
|
operator[1, 2] * data[i, j + 1, k] +
|
|
operator[2, 0] * data[i + 1, j - 1, k] +
|
|
operator[2, 1] * data[i + 1, j, k] +
|
|
operator[2, 2] * data[i + 1, j + 1, k]
|
|
)
|
|
new_value = max(0, min(new_value, 255))
|
|
data_new[i, j, k] = new_value
|
|
return Image.fromarray(data_new)
|
|
else:
|
|
raise TypeError("Not a valid instance of Image.Image")
|
|
|
|
|
|
g1 = np.array([
|
|
[0, 1, 0],
|
|
[0, 0, 0],
|
|
[0, -1, 0]
|
|
])
|
|
|
|
g2 = np.array([
|
|
[1, 0, 0],
|
|
[0, 0, 0],
|
|
[0, 0, -1]
|
|
])
|
|
|
|
g3 = np.array([
|
|
[0, 0, 0],
|
|
[1, 0, -1],
|
|
[0, 0, 0]
|
|
])
|
|
|
|
g4 = np.array([
|
|
[0, 0, 1],
|
|
[0, 0, 0],
|
|
[-1, 0, 0]
|
|
])
|
|
|
|
identity = np.array([
|
|
[0, 0, 0],
|
|
[0, 1, 0],
|
|
[0, 0, 0]
|
|
])
|
|
|
|
laplace = np.array([
|
|
[0, 1, 0],
|
|
[1, -4, 1],
|
|
[0, 1, 0]
|
|
])
|
|
|
|
"""
|
|
url = "https://cdn.prod.www.spiegel.de/images/9f9be1b3-ac0e-49f9-acbd-a809a102f9b6_w960_r1.778_fpx39_fpy30.jpg"
|
|
response = requests.get(url)
|
|
|
|
if response.status_code == 200:
|
|
# image = Image.open(BytesIO(response.content))
|
|
image = Image.open("next_generation.jpg")
|
|
operators = [laplace]
|
|
edited_image = image
|
|
for operator in operators:
|
|
edited_image = apply_convolution_operator(operator, edited_image)
|
|
edited_image = edited_image.convert("RGB") # Convert to RGB mode
|
|
edited_image.show()
|
|
edited_image.save("edited.jpg")
|
|
else:
|
|
print(f"Failed to download image. Status code: {response.status_code}")
|
|
"""
|
|
|
|
|
|
class Simulation:
|
|
|