anamnesis_GIS_TOOLS / image_utils.py
threeorfour's picture
Upload 16 files
e1ec339 verified
import base64
import numpy as np
from PIL import Image
from io import BytesIO
def load_captured_image(b64_string):
if not b64_string or not b64_string.startswith("data:image/png;base64,"): return None
img_data = base64.b64decode(b64_string.split(',')[1])
return Image.open(BytesIO(img_data)).convert("RGB")
def hex_to_rgb(hex_color):
try:
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
except (ValueError, TypeError, AttributeError):
return (0, 0, 0)
def process_fade_with_drop(source_image, preserve_hex, falloff_str, drop_hex, drop_strength_str, min_fade_str, recolor_hex, recolor_strength_str):
if source_image is None: return None
source_array = np.array(source_image, dtype=np.float32)
preserve_rgb = np.array(hex_to_rgb(preserve_hex), dtype=np.float32)
drop_rgb = np.array(hex_to_rgb(drop_hex), dtype=np.float32)
recolor_rgb = np.array(hex_to_rgb(recolor_hex), dtype=np.float32)
falloff = float(falloff_str) if float(falloff_str) > 0 else 1
drop_strength = float(drop_strength_str)
min_fade_ratio = float(min_fade_str) / 100.0
recolor_strength = float(recolor_strength_str) / 100.0
dist_to_preserve = np.linalg.norm(source_array - preserve_rgb, axis=2)
base_alpha = np.clip(dist_to_preserve / falloff, 0.0, 1.0)
dist_to_drop = np.linalg.norm(source_array - drop_rgb, axis=2)
repulsion_influence = 1.0 - np.clip(dist_to_drop / 100.0, 0.0, 1.0)
repulsion_multiplier = 1.0 + (repulsion_influence * drop_strength)
final_alpha = np.clip(base_alpha * repulsion_multiplier, 0.0, 1.0)
final_alpha = np.maximum(final_alpha, min_fade_ratio)
alpha_reshaped = final_alpha[:, :, np.newaxis]
white_bg = np.full_like(source_array, 255)
faded_array = source_array * (1 - alpha_reshaped) + white_bg * alpha_reshaped
if recolor_strength > 0:
recolor_mask = final_alpha < 1.0
pixels_to_recolor = faded_array[recolor_mask]
recolored_pixels = pixels_to_recolor * (1 - recolor_strength) + recolor_rgb * recolor_strength
faded_array[recolor_mask] = recolored_pixels
final_image_array = np.clip(faded_array, 0, 255).astype(np.uint8)
return Image.fromarray(final_image_array)