Initial commit
This commit is contained in:
+65
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
sharpen.py — ComfyUI_essentials ImageCASharpening+ 的独立移植。
|
||||
|
||||
来源:https://github.com/Jamy-L/Pytorch-Contrast-Adaptive-Sharpening/
|
||||
与 essentials 逐行对齐(含 min_/max_ 的 clamp 语义)。
|
||||
|
||||
tensor 约定:BHWC、float32、[0, 1]、RGB。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def _min_(tensor_list):
|
||||
x = torch.stack(tensor_list)
|
||||
mn = x.min(axis=0)[0]
|
||||
return torch.clamp(mn, min=0)
|
||||
|
||||
|
||||
def _max_(tensor_list):
|
||||
x = torch.stack(tensor_list)
|
||||
mx = x.max(axis=0)[0]
|
||||
return torch.clamp(mx, max=1)
|
||||
|
||||
|
||||
def cas_sharpen(image_bhwc01: torch.Tensor, amount: float) -> torch.Tensor:
|
||||
"""对比度自适应锐化。amount ∈ [0, 1](工作流用 1.0 与 0.8)。"""
|
||||
epsilon = 1e-5
|
||||
img = F.pad(image_bhwc01.permute([0, 3, 1, 2]), pad=(1, 1, 1, 1))
|
||||
|
||||
a = img[..., :-2, :-2]
|
||||
b = img[..., :-2, 1:-1]
|
||||
c = img[..., :-2, 2:]
|
||||
d = img[..., 1:-1, :-2]
|
||||
e = img[..., 1:-1, 1:-1]
|
||||
f = img[..., 1:-1, 2:]
|
||||
g = img[..., 2:, :-2]
|
||||
h = img[..., 2:, 1:-1]
|
||||
i = img[..., 2:, 2:]
|
||||
|
||||
# Computing contrast
|
||||
cross = (b, d, e, f, h)
|
||||
mn = _min_(cross)
|
||||
mx = _max_(cross)
|
||||
|
||||
diag = (a, c, g, i)
|
||||
mn2 = _min_(diag)
|
||||
mx2 = _max_(diag)
|
||||
mx = mx + mx2
|
||||
mn = mn + mn2
|
||||
|
||||
# Computing local weight
|
||||
inv_mx = torch.reciprocal(mx + epsilon)
|
||||
amp = inv_mx * torch.minimum(mn, (2 - mx))
|
||||
|
||||
# scaling
|
||||
amp = torch.sqrt(amp)
|
||||
w = -amp * (amount * (1 / 5 - 1 / 8) + 1 / 8)
|
||||
div = torch.reciprocal(1 + 4 * w)
|
||||
|
||||
output = ((b + d + f + h) * w + e) * div
|
||||
output = output.clamp(0, 1)
|
||||
return output.permute([0, 2, 3, 1])
|
||||
Reference in New Issue
Block a user