Colored Emoji - Windows
Browse files- style_20250128.css +127 -0
- utils/hex_grid.py +414 -0
- utils/image_utils.py +578 -0
- utils/misc.py +69 -0
style_20250128.css
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.interface-wrapper {
|
2 |
+
max-width: 1024px;
|
3 |
+
margin: 0 auto;
|
4 |
+
}
|
5 |
+
|
6 |
+
.centered {
|
7 |
+
margin: 0 auto;
|
8 |
+
display: block;
|
9 |
+
}
|
10 |
+
|
11 |
+
.solid {
|
12 |
+
opacity: 1.0 !important;
|
13 |
+
height: auto !important;
|
14 |
+
}
|
15 |
+
|
16 |
+
.intro {
|
17 |
+
font-size: 1.2em !important;
|
18 |
+
font-weight: bold;
|
19 |
+
text-align: center;
|
20 |
+
background-color: rgba(242, 218, 163, 0.62);
|
21 |
+
}
|
22 |
+
|
23 |
+
.dark .gradio-container.gradio-container-5-12-0 .contain .intro {
|
24 |
+
background-color: rgba(41, 18, 5, 0.38) !important;
|
25 |
+
}
|
26 |
+
|
27 |
+
.small {
|
28 |
+
font-size: smaller !important;
|
29 |
+
text-align: center;
|
30 |
+
}
|
31 |
+
|
32 |
+
.imgcontainer img {
|
33 |
+
object-fit: contain !important;
|
34 |
+
}
|
35 |
+
|
36 |
+
#examples {
|
37 |
+
font-weight: bolder;
|
38 |
+
}
|
39 |
+
|
40 |
+
--background-fill-primary: #FBCE50 !important;
|
41 |
+
#col-container {
|
42 |
+
max-width: 1024px;
|
43 |
+
margin-left: auto;
|
44 |
+
margin-right: auto;
|
45 |
+
}
|
46 |
+
|
47 |
+
a {
|
48 |
+
text-decoration-line: underline;
|
49 |
+
font-weight: 600;
|
50 |
+
}
|
51 |
+
|
52 |
+
#btn-generate {
|
53 |
+
background-image: linear-gradient(to right bottom, rgb(157, 255, 157), rgb(229, 255, 235));
|
54 |
+
}
|
55 |
+
|
56 |
+
#btn-generate:hover {
|
57 |
+
background-image: linear-gradient(to right bottom, rgb(229, 255, 229), rgb(255, 255, 255));
|
58 |
+
}
|
59 |
+
|
60 |
+
#btn-generate:active {
|
61 |
+
background-image: linear-gradient(to right bottom, rgb(229, 255, 235), rgb(157, 255, 157));
|
62 |
+
}
|
63 |
+
|
64 |
+
#versions {
|
65 |
+
margin-top: 1em;
|
66 |
+
width: 100%;
|
67 |
+
text-align: center;
|
68 |
+
}
|
69 |
+
|
70 |
+
.small-btn {
|
71 |
+
max-width: 75px;
|
72 |
+
}
|
73 |
+
|
74 |
+
#gallery .thumbnails {
|
75 |
+
flex-direction: column !important;
|
76 |
+
display: inline-flex !important;
|
77 |
+
flex-wrap: wrap !important;
|
78 |
+
position: relative !important;
|
79 |
+
}
|
80 |
+
|
81 |
+
#gallery caption.caption {
|
82 |
+
flex-direction: row !important;
|
83 |
+
display: inline-flex !important;
|
84 |
+
flex-wrap: wrap;
|
85 |
+
white-space: unset !important;
|
86 |
+
}
|
87 |
+
|
88 |
+
#gallery .image-button img.with-caption {
|
89 |
+
object-fit: cover !important;
|
90 |
+
object-position: center !important;
|
91 |
+
}
|
92 |
+
|
93 |
+
#gallery button.preview {
|
94 |
+
position: relative !important;
|
95 |
+
}
|
96 |
+
|
97 |
+
.gradio-container::before {
|
98 |
+
content: ' ';
|
99 |
+
display: block;
|
100 |
+
position: absolute;
|
101 |
+
left: 0;
|
102 |
+
top: 0;
|
103 |
+
width: 100%;
|
104 |
+
height: 100%;
|
105 |
+
opacity: 0.25;
|
106 |
+
background-image: url('gradio_api/file=./images/logo.png');
|
107 |
+
background-repeat: no-repeat;
|
108 |
+
background-position: 50% 0;
|
109 |
+
background-size: cover;
|
110 |
+
background-color: rgba(0,0,0,0.9);
|
111 |
+
}
|
112 |
+
|
113 |
+
#component-0, #component-1 {
|
114 |
+
opacity: 0.9;
|
115 |
+
}
|
116 |
+
|
117 |
+
#excluded_colors {
|
118 |
+
width: 95%;
|
119 |
+
margin: 0 auto;
|
120 |
+
font-size: smaller;
|
121 |
+
}
|
122 |
+
|
123 |
+
@media only screen and (min-width: 1920px) {
|
124 |
+
.gradio-container, .gradio-container::before {
|
125 |
+
max-width: 1920px !important;
|
126 |
+
}
|
127 |
+
}
|
utils/hex_grid.py
ADDED
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# utils/hex_grid.py
|
2 |
+
import os
|
3 |
+
import math
|
4 |
+
from PIL import Image
|
5 |
+
import cairocffi as cairo
|
6 |
+
import pangocffi
|
7 |
+
import pangocairocffi
|
8 |
+
from PIL import Image, ImageDraw, ImageChops, ImageFont #, ImageColor
|
9 |
+
#from pilmoji import Pilmoji # Import Pilmoji for handling emojis
|
10 |
+
from utils.excluded_colors import (
|
11 |
+
excluded_color_list,
|
12 |
+
)
|
13 |
+
from utils.image_utils import multiply_and_blend_images
|
14 |
+
from utils.color_utils import update_color_opacity, parse_hex_color, draw_text_with_emojis, hex_to_rgb
|
15 |
+
import random # For random text options
|
16 |
+
import utils.constants as constants # Import constants
|
17 |
+
import ast
|
18 |
+
|
19 |
+
def calculate_font_size(hex_size, padding=0.6, size_ceil=20, min_font_size=8):
|
20 |
+
"""
|
21 |
+
Calculate the font size based on the hexagon size.
|
22 |
+
|
23 |
+
Parameters:
|
24 |
+
hex_size (int): The size of the hexagon side.
|
25 |
+
padding (float): The fraction of the hex size to use for font size.
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
int or None: The calculated font size or None if hex is too small.
|
29 |
+
"""
|
30 |
+
font_size = int(hex_size * padding)
|
31 |
+
if font_size < min_font_size:
|
32 |
+
return None # Hex is too small for text
|
33 |
+
return min(font_size, size_ceil)
|
34 |
+
|
35 |
+
def generate_hexagon_grid(hex_size, border_size, input_image=None, image_width=0, image_height=0, start_x=0, start_y=0, end_x=0, end_y=0, rotation=0, background_color="#ede9ac44", border_color="#12165380", fill_hex=True, excluded_color_list=excluded_color_list, filter_color=False, x_spacing=0, y_spacing=0):
|
36 |
+
if input_image:
|
37 |
+
image_width, image_height = input_image.size
|
38 |
+
# Use half hex_size, thus do not double border size
|
39 |
+
# Calculate the dimensions of the grid before rotation
|
40 |
+
if rotation != 0:
|
41 |
+
# Calculate rotated dimensions
|
42 |
+
# modified to rotate input image and process to reduce calculation errors at edge conditions
|
43 |
+
rotated_input_image = input_image.rotate(rotation, expand=True)
|
44 |
+
rotated_image_width, rotated_image_height = rotated_input_image.size
|
45 |
+
#rotated_image_height = abs(math.ceil((image_height ) * math.sin(math.radians(90 - rotation)) + (image_width ) * math.cos(math.radians(90 - rotation))))
|
46 |
+
#rotated_image_width = abs(math.ceil((image_width ) * math.sin(math.radians(90 - rotation)) + (image_height ) * math.cos(math.radians(90 - rotation))))
|
47 |
+
# Adjust hexagon size, spacing adjustments and border for rotation
|
48 |
+
hex_size = abs(math.ceil((hex_size // 2) * math.sin(math.radians(90 - abs(rotation))) + (hex_size // 2) * math.cos(math.radians(90 - abs(rotation)))))
|
49 |
+
hex_border_size = math.ceil(border_size * math.sin(math.radians(90 - abs(rotation))) + border_size * math.cos(math.radians(90 - abs(rotation))))
|
50 |
+
x_spacing = math.ceil(x_spacing * math.sin(math.radians(90 - abs(rotation))) + x_spacing * math.cos(math.radians(90 - abs(rotation))))
|
51 |
+
y_spacing = math.ceil(y_spacing * math.sin(math.radians(90 - abs(rotation))) + y_spacing * math.cos(math.radians(90 - abs(rotation))))
|
52 |
+
# Calculate additional width and height due to rotation
|
53 |
+
additional_width = rotated_image_width - image_width
|
54 |
+
additional_height = rotated_image_height - image_height
|
55 |
+
#rotated_input_image.show()
|
56 |
+
else:
|
57 |
+
rotated_input_image = input_image
|
58 |
+
rotated_image_width = image_width
|
59 |
+
rotated_image_height = image_height
|
60 |
+
hex_size = hex_size // 2
|
61 |
+
hex_border_size = border_size
|
62 |
+
additional_width = 0
|
63 |
+
additional_height = 0
|
64 |
+
# Create a new image with white background (adjusted for rotation)
|
65 |
+
image = Image.new("RGBA", (rotated_image_width, rotated_image_height), background_color)
|
66 |
+
draw = ImageDraw.Draw(image, mode="RGBA")
|
67 |
+
hex_width = hex_size * 2
|
68 |
+
hex_height = hex_size * 2
|
69 |
+
hex_horizontal_spacing = (hex_width ) + (hex_border_size if hex_border_size < 0 else 0) + x_spacing #* 0.8660254
|
70 |
+
hex_vertical_spacing = hex_height + (hex_border_size if hex_border_size < 0 else 0) + y_spacing
|
71 |
+
col = 0
|
72 |
+
row = 0
|
73 |
+
def draw_hexagon(x, y, color="#FFFFFFFF", rotation=0, outline_color="#12165380", outline_width=0, sides=6):
|
74 |
+
side_length = (hex_size * 2) / math.sqrt(3)
|
75 |
+
points = [(x + side_length * math.cos(math.radians(angle + rotation)), y + side_length * math.sin(math.radians(angle + rotation))) for angle in range(0, 360, (360 // sides))]
|
76 |
+
draw.polygon(points, fill=color, outline=outline_color, width=max(-5, outline_width))
|
77 |
+
# Function to range a floating number
|
78 |
+
def frange(start, stop, step):
|
79 |
+
i = start
|
80 |
+
while i < stop:
|
81 |
+
yield i
|
82 |
+
i += step
|
83 |
+
# Draw hexagons
|
84 |
+
for y in frange(start_y, max(image_height + additional_height, image_height, rotated_image_height) + (end_y - start_y), hex_vertical_spacing):
|
85 |
+
row += 1
|
86 |
+
col = 0
|
87 |
+
for x in frange(start_x, max(image_width + additional_width, image_width, rotated_image_width) + (end_x - start_x), hex_horizontal_spacing):
|
88 |
+
col += 1
|
89 |
+
x_offset = hex_width // 2
|
90 |
+
y_offset = (hex_height // 2) #* 1.15470054342517
|
91 |
+
# Adjust y_offset for columns 1 and 3 to overlap
|
92 |
+
if col % 2 == 1:
|
93 |
+
y_offset -= (hex_height // 2) #* 0.8660254
|
94 |
+
if rotated_input_image:
|
95 |
+
# Sample the colors of the pixels in the hexagon, if fill_hex is True
|
96 |
+
if fill_hex:
|
97 |
+
sample_size = max(2, math.ceil(math.sqrt(hex_size)))
|
98 |
+
sample_x = int(x + x_offset)
|
99 |
+
sample_y = int(y + y_offset)
|
100 |
+
sample_colors = []
|
101 |
+
for i in range(-sample_size // 2, sample_size // 2 + 1):
|
102 |
+
for j in range(-sample_size // 2, sample_size // 2 + 1):
|
103 |
+
print(f" Progress : {str(min(rotated_image_width - 1,max(1,sample_x + i)))} {str(min(rotated_image_height - 1,max(1,sample_y + j)))}", end="\r")
|
104 |
+
sample_colors.append(rotated_input_image.getpixel((min(rotated_image_width - 1,max(1,sample_x + i)), min(rotated_image_height - 1,max(1,sample_y + j)))))
|
105 |
+
if filter_color:
|
106 |
+
# Filter out the excluded colors
|
107 |
+
filtered_colors = [color for color in sample_colors if color not in excluded_color_list]
|
108 |
+
# Ensure there are colors left after filtering
|
109 |
+
if filtered_colors:
|
110 |
+
# Calculate the average color of the filtered colors
|
111 |
+
avg_color = tuple(int(sum(channel) / len(filtered_colors)) for channel in zip(*filtered_colors))
|
112 |
+
else:
|
113 |
+
avg_color = excluded_color_list[0] if excluded_color_list else (0,0,0,0)
|
114 |
+
else:
|
115 |
+
avg_color = tuple(int(sum(channel) / len(sample_colors)) for channel in zip(*sample_colors))
|
116 |
+
if avg_color in excluded_color_list:
|
117 |
+
print(f"color excluded: {avg_color}")
|
118 |
+
avg_color = (0,0,0,0)
|
119 |
+
else:
|
120 |
+
print(f"color found: {avg_color}")
|
121 |
+
#draw_hexagon(x + x_offset, y + y_offset, color="#{:02x}{:02x}{:02x}{:02x}".format(*avg_color if fill_hex else (0,0,0,0)), outline_color=border_color, outline_width=hex_border_size)
|
122 |
+
draw_hexagon(x + x_offset, y + y_offset, color="#{:02x}{:02x}{:02x}{:02x}".format(*avg_color), outline_color=border_color, outline_width=hex_border_size)
|
123 |
+
else:
|
124 |
+
draw_hexagon(x + x_offset, y + y_offset, color="#000000", outline_color=border_color, outline_width=hex_border_size)
|
125 |
+
else:
|
126 |
+
color = "#%02x%02x%02x%02x" % (128, math.ceil(y) % 255, math.ceil(x) % 255, 255) if fill_hex else (0,0,0,0)
|
127 |
+
draw_hexagon(x + x_offset, y + y_offset, color=color, outline_color=border_color, outline_width=hex_border_size)
|
128 |
+
if rotation != 0:
|
129 |
+
#image.show()
|
130 |
+
# Rotate the final image
|
131 |
+
rotated_image = image.rotate(-rotation, expand=True)
|
132 |
+
#rotated_image.show()
|
133 |
+
bbox = rotated_image.split()[3].getbbox(False)
|
134 |
+
if bbox:
|
135 |
+
final_image = rotated_image.crop(bbox).resize((image_width,image_height))
|
136 |
+
else:
|
137 |
+
final_image = rotated_image.resize((image_width,image_height))
|
138 |
+
else:
|
139 |
+
final_image = image
|
140 |
+
return final_image
|
141 |
+
|
142 |
+
def generate_hexagon_grid_with_text(hex_size, border_size, input_image=None, image_width=0, image_height=0, start_x=0, start_y=0, end_x=0, end_y=0, rotation=0, background_color="#ede9ac44", border_color="#12165380", fill_hex=True, excluded_color_list=excluded_color_list, filter_color=False, x_spacing=0, y_spacing=0,
|
143 |
+
add_hex_text_option=None, custom_text_list=None, custom_text_color_list=None):
|
144 |
+
|
145 |
+
if input_image:
|
146 |
+
image_width, image_height = input_image.size
|
147 |
+
# Use half hex_size, thus do not double border size
|
148 |
+
# Calculate the dimensions of the grid before rotation
|
149 |
+
if rotation != 0:
|
150 |
+
# Calculate rotated dimensions
|
151 |
+
# modified to rotate input image and process to reduce calculation errors at edge conditions
|
152 |
+
rotated_input_image = input_image.rotate(rotation, expand=True)
|
153 |
+
rotated_image_width, rotated_image_height = rotated_input_image.size
|
154 |
+
#rotated_image_height = abs(math.ceil((image_height ) * math.sin(math.radians(90 - rotation)) + (image_width ) * math.cos(math.radians(90 - rotation))))
|
155 |
+
#rotated_image_width = abs(math.ceil((image_width ) * math.sin(math.radians(90 - rotation)) + (image_height ) * math.cos(math.radians(90 - rotation))))
|
156 |
+
# Adjust hexagon size, spacing adjustments and border for rotation
|
157 |
+
hex_size = abs(math.ceil((hex_size // 2) * math.sin(math.radians(90 - abs(rotation))) + (hex_size // 2) * math.cos(math.radians(90 - abs(rotation)))))
|
158 |
+
hex_border_size = math.ceil(border_size * math.sin(math.radians(90 - abs(rotation))) + border_size * math.cos(math.radians(90 - abs(rotation))))
|
159 |
+
x_spacing = math.ceil(x_spacing * math.sin(math.radians(90 - abs(rotation))) + x_spacing * math.cos(math.radians(90 - abs(rotation))))
|
160 |
+
y_spacing = math.ceil(y_spacing * math.sin(math.radians(90 - abs(rotation))) + y_spacing * math.cos(math.radians(90 - abs(rotation))))
|
161 |
+
# Calculate additional width and height due to rotation
|
162 |
+
additional_width = rotated_image_width - image_width
|
163 |
+
additional_height = rotated_image_height - image_height
|
164 |
+
#rotated_input_image.show()
|
165 |
+
else:
|
166 |
+
rotated_input_image = input_image
|
167 |
+
rotated_image_width = image_width
|
168 |
+
rotated_image_height = image_height
|
169 |
+
hex_size = hex_size // 2
|
170 |
+
hex_border_size = border_size
|
171 |
+
additional_width = 0
|
172 |
+
additional_height = 0
|
173 |
+
# Create a new image with white background (adjusted for rotation)
|
174 |
+
image = Image.new("RGBA", (rotated_image_width, rotated_image_height), background_color)
|
175 |
+
font_image = Image.new("RGBA", (rotated_image_width, rotated_image_height), (0,0,0,0))
|
176 |
+
draw = ImageDraw.Draw(image, mode="RGBA")
|
177 |
+
hex_width = hex_size * 2
|
178 |
+
hex_height = hex_size * 2
|
179 |
+
hex_horizontal_spacing = (hex_width ) + (hex_border_size if hex_border_size < 0 else 0) + x_spacing #* 0.8660254
|
180 |
+
hex_vertical_spacing = hex_height + (hex_border_size if hex_border_size < 0 else 0) + y_spacing
|
181 |
+
col = 0
|
182 |
+
row = 0
|
183 |
+
## Function to draw optional text
|
184 |
+
if add_hex_text_option != "None":
|
185 |
+
# Load the emoji font
|
186 |
+
font_name = "Segoe UI Emoji"
|
187 |
+
if os.name == 'nt': # Windows
|
188 |
+
font_path = "./fonts/seguiemj.ttf"
|
189 |
+
else: # Other OS (Linux, macOS, etc.)
|
190 |
+
font_path = "./fonts/seguiemj.ttf"
|
191 |
+
if not os.path.exists(font_path):
|
192 |
+
raise FileNotFoundError("Emoji font not found in './fonts' directory.")
|
193 |
+
# Prepare the text and color lists
|
194 |
+
text_list = []
|
195 |
+
color_list = []
|
196 |
+
if add_hex_text_option == "Row-Column Coordinates":
|
197 |
+
pass # Coordinates will be generated dynamically
|
198 |
+
elif add_hex_text_option == "Playing Cards Sequential":
|
199 |
+
text_list = constants.cards
|
200 |
+
color_list = constants.card_colors
|
201 |
+
elif add_hex_text_option == "Playing Cards Alternate Red and Black":
|
202 |
+
text_list = constants.cards_alternating
|
203 |
+
color_list = constants.card_colors_alternating
|
204 |
+
elif add_hex_text_option == "Custom List":
|
205 |
+
if custom_text_list:
|
206 |
+
#text_list = [text.strip() for text in custom_text_list.split(",")]
|
207 |
+
text_list = ast.literal_eval(custom_text_list) if custom_text_list else None
|
208 |
+
if custom_text_color_list:
|
209 |
+
#color_list = [color.strip() for color in custom_text_color_list.split(",")]
|
210 |
+
color_list = ast.literal_eval(custom_text_color_list) if custom_text_color_list else None
|
211 |
+
else:
|
212 |
+
text_list = []
|
213 |
+
color_list = []
|
214 |
+
hex_index = -1 # Initialize hex index
|
215 |
+
def draw_hexagon(x, y, color="#FFFFFFFF", rotation=0, outline_color="#12165380", outline_width=0, sides=6):
|
216 |
+
side_length = (hex_size * 2) / math.sqrt(3)
|
217 |
+
points = [(x + side_length * math.cos(math.radians(angle + rotation)), y + side_length * math.sin(math.radians(angle + rotation))) for angle in range(0, 360, (360 // sides))]
|
218 |
+
draw.polygon(points, fill=color, outline=outline_color, width=max(-5, outline_width))
|
219 |
+
# Function to range a floating number
|
220 |
+
def frange(start, stop, step):
|
221 |
+
i = start
|
222 |
+
while i < stop:
|
223 |
+
yield i
|
224 |
+
i += step
|
225 |
+
# Draw hexagons
|
226 |
+
for y in frange(start_y, max(image_height + additional_height, image_height, rotated_image_height) + (end_y - start_y), hex_vertical_spacing):
|
227 |
+
row += 1
|
228 |
+
col = 0
|
229 |
+
for x in frange(start_x, max(image_width + additional_width, image_width, rotated_image_width) + (end_x - start_x), hex_horizontal_spacing):
|
230 |
+
col += 1
|
231 |
+
hex_index += 1 # Increment hex index
|
232 |
+
x_offset = hex_width // 2
|
233 |
+
y_offset = (hex_height // 2) #* 1.15470054342517
|
234 |
+
# Adjust y_offset for columns 1 and 3 to overlap
|
235 |
+
if col % 2 == 1:
|
236 |
+
y_offset -= (hex_height // 2) #* 0.8660254
|
237 |
+
if rotated_input_image:
|
238 |
+
# Sample the colors of the pixels in the hexagon, if fill_hex is True
|
239 |
+
if fill_hex:
|
240 |
+
sample_size = max(2, math.ceil(math.sqrt(hex_size)))
|
241 |
+
sample_x = int(x + x_offset)
|
242 |
+
sample_y = int(y + y_offset)
|
243 |
+
sample_colors = []
|
244 |
+
for i in range(-sample_size // 2, sample_size // 2 + 1):
|
245 |
+
for j in range(-sample_size // 2, sample_size // 2 + 1):
|
246 |
+
print(f" Progress : {str(min(rotated_image_width - 1,max(1,sample_x + i)))} {str(min(rotated_image_height - 1,max(1,sample_y + j)))}", end="\r")
|
247 |
+
sample_colors.append(rotated_input_image.getpixel((min(rotated_image_width - 1,max(1,sample_x + i)), min(rotated_image_height - 1,max(1,sample_y + j)))))
|
248 |
+
if filter_color:
|
249 |
+
# Filter out the excluded colors
|
250 |
+
filtered_colors = [color for color in sample_colors if color not in excluded_color_list]
|
251 |
+
# Ensure there are colors left after filtering
|
252 |
+
if filtered_colors:
|
253 |
+
# Calculate the average color of the filtered colors
|
254 |
+
avg_color = tuple(int(sum(channel) / len(filtered_colors)) for channel in zip(*filtered_colors))
|
255 |
+
else:
|
256 |
+
avg_color = excluded_color_list[0] if excluded_color_list else (0,0,0,0)
|
257 |
+
else:
|
258 |
+
avg_color = tuple(int(sum(channel) / len(sample_colors)) for channel in zip(*sample_colors))
|
259 |
+
if avg_color in excluded_color_list:
|
260 |
+
print(f"color excluded: {avg_color}")
|
261 |
+
avg_color = (0,0,0,0)
|
262 |
+
else:
|
263 |
+
print(f"color found: {avg_color}")
|
264 |
+
#draw_hexagon(x + x_offset, y + y_offset, color="#{:02x}{:02x}{:02x}{:02x}".format(*avg_color if fill_hex else (0,0,0,0)), outline_color=border_color, outline_width=hex_border_size)
|
265 |
+
draw_hexagon(x + x_offset, y + y_offset, color="#{:02x}{:02x}{:02x}{:02x}".format(*avg_color), outline_color=border_color, outline_width=hex_border_size)
|
266 |
+
else:
|
267 |
+
draw_hexagon(x + x_offset, y + y_offset, color="#00000000", outline_color=border_color, outline_width=hex_border_size)
|
268 |
+
else:
|
269 |
+
color = "#%02x%02x%02x%02x" % (128, math.ceil(y) % 255, math.ceil(x) % 255, 255) if fill_hex else (0,0,0,0)
|
270 |
+
draw_hexagon(x + x_offset, y + y_offset, color=color, outline_color=border_color, outline_width=hex_border_size)
|
271 |
+
# Draw text in hexagon
|
272 |
+
if add_hex_text_option != None:
|
273 |
+
font_size = calculate_font_size(hex_size, 0.333, 20, 7)
|
274 |
+
# Skip drawing text if font size is too small
|
275 |
+
if font_size:
|
276 |
+
font = ImageFont.truetype(font_path, font_size)
|
277 |
+
# Determine the text to draw
|
278 |
+
if add_hex_text_option == "Row-Column Coordinates":
|
279 |
+
text = f"{col},{row}"
|
280 |
+
elif text_list:
|
281 |
+
text = text_list[hex_index % len(text_list)]
|
282 |
+
else:
|
283 |
+
text = ""
|
284 |
+
# Determine the text color
|
285 |
+
if color_list:
|
286 |
+
# Extract the opacity from the border color and add to the color_list
|
287 |
+
if isinstance(border_color, str):
|
288 |
+
opacity = int(border_color[-2:], 16)
|
289 |
+
elif isinstance(border_color, tuple) and len(border_color) == 4:
|
290 |
+
opacity = border_color[3]
|
291 |
+
else:
|
292 |
+
opacity = 255 # Default to full opacity if format is unexpected
|
293 |
+
text_color = update_color_opacity(hex_to_rgb(color_list[hex_index % len(color_list)]), opacity)
|
294 |
+
else:
|
295 |
+
# Use border color and opacity
|
296 |
+
text_color = border_color
|
297 |
+
#text_color = "#{:02x}{:02x}{:02x}{:02x}".format(*text_color)
|
298 |
+
# Skip if text is empty
|
299 |
+
if text != "":
|
300 |
+
print(f"Drawing Text: {text} color: {text_color} size: {font_size}")
|
301 |
+
# Calculate text size using Pango
|
302 |
+
# Create a temporary surface to calculate text size
|
303 |
+
# temp_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)
|
304 |
+
# temp_context = cairo.Context(temp_surface)
|
305 |
+
# temp_layout = pangocairocffi.create_layout(temp_context)
|
306 |
+
# temp_layout._set_text(text)
|
307 |
+
# temp_desc = pangocffi.FontDescription()
|
308 |
+
# temp_desc._set_family(font_name)
|
309 |
+
# temp_desc._set_size(pangocffi.units_from_double(font_size))
|
310 |
+
# temp_layout._set_font_description(temp_desc)
|
311 |
+
# pangocairocffi.show_layout(temp_context, temp_layout)
|
312 |
+
# ink_rect, logical_rect = temp_layout.get_extents()
|
313 |
+
# text_width = logical_rect.width
|
314 |
+
# text_height = logical_rect.height
|
315 |
+
# Calculate position to center text in hexagon
|
316 |
+
# text_x = x + x_offset - (text_width / 2)
|
317 |
+
# text_y = y + y_offset - (text_height / 2)
|
318 |
+
# Calculate position to center text in hexagon
|
319 |
+
text_x = x + x_offset - (hex_size / 1.75)
|
320 |
+
text_y = y + y_offset - (hex_size / 1.25)
|
321 |
+
# Draw the text directly onto the image
|
322 |
+
font_image = draw_text_with_emojis(
|
323 |
+
image=font_image,
|
324 |
+
text=text,
|
325 |
+
font_color=update_color_opacity(text_color,255),
|
326 |
+
offset_x=text_x,
|
327 |
+
offset_y=text_y,
|
328 |
+
font_name=font_name,
|
329 |
+
font_size=font_size
|
330 |
+
)
|
331 |
+
# # Use Pilmoji to draw text with emojis
|
332 |
+
# with Pilmoji(image) as pilmoji:
|
333 |
+
# # Calculate text size
|
334 |
+
# w, h = pilmoji.getsize(text, font=font)
|
335 |
+
# # Calculate position to center text in hexagon
|
336 |
+
# text_x = x + x_offset - w / 2
|
337 |
+
# text_y = y + y_offset - h / 2
|
338 |
+
# # Draw text
|
339 |
+
# pilmoji.text(
|
340 |
+
# (text_x, text_y),
|
341 |
+
# text,
|
342 |
+
# font=font,
|
343 |
+
# fill=text_color
|
344 |
+
# )
|
345 |
+
image.paste(font_image, (0, 0), font_image)
|
346 |
+
if rotation != 0:
|
347 |
+
# Rotate the final image
|
348 |
+
rotated_image = image.rotate(-rotation, expand=True, fillcolor=background_color)
|
349 |
+
bbox = rotated_image.split()[3].getbbox(alpha_only=False)
|
350 |
+
|
351 |
+
if bbox:
|
352 |
+
# Calculate the size of the rotated image
|
353 |
+
rotated_width, rotated_height = rotated_image.size
|
354 |
+
|
355 |
+
# Calculate the size of the cropped area
|
356 |
+
box_width = bbox[2] - bbox[0]
|
357 |
+
box_height = bbox[3] - bbox[1]
|
358 |
+
|
359 |
+
box_width_adjust = (box_width - image_width) / 2
|
360 |
+
bbox_height_adjust = (box_height - image_height) / 2
|
361 |
+
|
362 |
+
print(f"\nbbox: {bbox}: size: {(image_width, image_height)} estimated size: {(box_width, box_height)}")
|
363 |
+
|
364 |
+
# Calculate adjusted box coordinates
|
365 |
+
left = bbox[0] + box_width_adjust
|
366 |
+
upper = bbox[1] + bbox_height_adjust
|
367 |
+
right = bbox[2] - box_width_adjust
|
368 |
+
lower = bbox[3] - bbox_height_adjust
|
369 |
+
|
370 |
+
# Ensure coordinates are within image bounds
|
371 |
+
left = max(0, min(left, rotated_width))
|
372 |
+
upper = max(0, min(upper, rotated_height))
|
373 |
+
right = max(0, min(right, rotated_width))
|
374 |
+
lower = max(0, min(lower, rotated_height))
|
375 |
+
|
376 |
+
# Ensure the box has positive width and height
|
377 |
+
if right > left and lower > upper:
|
378 |
+
# Crop the image using the adjusted box
|
379 |
+
cropped_image = rotated_image.crop((left, upper, right, lower))
|
380 |
+
# Resize the cropped image to the desired size
|
381 |
+
final_image = cropped_image.resize((image_width, image_height))
|
382 |
+
else:
|
383 |
+
# If the box is invalid, resize the entire rotated image
|
384 |
+
final_image = rotated_image.resize((image_width, image_height))
|
385 |
+
else:
|
386 |
+
final_image = rotated_image.resize((image_width, image_height))
|
387 |
+
else:
|
388 |
+
final_image = image
|
389 |
+
return final_image
|
390 |
+
|
391 |
+
def generate_hexagon_grid_interface(hex_size, border_size, image, start_x, start_y, end_x, end_y, rotation, background_color, border_color, fill_hex, excluded_color_list, filter_color, x_spacing, y_spacing, add_hex_text_option=None, custom_text_list=None, custom_text_color_list=None):
|
392 |
+
print(f"Generating Hexagon Grid with Parameters: Hex Size: {hex_size}, Border Size: {border_size}, Start X: {start_x}, Start Y: {start_y}, End X: {end_x}, End Y: {end_y}, Rotation: {rotation}, Background Color: {background_color}, Border Color: {border_color}, Fill Hex: {fill_hex}, Excluded Color List: {excluded_color_list}, Filter Color: {filter_color}, X Spacing: {x_spacing}, Y Spacing: {y_spacing}, add Text Option {add_hex_text_option}\n")
|
393 |
+
hexagon_grid_image = generate_hexagon_grid_with_text(
|
394 |
+
hex_size=abs(hex_size),
|
395 |
+
border_size=border_size,
|
396 |
+
input_image=image,
|
397 |
+
start_x=start_x,
|
398 |
+
start_y=start_y,
|
399 |
+
end_x=end_x,
|
400 |
+
end_y=end_y,
|
401 |
+
rotation=rotation,
|
402 |
+
background_color=background_color,
|
403 |
+
border_color=border_color,
|
404 |
+
fill_hex = fill_hex,
|
405 |
+
excluded_color_list = excluded_color_list,
|
406 |
+
filter_color = filter_color,
|
407 |
+
x_spacing = x_spacing if abs(hex_size) > abs(x_spacing) else (hex_size if x_spacing >= 0 else -hex_size),
|
408 |
+
y_spacing = y_spacing if abs(hex_size) > abs(y_spacing) else (hex_size if y_spacing >= 0 else -hex_size),
|
409 |
+
add_hex_text_option = add_hex_text_option,
|
410 |
+
custom_text_list = custom_text_list,
|
411 |
+
custom_text_color_list= custom_text_color_list
|
412 |
+
)
|
413 |
+
overlay_image = multiply_and_blend_images(image, hexagon_grid_image, 50)
|
414 |
+
return hexagon_grid_image, overlay_image
|
utils/image_utils.py
ADDED
@@ -0,0 +1,578 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# utils/image_utils.py
|
2 |
+
import os
|
3 |
+
from io import BytesIO
|
4 |
+
import base64
|
5 |
+
import numpy as np
|
6 |
+
#from decimal import ROUND_CEILING
|
7 |
+
from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFilter, ImageDraw, ImageOps, ImageMath
|
8 |
+
from typing import List, Union
|
9 |
+
#import numpy as np
|
10 |
+
#import math
|
11 |
+
from utils.constants import default_lut_example_img
|
12 |
+
from utils.color_utils import (
|
13 |
+
detect_color_format,
|
14 |
+
update_color_opacity
|
15 |
+
)
|
16 |
+
from utils.misc import (pause)
|
17 |
+
|
18 |
+
def open_image(image_path):
|
19 |
+
"""
|
20 |
+
Opens an image from a file path or URL, or decodes a DataURL string into an image.
|
21 |
+
|
22 |
+
Parameters:
|
23 |
+
image_path (str): The file path, URL, or DataURL string of the image to open.
|
24 |
+
|
25 |
+
Returns:
|
26 |
+
Image: A PIL Image object of the opened image.
|
27 |
+
|
28 |
+
Raises:
|
29 |
+
Exception: If there is an error opening the image.
|
30 |
+
"""
|
31 |
+
import requests
|
32 |
+
try:
|
33 |
+
# Strip leading and trailing double quotation marks, if present
|
34 |
+
image_path = image_path.strip('"')
|
35 |
+
if image_path.startswith('http'):
|
36 |
+
# If the image path is a URL, download the image using requests
|
37 |
+
response = requests.get(image_path)
|
38 |
+
img = Image.open(BytesIO(response.content))
|
39 |
+
elif image_path.startswith('data'):
|
40 |
+
# If the image path is a DataURL, decode the base64 string
|
41 |
+
encoded_data = image_path.split(',')[1]
|
42 |
+
decoded_data = base64.b64decode(encoded_data)
|
43 |
+
img = Image.open(BytesIO(decoded_data))
|
44 |
+
else:
|
45 |
+
# Assume that the image path is a file path
|
46 |
+
img = Image.open(image_path)
|
47 |
+
except Exception as e:
|
48 |
+
raise Exception(f'Error opening image: {e}')
|
49 |
+
return img
|
50 |
+
|
51 |
+
def build_prerendered_images(images_list):
|
52 |
+
"""
|
53 |
+
Opens a list of images from file paths, URLs, or DataURL strings.
|
54 |
+
|
55 |
+
Parameters:
|
56 |
+
images_list (list): A list of file paths, URLs, or DataURL strings of the images to open.
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
list: A list of PIL Image objects of the opened images.
|
60 |
+
"""
|
61 |
+
return [open_image(image) for image in images_list]
|
62 |
+
|
63 |
+
def build_encoded_images(images_list):
|
64 |
+
"""
|
65 |
+
Encodes a list of images to base64 strings.
|
66 |
+
|
67 |
+
Parameters:
|
68 |
+
images_list (list): A list of file paths, URLs, DataURL strings, or PIL Image objects of the images to encode.
|
69 |
+
|
70 |
+
Returns:
|
71 |
+
list: A list of base64-encoded strings of the images.
|
72 |
+
"""
|
73 |
+
return [image_to_base64(image) for image in images_list]
|
74 |
+
|
75 |
+
def image_to_base64(image):
|
76 |
+
"""
|
77 |
+
Encodes an image to a base64 string.
|
78 |
+
|
79 |
+
Parameters:
|
80 |
+
image (str or PIL.Image.Image): The file path, URL, DataURL string, or PIL Image object of the image to encode.
|
81 |
+
|
82 |
+
Returns:
|
83 |
+
str: A base64-encoded string of the image.
|
84 |
+
"""
|
85 |
+
buffered = BytesIO()
|
86 |
+
if type(image) is str:
|
87 |
+
image = open_image(image)
|
88 |
+
image.save(buffered, format="PNG")
|
89 |
+
return "data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode()
|
90 |
+
|
91 |
+
def change_color(image, color, opacity=0.75):
|
92 |
+
"""
|
93 |
+
Changes the color of an image by overlaying it with a specified color and opacity.
|
94 |
+
|
95 |
+
Parameters:
|
96 |
+
image (str or PIL.Image.Image): The file path, URL, DataURL string, or PIL Image object of the image to change.
|
97 |
+
color (str or tuple): The color to overlay on the image.
|
98 |
+
opacity (float): The opacity of the overlay color (0.0 to 1.0).
|
99 |
+
|
100 |
+
Returns:
|
101 |
+
PIL.Image.Image: The image with the color changed.
|
102 |
+
"""
|
103 |
+
if type(image) is str:
|
104 |
+
image = open_image(image)
|
105 |
+
try:
|
106 |
+
# Convert the color to RGBA format
|
107 |
+
rgba_color = detect_color_format(color)
|
108 |
+
rgba_color = update_color_opacity(rgba_color, opacity)
|
109 |
+
|
110 |
+
# Convert the image to RGBA mode
|
111 |
+
image = image.convert("RGBA")
|
112 |
+
|
113 |
+
# Create a new image with the same size and mode
|
114 |
+
new_image = Image.new("RGBA", image.size, rgba_color)
|
115 |
+
|
116 |
+
# Composite the new image with the original image
|
117 |
+
result = Image.alpha_composite(image, new_image)
|
118 |
+
except Exception as e:
|
119 |
+
print(f"Error changing color: {e}")
|
120 |
+
return image
|
121 |
+
return result
|
122 |
+
|
123 |
+
def convert_str_to_int_or_zero(value):
|
124 |
+
"""
|
125 |
+
Converts a string to an integer, or returns zero if the conversion fails.
|
126 |
+
|
127 |
+
Parameters:
|
128 |
+
value (str): The string to convert.
|
129 |
+
|
130 |
+
Returns:
|
131 |
+
int: The converted integer, or zero if the conversion fails.
|
132 |
+
"""
|
133 |
+
try:
|
134 |
+
return int(value)
|
135 |
+
except ValueError:
|
136 |
+
return 0
|
137 |
+
|
138 |
+
def upscale_image(image, scale_factor):
|
139 |
+
"""
|
140 |
+
Upscales an image by a given scale factor using the LANCZOS filter.
|
141 |
+
|
142 |
+
Parameters:
|
143 |
+
image (PIL.Image.Image): The input image to be upscaled.
|
144 |
+
scale_factor (float): The factor by which to upscale the image.
|
145 |
+
|
146 |
+
Returns:
|
147 |
+
PIL.Image.Image: The upscaled image.
|
148 |
+
"""
|
149 |
+
# Calculate the new size
|
150 |
+
new_width = int(image.width * scale_factor)
|
151 |
+
new_height = int(image.height * scale_factor)
|
152 |
+
|
153 |
+
# Upscale the image using the LANCZOS filter
|
154 |
+
upscaled_image = image.resize((new_width, new_height), Image.LANCZOS)
|
155 |
+
|
156 |
+
return upscaled_image
|
157 |
+
|
158 |
+
def crop_and_resize_image(image, width, height):
|
159 |
+
"""
|
160 |
+
Crops the image to a centered square and resizes it to the specified width and height.
|
161 |
+
|
162 |
+
Parameters:
|
163 |
+
image (PIL.Image.Image): The input image to be cropped and resized.
|
164 |
+
width (int): The desired width of the output image.
|
165 |
+
height (int): The desired height of the output image.
|
166 |
+
|
167 |
+
Returns:
|
168 |
+
PIL.Image.Image: The cropped and resized image.
|
169 |
+
"""
|
170 |
+
# Get original dimensions
|
171 |
+
original_width, original_height = image.size
|
172 |
+
|
173 |
+
# Determine the smaller dimension to make a square crop
|
174 |
+
min_dim = min(original_width, original_height)
|
175 |
+
|
176 |
+
# Calculate coordinates for cropping to a centered square
|
177 |
+
left = (original_width - min_dim) // 2
|
178 |
+
top = (original_height - min_dim) // 2
|
179 |
+
right = left + min_dim
|
180 |
+
bottom = top + min_dim
|
181 |
+
|
182 |
+
# Crop the image
|
183 |
+
cropped_image = image.crop((left, top, right, bottom))
|
184 |
+
|
185 |
+
# Resize the image to the desired dimensions
|
186 |
+
resized_image = cropped_image.resize((width, height), Image.LANCZOS)
|
187 |
+
|
188 |
+
return resized_image
|
189 |
+
|
190 |
+
def resize_image_with_aspect_ratio(image, target_width, target_height):
|
191 |
+
"""
|
192 |
+
Resizes the image to fit within the target dimensions while maintaining aspect ratio.
|
193 |
+
If the aspect ratio does not match, the image will be padded with black pixels.
|
194 |
+
|
195 |
+
Parameters:
|
196 |
+
image (PIL.Image.Image): The input image to be resized.
|
197 |
+
target_width (int): The target width.
|
198 |
+
target_height (int): The target height.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
PIL.Image.Image: The resized image.
|
202 |
+
"""
|
203 |
+
# Calculate aspect ratios
|
204 |
+
original_width, original_height = image.size
|
205 |
+
target_aspect = target_width / target_height
|
206 |
+
original_aspect = original_width / original_height
|
207 |
+
|
208 |
+
# Decide whether to fit width or height
|
209 |
+
if original_aspect > target_aspect:
|
210 |
+
# Image is wider than target aspect ratio
|
211 |
+
new_width = target_width
|
212 |
+
new_height = int(target_width / original_aspect)
|
213 |
+
else:
|
214 |
+
# Image is taller than target aspect ratio
|
215 |
+
new_height = target_height
|
216 |
+
new_width = int(target_height * original_aspect)
|
217 |
+
|
218 |
+
# Resize the image
|
219 |
+
resized_image = image.resize((new_width, new_height), Image.LANCZOS)
|
220 |
+
|
221 |
+
# Create a new image with target dimensions and black background
|
222 |
+
new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
|
223 |
+
# Paste the resized image onto the center of the new image
|
224 |
+
paste_x = (target_width - new_width) // 2
|
225 |
+
paste_y = (target_height - new_height) // 2
|
226 |
+
new_image.paste(resized_image, (paste_x, paste_y))
|
227 |
+
|
228 |
+
return new_image
|
229 |
+
|
230 |
+
def lerp_imagemath(img1, img2, alpha_percent: int = 50):
|
231 |
+
"""
|
232 |
+
Performs linear interpolation (LERP) between two images based on the given alpha value.
|
233 |
+
|
234 |
+
Parameters:
|
235 |
+
img1 (str or PIL.Image.Image): The first image or its file path.
|
236 |
+
img2 (str or PIL.Image.Image): The second image or its file path.
|
237 |
+
alpha (int): The interpolation factor (0 to 100).
|
238 |
+
|
239 |
+
Returns:
|
240 |
+
PIL.Image.Image: The interpolated image.
|
241 |
+
"""
|
242 |
+
if isinstance(img1, str):
|
243 |
+
img1 = open_image(img1)
|
244 |
+
if isinstance(img2, str):
|
245 |
+
img2 = open_image(img2)
|
246 |
+
|
247 |
+
# Ensure both images are in the same mode (e.g., RGBA)
|
248 |
+
img1 = img1.convert('RGBA')
|
249 |
+
img2 = img2.convert('RGBA')
|
250 |
+
|
251 |
+
# Convert images to NumPy arrays
|
252 |
+
arr1 = np.array(img1, dtype=np.float32)
|
253 |
+
arr2 = np.array(img2, dtype=np.float32)
|
254 |
+
|
255 |
+
# Perform linear interpolation
|
256 |
+
alpha = alpha_percent / 100.0
|
257 |
+
result_arr = (arr1 * (1 - alpha)) + (arr2 * alpha)
|
258 |
+
|
259 |
+
# Convert the result back to a PIL image
|
260 |
+
result_img = Image.fromarray(np.uint8(result_arr))
|
261 |
+
|
262 |
+
#result_img.show()
|
263 |
+
return result_img
|
264 |
+
|
265 |
+
def shrink_and_paste_on_blank(current_image, mask_width, mask_height, blank_color:tuple[int, int, int, int] = (0,0,0,0)):
|
266 |
+
"""
|
267 |
+
Decreases size of current_image by mask_width pixels from each side,
|
268 |
+
then adds a mask_width width transparent frame,
|
269 |
+
so that the image the function returns is the same size as the input.
|
270 |
+
|
271 |
+
Parameters:
|
272 |
+
current_image (PIL.Image.Image): The input image to transform.
|
273 |
+
mask_width (int): Width in pixels to shrink from each side.
|
274 |
+
mask_height (int): Height in pixels to shrink from each side.
|
275 |
+
blank_color (tuple): The color of the blank frame (default is transparent).
|
276 |
+
|
277 |
+
Returns:
|
278 |
+
PIL.Image.Image: The transformed image.
|
279 |
+
"""
|
280 |
+
# calculate new dimensions
|
281 |
+
width, height = current_image.size
|
282 |
+
new_width = width - (2 * mask_width)
|
283 |
+
new_height = height - (2 * mask_height)
|
284 |
+
|
285 |
+
# resize and paste onto blank image
|
286 |
+
prev_image = current_image.resize((new_width, new_height))
|
287 |
+
blank_image = Image.new("RGBA", (width, height), blank_color)
|
288 |
+
blank_image.paste(prev_image, (mask_width, mask_height))
|
289 |
+
|
290 |
+
return blank_image
|
291 |
+
|
292 |
+
def multiply_and_blend_images(base_image, image2, alpha_percent=50):
|
293 |
+
"""
|
294 |
+
Multiplies two images and blends the result with the original image.
|
295 |
+
|
296 |
+
Parameters:
|
297 |
+
image1 (PIL.Image.Image): The first input image.
|
298 |
+
image2 (PIL.Image.Image): The second input image.
|
299 |
+
alpha (float): The blend factor (0.0 to 100.0) for blending the multiplied result with the original image.
|
300 |
+
|
301 |
+
Returns:
|
302 |
+
PIL.Image.Image: The blended image.
|
303 |
+
"""
|
304 |
+
alpha = alpha_percent / 100.0
|
305 |
+
if isinstance(base_image, str):
|
306 |
+
base_image = open_image(base_image)
|
307 |
+
if isinstance(image2, str):
|
308 |
+
image2 = open_image(image2)
|
309 |
+
# Ensure both images are in the same mode and size
|
310 |
+
base_image = base_image.convert('RGBA')
|
311 |
+
image2 = image2.convert('RGBA')
|
312 |
+
image2 = image2.resize(base_image.size)
|
313 |
+
|
314 |
+
# Multiply the images
|
315 |
+
multiplied_image = ImageChops.multiply(base_image, image2)
|
316 |
+
|
317 |
+
# Blend the multiplied result with the original
|
318 |
+
blended_image = Image.blend(base_image, multiplied_image, alpha)
|
319 |
+
|
320 |
+
return blended_image
|
321 |
+
|
322 |
+
def alpha_composite_with_control(base_image, image_with_alpha, alpha_percent=100):
|
323 |
+
"""
|
324 |
+
Overlays image_with_alpha onto base_image with controlled alpha transparency.
|
325 |
+
|
326 |
+
Parameters:
|
327 |
+
base_image (PIL.Image.Image): The base image.
|
328 |
+
image_with_alpha (PIL.Image.Image): The image to overlay with an alpha channel.
|
329 |
+
alpha_percent (float): The multiplier for the alpha channel (0.0 to 100.0).
|
330 |
+
|
331 |
+
Returns:
|
332 |
+
PIL.Image.Image: The resulting image after alpha compositing.
|
333 |
+
"""
|
334 |
+
alpha_multiplier = alpha_percent / 100.0
|
335 |
+
if isinstance(base_image, str):
|
336 |
+
base_image = open_image(base_image)
|
337 |
+
if isinstance(image_with_alpha, str):
|
338 |
+
image_with_alpha = open_image(image_with_alpha)
|
339 |
+
|
340 |
+
# Ensure both images are in RGBA mode
|
341 |
+
base_image = base_image.convert('RGBA')
|
342 |
+
image_with_alpha = image_with_alpha.convert('RGBA')
|
343 |
+
|
344 |
+
# Extract the alpha channel and multiply by alpha_multiplier
|
345 |
+
alpha_channel = image_with_alpha.split()[3]
|
346 |
+
alpha_channel = alpha_channel.point(lambda p: p * alpha_multiplier)
|
347 |
+
|
348 |
+
# Apply the modified alpha channel back to the image
|
349 |
+
image_with_alpha.putalpha(alpha_channel)
|
350 |
+
|
351 |
+
# Composite the images
|
352 |
+
result = Image.alpha_composite(base_image, image_with_alpha)
|
353 |
+
|
354 |
+
return result
|
355 |
+
|
356 |
+
def apply_alpha_mask(image, mask_image, invert = False):
|
357 |
+
"""
|
358 |
+
Applies a mask image as the alpha channel of the input image.
|
359 |
+
|
360 |
+
Parameters:
|
361 |
+
image (PIL.Image.Image): The image to apply the mask to.
|
362 |
+
mask_image (PIL.Image.Image): The alpha mask to apply.
|
363 |
+
invert (bool): Whether to invert the mask (default is False).
|
364 |
+
|
365 |
+
Returns:
|
366 |
+
PIL.Image.Image: The image with the applied alpha mask.
|
367 |
+
"""
|
368 |
+
# Resize the mask to match the current image size
|
369 |
+
mask_image = resize_and_crop_image(mask_image, image.width, image.height).convert('L') # convert to grayscale
|
370 |
+
if invert:
|
371 |
+
mask_image = ImageOps.invert(mask_image)
|
372 |
+
# Apply the mask as the alpha layer of the current image
|
373 |
+
result_image = image.copy()
|
374 |
+
result_image.putalpha(mask_image)
|
375 |
+
return result_image
|
376 |
+
|
377 |
+
def resize_and_crop_image(image: Image, new_width: int = 512, new_height: int = 512) -> Image:
|
378 |
+
"""
|
379 |
+
Resizes and crops an image to a specified width and height. This ensures that the entire new_width and new_height
|
380 |
+
dimensions are filled by the image, and the aspect ratio is maintained.
|
381 |
+
|
382 |
+
Parameters:
|
383 |
+
image (PIL.Image.Image): The image to be resized and cropped.
|
384 |
+
new_width (int): The desired width of the new image (default is 512).
|
385 |
+
new_height (int): The desired height of the new image (default is 512).
|
386 |
+
|
387 |
+
Returns:
|
388 |
+
PIL.Image.Image: The resized and cropped image.
|
389 |
+
"""
|
390 |
+
# Get the dimensions of the original image
|
391 |
+
orig_width, orig_height = image.size
|
392 |
+
# Calculate the aspect ratios of the original and new images
|
393 |
+
orig_aspect_ratio = orig_width / float(orig_height)
|
394 |
+
new_aspect_ratio = new_width / float(new_height)
|
395 |
+
# Calculate the new size of the image while maintaining aspect ratio
|
396 |
+
if orig_aspect_ratio > new_aspect_ratio:
|
397 |
+
# The original image is wider than the new image, so we need to crop the sides
|
398 |
+
resized_width = int(new_height * orig_aspect_ratio)
|
399 |
+
resized_height = new_height
|
400 |
+
left_offset = (resized_width - new_width) // 2
|
401 |
+
top_offset = 0
|
402 |
+
else:
|
403 |
+
# The original image is taller than the new image, so we need to crop the top and bottom
|
404 |
+
resized_width = new_width
|
405 |
+
resized_height = int(new_width / orig_aspect_ratio)
|
406 |
+
left_offset = 0
|
407 |
+
top_offset = (resized_height - new_height) // 2
|
408 |
+
# Resize the image with Lanczos resampling filter
|
409 |
+
resized_image = image.resize((resized_width, resized_height), resample=Image.Resampling.LANCZOS)
|
410 |
+
# Crop the image to fill the entire height and width of the new image
|
411 |
+
cropped_image = resized_image.crop((left_offset, top_offset, left_offset + new_width, top_offset + new_height))
|
412 |
+
return cropped_image
|
413 |
+
|
414 |
+
##################################################### LUTs ############################################################
|
415 |
+
|
416 |
+
def is_3dlut_row(row: List[str]) -> bool:
|
417 |
+
"""
|
418 |
+
Check if one line in the file has exactly 3 numeric values.
|
419 |
+
|
420 |
+
Parameters:
|
421 |
+
row (list): A list of strings representing the values in a row.
|
422 |
+
|
423 |
+
Returns:
|
424 |
+
bool: True if the row has exactly 3 numeric values, False otherwise.
|
425 |
+
"""
|
426 |
+
try:
|
427 |
+
row_values = [float(val) for val in row]
|
428 |
+
return len(row_values) == 3
|
429 |
+
except ValueError:
|
430 |
+
return False
|
431 |
+
|
432 |
+
|
433 |
+
def read_lut(path_lut: Union[str, os.PathLike], num_channels: int = 3) -> ImageFilter.Color3DLUT:
|
434 |
+
"""
|
435 |
+
Read LUT from a raw file.
|
436 |
+
|
437 |
+
Each line in the file is considered part of the LUT table. The function
|
438 |
+
reads the file, parses the rows, and constructs a Color3DLUT object.
|
439 |
+
|
440 |
+
Args:
|
441 |
+
path_lut: A string or os.PathLike object representing the path to the LUT file.
|
442 |
+
num_channels: An integer specifying the number of color channels in the LUT (default is 3).
|
443 |
+
|
444 |
+
Returns:
|
445 |
+
An instance of ImageFilter.Color3DLUT representing the LUT.
|
446 |
+
|
447 |
+
Raises:
|
448 |
+
FileNotFoundError: If the LUT file specified by path_lut does not exist.
|
449 |
+
"""
|
450 |
+
with open(path_lut) as f:
|
451 |
+
lut_raw = f.read().splitlines()
|
452 |
+
|
453 |
+
size = round(len(lut_raw) ** (1 / 3))
|
454 |
+
row2val = lambda row: tuple([float(val) for val in row.split(" ")])
|
455 |
+
lut_table = [row2val(row) for row in lut_raw if is_3dlut_row(row.split(" "))]
|
456 |
+
|
457 |
+
return ImageFilter.Color3DLUT(size, lut_table, num_channels)
|
458 |
+
|
459 |
+
def apply_lut(img: Image, lut_path: str = "", lut: ImageFilter.Color3DLUT = None) -> Image:
|
460 |
+
"""
|
461 |
+
Apply a LUT to an image and return a PIL Image with the LUT applied.
|
462 |
+
|
463 |
+
The function applies the LUT to the input image using the filter() method of the PIL Image class.
|
464 |
+
|
465 |
+
Args:
|
466 |
+
img: A PIL Image object to which the LUT should be applied.
|
467 |
+
lut_path: A string representing the path to the LUT file (optional if lut argument is provided).
|
468 |
+
lut: An instance of ImageFilter.Color3DLUT representing the LUT (optional if lut_path is provided).
|
469 |
+
|
470 |
+
Returns:
|
471 |
+
A PIL Image object with the LUT applied.
|
472 |
+
|
473 |
+
Raises:
|
474 |
+
ValueError: If both lut_path and lut arguments are not provided.
|
475 |
+
"""
|
476 |
+
if lut is None:
|
477 |
+
if lut_path == "":
|
478 |
+
raise ValueError("Either lut_path or lut argument must be provided.")
|
479 |
+
lut = read_lut(lut_path)
|
480 |
+
|
481 |
+
return img.filter(lut)
|
482 |
+
|
483 |
+
def show_lut(lut_filename: str, lut_example_image: Image = default_lut_example_img) -> Image:
|
484 |
+
if lut_filename is not None:
|
485 |
+
try:
|
486 |
+
lut_example_image = apply_lut(lut_example_image, lut_filename)
|
487 |
+
except Exception as e:
|
488 |
+
print(f"BAD LUT: Error applying LUT {str(e)}.")
|
489 |
+
else:
|
490 |
+
lut_example_image = open_image(default_lut_example_img)
|
491 |
+
return lut_example_image
|
492 |
+
|
493 |
+
def convert_rgb_to_rgba_safe(image: Image) -> Image:
|
494 |
+
"""
|
495 |
+
Converts an RGB image to RGBA by adding an alpha channel.
|
496 |
+
Ensures that the original image remains unaltered.
|
497 |
+
|
498 |
+
Parameters:
|
499 |
+
image (PIL.Image.Image): The RGB image to convert.
|
500 |
+
|
501 |
+
Returns:
|
502 |
+
PIL.Image.Image: The converted RGBA image.
|
503 |
+
"""
|
504 |
+
if image.mode != 'RGB':
|
505 |
+
if image.mode == 'RGBA':
|
506 |
+
return image
|
507 |
+
elif image.mode == 'P':
|
508 |
+
# Convert palette image to RGBA
|
509 |
+
image = image.convert('RGB')
|
510 |
+
else:
|
511 |
+
raise ValueError("Unsupported image mode for conversion to RGBA.")
|
512 |
+
|
513 |
+
# Create a copy of the image to avoid modifying the original
|
514 |
+
rgba_image = image.copy()
|
515 |
+
|
516 |
+
# Optionally, set a default alpha value (e.g., fully opaque)
|
517 |
+
alpha = Image.new('L', rgba_image.size, 255) # 255 for full opacity
|
518 |
+
rgba_image.putalpha(alpha)
|
519 |
+
|
520 |
+
return rgba_image
|
521 |
+
|
522 |
+
def apply_lut_to_image_path(lut_filename: str, image_path: str) -> Image:
|
523 |
+
"""
|
524 |
+
Apply a LUT to an image and return the result.
|
525 |
+
|
526 |
+
Args:
|
527 |
+
lut_filename: A string representing the path to the LUT file.
|
528 |
+
image_path: A string representing the path to the input image.
|
529 |
+
|
530 |
+
Returns:
|
531 |
+
A PIL Image object with the LUT applied.
|
532 |
+
"""
|
533 |
+
img = open_image(image_path)
|
534 |
+
# Handle specific file formats by converting to appropriate modes
|
535 |
+
if image_path.lower().endswith(('.gif', '.webp')):
|
536 |
+
# Convert to RGBA to preserve transparency
|
537 |
+
img = img.convert('RGBA')
|
538 |
+
elif image_path.lower().endswith(('.jpg', '.jpeg')):
|
539 |
+
# Convert to RGB since JPEG doesn't support transparency
|
540 |
+
img = convert_rgb_to_rgba_safe(img)
|
541 |
+
|
542 |
+
# For other formats like PNG, retain the existing mode
|
543 |
+
# Apply the LUT if provided
|
544 |
+
if lut_filename is not None:
|
545 |
+
try:
|
546 |
+
img = apply_lut(img, lut_filename)
|
547 |
+
except Exception as e:
|
548 |
+
print(f"BAD LUT: Error applying LUT {str(e)}.")
|
549 |
+
return img
|
550 |
+
|
551 |
+
|
552 |
+
def convert_to_rgba_png(file_path: str) -> None:
|
553 |
+
"""
|
554 |
+
Converts an image to RGBA PNG format and saves it with the same base name and a .png extension.
|
555 |
+
|
556 |
+
Args:
|
557 |
+
file_path (str): The path to the input image file.
|
558 |
+
|
559 |
+
Raises:
|
560 |
+
ValueError: If the input file extension is not a supported image format.
|
561 |
+
Exception: If there is an error during the conversion or saving process.
|
562 |
+
"""
|
563 |
+
try:
|
564 |
+
# Open the original image
|
565 |
+
img = open_image(file_path)
|
566 |
+
|
567 |
+
# Convert the image to RGBA
|
568 |
+
rgba_img = convert_rgb_to_rgba_safe(img)
|
569 |
+
# Generate the new file name with .png extension
|
570 |
+
base_name = os.path.splitext(file_path)[0]
|
571 |
+
new_file_path = f"{base_name}.png"
|
572 |
+
# Save the RGBA image as PNG
|
573 |
+
rgba_img.save(new_file_path, format='PNG')
|
574 |
+
print(f"Image saved as {new_file_path}")
|
575 |
+
except ValueError as ve:
|
576 |
+
print(f"ValueError: {ve}")
|
577 |
+
except Exception as e:
|
578 |
+
print(f"Error converting image: {e}")
|
utils/misc.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# misc.py file contains miscellaneous utility functions
|
2 |
+
import math
|
3 |
+
import sys
|
4 |
+
|
5 |
+
def pause():
|
6 |
+
"""
|
7 |
+
Pauses the execution until any key is pressed.
|
8 |
+
"""
|
9 |
+
if sys.platform.startswith('win'):
|
10 |
+
import msvcrt
|
11 |
+
print("Press any key to continue...")
|
12 |
+
msvcrt.getch()
|
13 |
+
else:
|
14 |
+
import termios
|
15 |
+
import tty
|
16 |
+
print("Press any key to continue...")
|
17 |
+
fd = sys.stdin.fileno()
|
18 |
+
old_settings = termios.tcgetattr(fd)
|
19 |
+
try:
|
20 |
+
tty.setraw(fd)
|
21 |
+
sys.stdin.read(1)
|
22 |
+
finally:
|
23 |
+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
|
24 |
+
|
25 |
+
|
26 |
+
def install(package):
|
27 |
+
import subprocess
|
28 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
|
29 |
+
|
30 |
+
def get_filename(file):
|
31 |
+
filename = None
|
32 |
+
if file is not None:
|
33 |
+
filename = file.name
|
34 |
+
return filename
|
35 |
+
|
36 |
+
def get_extension(file):
|
37 |
+
extension = None
|
38 |
+
if file is not None:
|
39 |
+
extension = file.name.split(".")[-1]
|
40 |
+
return extension
|
41 |
+
|
42 |
+
|
43 |
+
def convert_ratio_to_dimensions(ratio, height=512, rotate90=False):
|
44 |
+
"""
|
45 |
+
Calculate pixel dimensions based on a given aspect ratio and base height.
|
46 |
+
|
47 |
+
This function computes the width and height in pixels for an image, ensuring that both dimensions are divisible by 16. The height is adjusted upwards to the nearest multiple of 16 if necessary, and the width is calculated based on the adjusted height and the provided aspect ratio. Additionally, it ensures that both width and height are at least 16 pixels to avoid extremely small dimensions.
|
48 |
+
|
49 |
+
Parameters:
|
50 |
+
ratio (float): The aspect ratio of the image (width divided by height).
|
51 |
+
height (int, optional): The base height in pixels. Defaults to 512.
|
52 |
+
|
53 |
+
Returns:
|
54 |
+
tuple: A tuple containing the calculated (width, height) in pixels, both divisible by 16.
|
55 |
+
"""
|
56 |
+
base_height = 512
|
57 |
+
# Scale the height based on the provided height parameter
|
58 |
+
# Ensure the height is at least base_height
|
59 |
+
scaled_height = max(height, base_height)
|
60 |
+
# Adjust the height to be divisible by 16
|
61 |
+
adjusted_height = math.ceil(scaled_height / 16) * 16
|
62 |
+
# Calculate the width based on the ratio
|
63 |
+
calculated_width = int(adjusted_height * ratio)
|
64 |
+
# Adjust the width to be divisible by 16
|
65 |
+
adjusted_width = math.ceil(calculated_width / 16) * 16
|
66 |
+
if rotate90:
|
67 |
+
adjusted_width, adjusted_height = adjusted_height, adjusted_width
|
68 |
+
return adjusted_width, adjusted_height
|
69 |
+
|