Metal每日分享,虚假颜色混合滤镜效果

2022-12-07  本文已影响0人  弹吉他的少年

本案例的目的是理解如何用Metal实现虚假颜色效果滤镜,使用图像的亮度在两种用户指定的颜色之间进行混合;


Demo

实操代码

// 混合颜色
let filter = C7FalseColor.init(fristColor: .blue, secondColor: .green)

// 方案1:
ImageView.image = try? BoxxIO(element: originImage, filters: [filter, filter2, filter3]).output()

// 方案2:
ImageView.image = originImage.filtering(filter, filter2, filter3)

// 方案3:
ImageView.image = originImage ->> filter ->> filter2 ->> filter3

效果对比图

蓝色~绿色 黄色~棕色 绿色~蓝色

实现原理

这款滤镜采用并行计算编码器设计.compute(kernel: "C7FalseColor")

对外开放参数

/// 使用图像的亮度在两种用户指定的颜色之间进行混合
/// Uses the luminance of the image to mix between two user-specified colors
public struct C7FalseColor: C7FilterProtocol, ComputeFiltering {
    
    /// The first and second colors specify what colors replace the dark and light areas of the image, respectively.
    public var fristColor: C7Color = .zero
    
    public var secondColor: C7Color = .zero
    
    public var modifier: Modifier {
        return .compute(kernel: "C7FalseColor")
    }
    
    public func setupSpecialFactors(for encoder: MTLCommandEncoder, index: Int) {
        guard let computeEncoder = encoder as? MTLComputeCommandEncoder else { return }
        var fristFactor = Vector3.init(color: fristColor).to_factor()
        computeEncoder.setBytes(&fristFactor, length: Vector3.size, index: index + 1)
        var secondFactor = Vector3(color: secondColor).to_factor()
        computeEncoder.setBytes(&secondFactor, length: Vector3.size, index: index + 2)
    }
    
    public init(fristColor: C7Color = .zero, secondColor: C7Color = .zero) {
        self.fristColor = fristColor
        self.secondColor = secondColor
    }
}

计算出输入像素dot(inColor.rgb, luminanceWeighting)亮度点积,然后再两种输入颜色当中混合mix(color1.rgb, color2.rgb, luminance)获取到rgb;

kernel void C7FalseColor(texture2d<half, access::write> outputTexture [[texture(0)]],
                         texture2d<half, access::read> inputTexture [[texture(1)]],
                         constant float3 *firstVector [[buffer(0)]],
                         constant float3 *secondVector [[buffer(1)]],
                         uint2 grid [[thread_position_in_grid]]) {
    const half4 inColor = inputTexture.read(grid);
    
    const half3 luminanceWeighting = half3(0.2125, 0.7154, 0.0721);
    const half luminance = dot(inColor.rgb, luminanceWeighting);
    const half3 color1 = half3(*firstVector);
    const half3 color2 = half3(*secondVector);
    const half4 outColor = half4(mix(half3(color1.rgb), half3(color2.rgb), half3(luminance)), inColor.a);
    
    outputTexture.write(outColor, grid);
}

Harbeth功能清单

最后

✌️.

上一篇 下一篇

猜你喜欢

热点阅读