farm-recolor / recolorReinhardV2Algo.py
vettorazi's picture
new modes added, fixes in old methods and improvements in the server
1683145
raw
history blame contribute delete
No virus
2.8 kB
import cv2
import numpy as np
def color_transfer(source, target):
# Convert the images from RGB to L*a*b* color space
source_lab = cv2.cvtColor(source, cv2.COLOR_BGR2Lab)
target_lab = cv2.cvtColor(target, cv2.COLOR_BGR2Lab)
# Split the LAB image into L, A and B channels
source_l, source_a, source_b = cv2.split(source_lab)
target_l, target_a, target_b = cv2.split(target_lab)
# Compute mean and standard deviation for each channel in both images
l_mean_src, l_std_src, = source_l.mean(), source_l.std()
a_mean_src, a_std_src = source_a.mean(), source_a.std()
b_mean_src, b_std_src = source_b.mean(), source_b.std()
l_mean_tar, l_std_tar = target_l.mean(), target_l.std()
a_mean_tar, a_std_tar = target_a.mean(), target_a.std()
b_mean_tar, b_std_tar = target_b.mean(), target_b.std()
# Perform the color transfer
l_result = (source_l - l_mean_src) * (l_std_tar / l_std_src) + l_mean_tar
a_result = (source_a - a_mean_src) * (a_std_tar / a_std_src) + a_mean_tar
b_result = (source_b - b_mean_src) * (b_std_tar / b_std_src) + b_mean_tar
# Clip and reshape the channels
l_result = np.clip(l_result, 0, 255).astype(np.uint8)
a_result = np.clip(a_result, 0, 255).astype(np.uint8)
b_result = np.clip(b_result, 0, 255).astype(np.uint8)
# Merge the channels back
result_lab = cv2.merge([l_result, a_result, b_result])
# Convert the resulting image from L*a*b* to RGB color space
result = cv2.cvtColor(result_lab, cv2.COLOR_Lab2BGR)
return result
def create_target_image(hex_colors):
# Convert hex colors to RGB
rgb_colors = [tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) for hex_color in hex_colors]
# Create an image with the RGB colors
target_image = np.zeros((100, len(rgb_colors), 3), dtype=np.uint8)
for i, rgb_color in enumerate(rgb_colors):
target_image[:, i] = rgb_color
return target_image
# # Load source and target images
# source_img = cv2.imread("estampa.jpg")
# target_img = cv2.imread("cor.jpg")
# hex_colors = ['ff0000', '00ff00', '0000ff'] # Example hex colors
# target_img = create_target_image(hex_colors)
# image_bytes = io.BytesIO(source_img)
# image_np = np.array(image)
# # Perform color transfer
# transferred_img = color_transfer(source_img, target_img)
# # Return the transferred image for visualization
# cv2.imwrite("result.jpg", transferred_img)
def recolor(image_np, colors):
colors = [color.replace('#', '') for color in colors]
target_img = create_target_image(colors)
source_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
transferred_img = color_transfer(source_bgr, target_img)
cv2.imwrite("result.jpg", transferred_img)
return transferred_img