tcc/FlaskAPI/services/image.py

61 lines
1.9 KiB
Python
Raw Normal View History

2023-09-26 19:02:46 +00:00
from wand.image import Image, Color
2023-09-24 13:56:01 +00:00
def box_blur_image_separable(image, radius_x, radius_y):
width, height = image.width, image.height
2023-09-26 19:02:46 +00:00
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()
2023-09-24 13:56:01 +00:00
for y in range(height):
for x in range(width):
r_total, g_total, b_total = 0, 0, 0
2023-09-26 19:02:46 +00:00
2023-09-24 13:56:01 +00:00
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:
2023-09-26 19:02:46 +00:00
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):
2023-09-21 20:57:47 +00:00
with Image(blob=img) as image:
2023-09-28 01:28:52 +00:00
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):
2023-09-18 15:24:05 +00:00
with open("./static/small-image.png", "rb") as file:
return file.read()
def get_big_image(self):
2023-09-18 15:24:05 +00:00
with open("./static/big-image.png", "rb") as file:
return file.read()
def save_image(self, img):
2023-09-21 20:57:47 +00:00
with open("image.png", "wb") as file:
file.write(img)
2023-09-24 13:56:01 +00:00
return True