前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS 利用 Metal 实现滤镜与动效滤镜

iOS 利用 Metal 实现滤镜与动效滤镜

作者头像
网罗开发
发布2022-03-25 16:24:21
1.5K0
发布2022-03-25 16:24:21
举报
文章被收录于专栏:网罗开发网罗开发

功能清单

🟣 目前,Metal Moudle[1] 最重要的特点可以总结如下:

  • 支持运算符函数式操作
  • 支持快速设计滤镜
  • 支持输出源的快速扩展
  • 支持矩阵卷积
  • 滤镜部分大致分为以下几个模块:
    • Blend[2]:图像融合技术
    • Blur[3]:模糊效果
    • ColorProcess[4]:图像的基本像素颜色处理
    • Effect[5]:效果处理
    • Lookup[6]:查找表过滤器
    • Matrix[7]: 矩阵卷积滤波器
    • Shape[8]:图像形状大小相关
总结下来目前共有100+种滤镜供您使用。

主要部分

  • 核心,基础核心板块
    • modifier:编码器类型和对应的函数名称。
    • factors:设置修改参数因子,需要转换为Float
    • otherInputTextures:多个输入源,包含MTLTexture的数组
    • outputSize:更改输出图像的大小。
    • C7FilterProtocol[9]:滤镜设计必须遵循此协议。
  • 输出,输出板块
    • make:根据滤镜处理生成数据。
    • makeGroup:多个滤镜组合,请注意滤镜添加的顺序可能会影响图像生成的结果。
    • C7FilterOutput[10]:输出内容协议,所有输出都必须实现该协议。
    • C7FilterImage[11]:基于C7FilterOutput的图像输入源,以下模式仅支持基于并行计算的编码器。
    • C7FilterTexture[12]: 基于C7FilterOutput的纹理输入源,输入纹理转换成滤镜处理纹理。

设计滤镜

  • 下面我们就第一款滤镜来分享一下如何设计处理
  1. 实现协议 C7FilterProtocal
代码语言:javascript
复制
public protocol C7FilterProtocol {
     /// 编码器类型和对应的函数名
     ///
     /// 计算需要对应的`kernel`函数名
     /// 渲染需要一个`vertex`着色器函数名和一个`fragment`着色器函数名
     var modifier: Modifier { get }
    
     /// 制作缓冲区
     /// 设置修改参数因子,需要转换为`Float`。
     var factors: [Float] { get }
    
     /// 多输入源扩展
     /// 包含 `MTLTexture` 的数组
     var otherInputTextures: C7InputTextures { get }
    
     /// 改变输出图像的大小
     func outputSize(input size:C7Size)-> C7Size
}
  1. 编写基于并行计算的核函数着色器。
  2. 配置传递参数因子,仅支持Float类型。
  3. 配置额外的所需纹理。

举个例子

设计一款灵魂出窍滤镜,

代码语言:javascript
复制
public struct C7SoulOut: C7FilterProtocol {
    
    /// The adjusted soul, from 0.0 to 1.0, with a default of 0.5
    public var soul: Float = 0.5
    public var maxScale: Float = 1.5
    public var maxAlpha: Float = 0.5
    
    public var modifier: Modifier {
        return .compute(kernel: "C7SoulOut")
    }
    
    public var factors: [Float] {
        return [soul, maxScale, maxAlpha]
    }
    
    public init() { }
}
  • 此过滤器需要三个参数:
    • soul:调整后的灵魂,从 0.0 到 1.0,默认为 0.5
    • maxScale:最大灵魂比例
    • maxAlpha:最大灵魂的透明度
  • 编写基于并行计算内核函数
代码语言:javascript
复制
kernel void C7SoulOut(texture2d<half, access::write> outputTexture [[texture(0)]],
                      texture2d<half, access::sample> inputTexture [[texture(1)]],
                      constant float *soulPointer [[buffer(0)]],
                      constant float *maxScalePointer [[buffer(1)]],
                      constant float *maxAlphaPointer [[buffer(2)]],
                      uint2 grid [[thread_position_in_grid]]) {
    constexpr sampler quadSampler(mag_filter::linear, min_filter::linear);
    const half4 inColor = inputTexture.read(grid);
    const float x = float(grid.x) / outputTexture.get_width();
    const float y = float(grid.y) / outputTexture.get_height();

    const half soul = half(*soulPointer);
    const half maxScale = half(*maxScalePointer);
    const half maxAlpha = half(*maxAlphaPointer);

    const half alpha = maxAlpha * (1.0h - soul);
    const half scale = 1.0h + (maxScale - 1.0h) * soul;

    const half soulX = 0.5h + (x - 0.5h) / scale;
    const half soulY = 0.5h + (y - 0.5h) / scale;

    const half4 soulMask = inputTexture.sample(quadSampler, float2(soulX, soulY));
    const half4 outColor = inColor * (1.0h - alpha) + soulMask * alpha;

    outputTexture.write(outColor, grid);
}
  • 简单使用,由于我这边设计的是基于并行计算管道,所以可以直接生成图片
