Metal每日分享,海报画滤镜效果

999 阅读1分钟

「这是我参与2022首次更文挑战的第23天,活动详情查看:2022首次更文挑战

本案例的目的是理解如何用Metal实现海报画效果滤镜,主要就是改变颜色级别数量从而获取到新的像素颜色;


Demo

实操代码

// 海报画滤镜
let filter = C7Posterize.init(colorLevels: 2.3)

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

效果对比图

  • 不同参数下效果
colorLevels: 1.03colorLevels: 2.3colorLevels: 5.03
WX20221213-112230.pngWX20221213-112244.pngWX20221213-112256.png

实现原理

  • 过滤器

这款滤镜采用并行计算编码器设计.compute(kernel: "C7Posterize"),参数因子[colorLevels]

对外开放参数

  • colorLevels: 减少图像空间的颜色级别数量;
public struct C7Posterize: C7FilterProtocol {
    
    public static let range: ParameterRange<Float, Self> = .init(min: 1.0, max: 255.0, value: 10.0)
    
    /// The number of color levels to reduce the image space to.
    /// This ranges from 1 to 256, with a default of 10
    public var colorLevels: Float = range.value
    
    public var modifier: Modifier {
        return .compute(kernel: "C7Posterize")
    }
    
    public var factors: [Float] {
        return [colorLevels]
    }
    
    public init(colorLevels: Float = range.value) {
        self.colorLevels = colorLevels
    }
}
  • 着色器

对输入像素x颜色级别数量再加上平均亮度half4(0.5h)取整floor,再除以颜色级别数量得到最终的像素颜色;

kernel void C7Posterize(texture2d<half, access::write> outputTexture [[texture(0)]],
                        texture2d<half, access::read> inputTexture [[texture(1)]],
                        constant float *colorLevelsPointer [[buffer(0)]],
                        uint2 grid [[thread_position_in_grid]]) {
    const half4 inColor = inputTexture.read(grid);
    
    const half colorLevels = half(*colorLevelsPointer);
    const half4 outColor = floor((inColor * colorLevels) + half4(0.5h)) / colorLevels;
    
    outputTexture.write(outColor, grid);
}

最后

  • 慢慢再补充其他相关滤镜,喜欢就给我点个星🌟吧。

✌️.