tcc/FlaskAPI/services/image.py

61 lines
1.9 KiB
Python

from wand.image import Image, Color
def box_blur_image_separable(image, radius_x, radius_y):
width, height = image.width, image.height
kernel_x_size = 2 * radius_x + 1
kernel_y_size = 2 * radius_y + 1
kernel_area = kernel_x_size * kernel_y_size
blurred_image = image.clone()
for y in range(height):
for x in range(width):
r_total, g_total, b_total = 0, 0, 0
for offset_y in range(-radius_y, radius_y + 1):
for offset_x in range(-radius_x, radius_x + 1):
new_x = x + offset_x
new_y = y + offset_y
if 0 <= new_x < width and 0 <= new_y < height:
pixel = image[new_x, new_y]
r_total += pixel.red_int8
g_total += pixel.green_int8
b_total += pixel.blue_int8
r_avg = int(r_total / kernel_area)
g_avg = int(g_total / kernel_area)
b_avg = int(b_total / kernel_area)
blurred_image[x, y] = Color(f'rgb({r_avg},{g_avg},{b_avg})')
return blurred_image
class ImageService:
def __init__(self):
pass
def box_blur_image(self, img, radius):
with Image(blob=img) as image:
image.gaussian_blur(radius, radius)
return image.make_blob()
# blurred_image = box_blur_image_separable(image, radius, 0)
# blurred_image = box_blur_image_separable(blurred_image, 0, radius)
# return blurred_image.make_blob()
def get_simple_image(self):
with open("./static/small-image.png", "rb") as file:
return file.read()
def get_big_image(self):
with open("./static/big-image.png", "rb") as file:
return file.read()
def save_image(self, img):
with open("image.png", "wb") as file:
file.write(img)
return True