代码语言:javascript
复制
var filter = C7SoulOut()
filter.soul = 0.5
filter.maxScale = 2.0

/// 直接显示在ImageView
ImageView.image = try? originImage.makeImage(filter: filter)
  • 至于上面的动效也很简单,添加一个计时器,然后改变soul值就完事,简单嘛。

高级用法

  • 运算符链式处理
代码语言:javascript
复制
/// 1.转换成BGRA
let filter1 = C7Color2(with: .color2BGRA)

/// 2.调整颗粒度
var filter2 = C7Granularity()
filter2.grain = 0.8

/// 3.调整白平衡
var filter3 = C7WhiteBalance()
filter3.temperature = 5555

/// 4.调整高光阴影
var filter4 = C7HighlightShadow()
filter4.shadows = 0.4
filter4.highlights = 0.5

/// 5.组合操作
let AT = C7FilterTexture.init(texture: originImage.mt.toTexture()!)
let result = AT ->> filter1 ->> filter2 ->> filter3 ->> filter4

/// 6.获取结果
filterImageView.image = result.outputImage()
  • 批量操作处理
代码语言:javascript
复制
/// 1.转换成RBGA
let filter1 = C7Color2(with: .color2RBGA)

/// 2.调整颗粒度
var filter2 = C7Granularity()
filter2.grain = 0.8

/// 3.配置灵魂效果
var filter3 = C7SoulOut()
filter3.soul = 0.7

/// 4.组合操作
let group: [C7FilterProtocol] = [filter1, filter2, filter3]

/// 5.获取结果
filterImageView.image = try? originImage.makeGroup(filters: group)

两种方式都可以处理多滤镜方案,怎么选择就看你心情。✌️

CocoaPods

  • 如果要导入 Metal[13] 模块,则需要在 Podfile 中:
代码语言:javascript
复制
pod 'Harbeth'
  • 如果要导入 OpenCV[14] 图像模块,则需要在 Podfile 中:
代码语言:javascript
复制
pod 'OpencvQueen'

效果图

  • 来一波部分展示效果图:

文章涉及源码

  • 滤镜Demo地址[15],目前包含100+种滤镜,当然也有大部分滤镜算法是参考GPUImage[16]设计而来。
  • 再附上一个开发加速库KJCategoriesDemo 地址[17] 🎷喜欢的老板们可以点个星🌟

参考资料

[1] Metal Moudle: https://github.com/yangKJ/Harbeth

[2] Blend: https://github.com/yangKJ/Harbeth/tree/master/Sources/Compute/Blend

[3] Blur: https://github.com/yangKJ/Harbeth/tree/master/Sources/Compute/Blur

[4] ColorProcess: https://github.com/yangKJ/Harbeth/tree/master/Sources/Compute/ColorProcess

[5] Effect: https://github.com/yangKJ/Harbeth/tree/master/Sources/Compute/Effect

[6] Lookup: https://github.com/yangKJ/Harbeth/tree/master/Sources/Compute/Lookup

[7] Matrix: https://github.com/yangKJ/Harbeth/tree/master/Sources/Compute/Matrix

[8] Shape: https://github.com/yangKJ/Harbeth/tree/master/Sources/Compute/Shape

[9] C7FilterProtocol: https://github.com/yangKJ/Harbeth/blob/master/Sources/Basic/Core/C7FilterProtocol.swift

[10] C7FilterOutput: https://github.com/yangKJ/Harbeth/blob/master/Sources/Basic/Outputs/C7FilterOutput.swift

[11] C7FilterImage: https://github.com/yangKJ/Harbeth/blob/master/Sources/Basic/Outputs/C7FilterImage.swift

[12] C7FilterTexture: https://github.com/yangKJ/Harbeth/blob/master/Sources/Basic/Outputs/C7FilterTexture.swift

[13] Metal: https://github.com/yangKJ/Harbeth

[14] OpenCV: https://github.com/yangKJ/OpencvQueen

[15] 滤镜Demo地址: https://github.com/yangKJ/Harbeth

[16] GPUImage: https://github.com/BradLarson/GPUImage

[17] KJCategoriesDemo: https://github.com/yangKJ/KJCategories

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-02-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 网罗开发 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 功能清单
    • 总结下来目前共有100+种滤镜供您使用。
      • 主要部分
        • 设计滤镜
          • 举个例子
            • 高级用法
              • CocoaPods
                • 效果图
                  • 文章涉及源码
                    • 参考资料
                    相关产品与服务
                    GPU 云服务器
                    GPU 云服务器(Cloud GPU Service,GPU)是提供 GPU 算力的弹性计算服务,具有超强的并行计算能力,作为 IaaS 层的尖兵利器,服务于生成式AI,自动驾驶,深度学习训练、科学计算、图形图像处理、视频编解码等场景。腾讯云随时提供触手可得的算力,有效缓解您的计算压力,提升业务效率与竞争力。
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档