|
import numpy as np |
|
from PIL import Image |
|
import cv2 |
|
|
|
|
|
def hex_to_rgb(hex_color): |
|
hex_color = hex_color.lstrip('#') |
|
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) |
|
def rgb_to_bgr(rgb_color): |
|
return rgb_color[::-1] |
|
def recolor_selected_area(image_np, color_to_replace, replacement_color, tolerance=20): |
|
|
|
color_to_replace_rgb = hex_to_rgb(color_to_replace) |
|
replacement_color_rgb = hex_to_rgb(replacement_color) |
|
color_to_replace_bgr = rgb_to_bgr(color_to_replace_rgb) |
|
replacement_color_bgr = rgb_to_bgr(replacement_color_rgb) |
|
|
|
lower_bound = np.array([max(c - tolerance, 0) for c in color_to_replace_bgr]) |
|
upper_bound = np.array([min(c + tolerance, 255) for c in color_to_replace_bgr]) |
|
|
|
image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) |
|
|
|
mask = cv2.inRange(image_bgr, lower_bound, upper_bound) |
|
|
|
image_bgr[mask > 0] = replacement_color_bgr |
|
|
|
result_image_np = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) |
|
|
|
result_image = Image.fromarray(result_image_np) |
|
result_image.save('./result.jpg') |
|
return result_image |