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

本案例的目的是理解如何用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);
}

Harbeth功能清单

  • 支持ios系统和macOS系统
  • 支持运算符函数式操作
  • 支持多种模式数据源 UIImage, CIImage, CGImage, CMSampleBuffer, CVPixelBuffer.
  • 支持快速设计滤镜
  • 支持合并多种滤镜效果
  • 支持输出源的快速扩展
  • 支持相机采集特效
  • 支持视频添加滤镜特效
  • 支持矩阵卷积
  • 支持使用系统 MetalPerformanceShaders.
  • 支持兼容 CoreImage.
  • 滤镜部分大致分为以下几个模块:
    • Blend:图像融合技术
    • Blur:模糊效果
    • Pixel:图像的基本像素颜色处理
    • Effect:效果处理
    • Lookup:查找表过滤器
    • Matrix: 矩阵卷积滤波器
    • Shape:图像形状大小相关
    • Visual: 视觉动态特效
    • MPS: 系统 MetalPerformanceShaders.

最后

  • 慢慢再补充其他相关滤镜,喜欢就给我点个星🌟吧。
  • 滤镜Demo地址,目前包含100+种滤镜,同时也支持CoreImage混合使用。
  • 再附上一个开发加速库KJCategoriesDemo地址
  • 再附上一个网络基础库RxNetworksDemo地址
  • 喜欢的老板们可以点个星🌟,谢谢各位老板!!!

✌️.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值