how can i run this code in natron – Processing

import NatronGui
import numpy as np
from PIL import Image

def analyze_image_colors(image_path):
“””
分析图像的颜色分布特征。
“””
img = Image.open(image_path).convert(“RGB”)
data = np.array(img)

# 计算 RGB 通道的均值和标准差
mean = data.mean(axis=(0, 1))
std = data.std(axis=(0, 1))

return mean, std

def apply_color_transfer(target_img_path, ref_mean, ref_std):
“””
根据参考图像的颜色特征调整目标图像。
“””
target_img = Image.open(target_img_path).convert(“RGB”)
data = np.array(target_img)

# 调整颜色:标准化目标图像,并匹配参考图像的均值和标准差
adjusted = (data - data.mean(axis=(0, 1))) * (ref_std / data.std(axis=(0, 1))) + ref_mean
adjusted = np.clip(adjusted, 0, 255).astype(np.uint8)

return Image.fromarray(adjusted)

def export_lut(output_path, ref_mean, ref_std, target_mean, target_std):
“””
生成 LUT 文件
“””
size = 32 # LUT 网格大小
with open(output_path, ‘w’) as f:
f.write(“TITLE “Generated LUT”\n”)
f.write(“LUT_3D_SIZE {}\n”.format(size))
for r in range(size):
for g in range(size):
for b in range(size):
r_val = (r / (size – 1)) * 255
g_val = (g / (size – 1)) * 255
b_val = (b / (size – 1)) * 255

                # 应用调色公式
                r_out = ((r_val - target_mean[0]) * (ref_std[0] / target_std[0])) + ref_mean[0]
                g_out = ((g_val - target_mean[1]) * (ref_std[1] / target_std[1])) + ref_mean[1]
                b_out = ((b_val - target_mean[2]) * (ref_std[2] / target_std[2])) + ref_mean[2]

                # 限制值域
                r_out = np.clip(r_out / 255.0, 0, 1)
                g_out = np.clip(g_out / 255.0, 0, 1)
                b_out = np.clip(b_out / 255.0, 0, 1)

                f.write("{:.6f} {:.6f} {:.6f}\n".format(r_out, g_out, b_out))

def style_transfer_in_natron():
“””
在 Natron 中实现风格迁移和 LUT 文件生成。
“””
app = NatronGui.natron.getGuiInstance(0)

# 获取 Read 节点
ref_node = app.getNode("Read1")  # 参考图像
target_node = app.getNode("Read2")  # 目标图像

# 获取图像路径
ref_img_path = ref_node.getParam("file").getValue()
target_img_path = target_node.getParam("file").getValue()

# 分析参考图像
print("分析参考图像颜色分布...")
ref_mean, ref_std = analyze_image_colors(ref_img_path)

# 分析目标图像
print("分析目标图像颜色分布...")
target_mean, target_std = analyze_image_colors(target_img_path)

# 调整目标图像
print("应用风格迁移...")
adjusted_image = apply_color_transfer(target_img_path, ref_mean, ref_std)
adjusted_image.save("output_adjusted.png")  # 保存调整后的图像

# 导出 LUT 文件
print("生成 LUT 文件...")
output_path = "output_lut.cube"
export_lut(output_path, ref_mean, ref_std, target_mean, target_std)

print("风格迁移和 LUT 文件生成完成!")
print("调整后的图像保存为: output_adjusted.png")
print("LUT 文件保存为: {}".format(output_path))

style_transfer_in_natron()

Read more here: Source link