Metal每日分享,四维向量偏移滤镜效果

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

本案例的目的是理解如何用Metal实现图像4维向量颜色效果滤镜,通过对像素点颜色进行4维向量叠加运算得到新的像素点;


Demo

实操代码

// 暖色系
let filter = C7ColorVector4(vector: Vector4.Color.warm)

// 方案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

效果对比图

origin: 原始 warm: 暖色系 cool_tone: 冷色系
WX20221205-103059.png WX20221205-103110.png WX20221205-103121.png

实现原理

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

对外开放参数

/// 四维向量颜色
public struct C7ColorVector4: C7FilterProtocol {
    
    public var vector: Vector4
    
    public var modifier: Modifier {
        return .compute(kernel: "C7ColorVector4")
    }
    
    public func setupSpecialFactors(for encoder: MTLCommandEncoder, index: Int) {
        guard let computeEncoder = encoder as? MTLComputeCommandEncoder else { return }
        var factor = vector.to_factor()
        computeEncoder.setBytes(&factor, length: Vector4.size, index: index + 1)
    }
    
    public init(vector: Vector4) {
        self.vector = vector
    }
}

对像素点颜色进行4维向量叠加运算inColor + half4(*vector)

kernel void C7ColorVector4(texture2d<half, access::write> outputTexture [[texture(0)]],
                           texture2d<half, access::read> inputTexture [[texture(1)]],
                           constant float4 *vector [[buffer(0)]],
                           uint2 grid [[thread_position_in_grid]]) {
    const half4 inColor = inputTexture.read(grid);
    
    const half4 outColor = inColor + half4(*vector);
    
    outputTexture.write(outColor, grid);
}

4维向量

extension Vector4 {
    public struct Color { }
}

extension Vector4.Color {
    
    /// 原始
    public static let origin = Vector4(values: [0.0, 0.0, 0.0, 0.0])
    
    /// 暖色,将rgb通道的颜色添加相应的红/绿色值
    /// Warm color, add the color of the rgb channel to the corresponding red/green value.
    public static let warm = Vector4(values: [0.3, 0.3, 0.0, 0.0])
    
    /// 冷色,将rgb通道的颜色添加相应的蓝色值
    /// Cold color, add the color of the rgb channel to the corresponding blue value.
    public static let cool_tone = Vector4(values: [0.0, 0.0, 0.3, 0.0])
}

Harbeth功能清单

最后

✌️.

上一篇 下一篇

猜你喜欢

热点阅读