Metal每日分享,3x3矩阵卷积滤镜效果

简介: Metal每日分享,3x3矩阵卷积滤镜效果

Demo


HarbethDemo地址

iDay每日分享文档地址


实操代码


// 锐化卷积效果滤镜
let filter = C7ConvolutionMatrix3x3(convolutionType: .sharpen(iterations: 2))
// 方案1:
let dest = BoxxIO.init(element: originImage, filter: filter)
ImageView.image = try? dest.output()
dest.filters.forEach {
    NSLog("%@", "\($0.parameterDescription)")
}
// 方案2:
ImageView.image = try? originImage.make(filter: filter)
// 方案3:
ImageView.image = originImage ->> filter


实现原理


过滤器

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

对外开放参数

convolutionPixel: 卷积像素

/// 3 x 3卷积
public struct C7ConvolutionMatrix3x3: C7FilterProtocol {
    public enum ConvolutionType {
        case `default`
        case identity
        case edgedetect
        case embossment
        case embossment45
        case morphological
        case sobel(orientation: Bool)
        case laplance(iterations: Float)
        case sharpen(iterations: Float)
        case custom(Matrix3x3)
    }
    /// Convolution pixels, default 1
    public var convolutionPixel: Int = 1
    private var matrix: Matrix3x3
    public var modifier: Modifier {
        return .compute(kernel: "C7ConvolutionMatrix3x3")
    }
    public var factors: [Float] {
        return [Float(convolutionPixel)]
    }
    public func setupSpecialFactors(for encoder: MTLCommandEncoder, index: Int) {
        guard let computeEncoder = encoder as? MTLComputeCommandEncoder else { return }
        var factor = matrix.to_factor()
        computeEncoder.setBytes(&factor, length: Matrix3x3.size, index: index + 1)
    }
    public init(matrix: Matrix3x3) {
        self.matrix = matrix
    }
    public init(convolutionType: ConvolutionType) {
        self.init(matrix: convolutionType.matrix)
    }
    public mutating func updateConvolutionType(_ convolutionType: ConvolutionType) {
        self.matrix = convolutionType.matrix
    }
    public mutating func updateMatrix3x3(_ matrix: Matrix3x3) {
        self.matrix = matrix
    }
}
extension C7ConvolutionMatrix3x3.ConvolutionType {
    var matrix: Matrix3x3 {
        switch self {
        case .identity:
            return Matrix3x3.Kernel.identity
        case .edgedetect:
            return Matrix3x3.Kernel.edgedetect
        case .embossment:
            return Matrix3x3.Kernel.embossment
        case .embossment45:
            return Matrix3x3.Kernel.embossment45
        case .morphological:
            return Matrix3x3.Kernel.morphological
        case .sobel(let orientation):
            return Matrix3x3.Kernel.sobel(orientation)
        case .laplance(let iterations):
            return Matrix3x3.Kernel.laplance(iterations)
        case .sharpen(let iterations):
            return Matrix3x3.Kernel.sharpen(iterations)
        case .custom(let matrix3x3):
            return matrix3x3
        default:
            return Matrix3x3.Kernel.`default`
        }
    }
}

着色器

取像素点周边九个区域半径点像素,然后归一化处理,然后取出每个像素对应rgb,再进行卷积矩阵运算得到卷积之后的rgb值,生成新的像素颜色;

kernel void C7ConvolutionMatrix3x3(texture2d<half, access::write> outputTexture [[texture(0)]],
                                   texture2d<half, access::sample> inputTexture [[texture(1)]],
                                   constant float *pixel [[buffer(0)]],
                                   constant float3x3 *matrix3x3 [[buffer(1)]],
                                   uint2 grid [[thread_position_in_grid]]) {
    constexpr sampler quadSampler(mag_filter::linear, min_filter::linear);
    const float x = float(grid.x);
    const float y = float(grid.y);
    const float w = float(inputTexture.get_width());
    const float h = float(inputTexture.get_height());
    const float l = float(x - *pixel);
    const float r = float(x + *pixel);
    const float t = float(y - *pixel);
    const float b = float(y + *pixel);
    // Normalization
    const float2 m11Coordinate = float2(l / w, t / h);
    const float2 m12Coordinate = float2(x / w, t / h);
    const float2 m13Coordinate = float2(r / w, t / h);
    const float2 m21Coordinate = float2(l / w, y / h);
    const float2 m22Coordinate = float2(x / w, y / h);
    const float2 m23Coordinate = float2(r / w, y / h);
    const float2 m31Coordinate = float2(l / w, b / h);
    const float2 m32Coordinate = float2(x / w, b / h);
    const float2 m33Coordinate = float2(r / w, b / h);
    const half4 centerColor = inputTexture.sample(quadSampler, m22Coordinate);
    const half3 m11Color = inputTexture.sample(quadSampler, m11Coordinate).rgb;
    const half3 m12Color = inputTexture.sample(quadSampler, m12Coordinate).rgb;
    const half3 m13Color = inputTexture.sample(quadSampler, m13Coordinate).rgb;
    const half3 m21Color = inputTexture.sample(quadSampler, m21Coordinate).rgb;
    const half3 m22Color = centerColor.rgb;
    const half3 m23Color = inputTexture.sample(quadSampler, m23Coordinate).rgb;
    const half3 m31Color = inputTexture.sample(quadSampler, m31Coordinate).rgb;
    const half3 m32Color = inputTexture.sample(quadSampler, m32Coordinate).rgb;
    const half3 m33Color = inputTexture.sample(quadSampler, m33Coordinate).rgb;
    const float3x3 matrix = (*matrix3x3);
    half3 resultColor = half3(0.0h);
    resultColor += m11Color * (matrix[0][0]) + m12Color * (matrix[0][1]) + m13Color * (matrix[0][2]);
    resultColor += m21Color * (matrix[1][0]) + m22Color * (matrix[1][1]) + m23Color * (matrix[1][2]);
    resultColor += m31Color * (matrix[2][0]) + m32Color * (matrix[2][1]) + m33Color * (matrix[2][2]);
    const half4 outColor = half4(resultColor, centerColor.a);
    outputTexture.write(outColor, grid);
}


其他卷积核


extension Matrix3x3 {
    /// 常见 3x3 矩阵卷积内核,考线性代数时刻😪
    /// Common 3x3 matrix convolution kernel
    public struct Kernel { }
}
extension Matrix3x3.Kernel {
    /// 原始矩阵,空卷积核
    /// The original matrix, the empty convolution kernel
    public static let `default` = Matrix3x3(values: [
        0.0, 0.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 0.0, 0.0,
    ])
    public static let identity = Matrix3x3(values: [
        1.0, 0.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 0.0, 1.0,
    ])
    /// 边缘检测矩阵
    /// Edge detection matrix
    public static let edgedetect = Matrix3x3(values: [
        -1.0, -1.0, -1.0,
        -1.0,  8.0, -1.0,
        -1.0, -1.0, -1.0,
    ])
    /// 浮雕矩阵
    /// Anaglyph matrix
    public static let embossment = Matrix3x3(values: [
        -2.0, 0.0, 0.0,
         0.0, 1.0, 0.0,
         0.0, 0.0, 2.0,
    ])
    /// 45度的浮雕滤波器
    /// A 45 degree emboss filter
    public static let embossment45 = Matrix3x3(values: [
        -1.0, -1.0, 0.0,
        -1.0,  0.0, 1.0,
         0.0,  1.0, 1.0,
    ])
    /// 侵蚀矩阵
    /// Matrix erosion
    public static let morphological = Matrix3x3(values: [
        1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
    ])
    /// 拉普拉斯算子,边缘检测算子
    /// Laplace operator, edge detection operator
    public static func laplance(_ iterations: Float) -> Matrix3x3 {
        let xxx = iterations
        return Matrix3x3(values: [
             0.0, -1.0,  0.0,
            -1.0,  xxx, -1.0,
             0.0, -1.0,  0.0,
        ])
    }
    /// 锐化矩阵
    /// Sharpening matrix
    public static func sharpen(_ iterations: Float) -> Matrix3x3 {
        let cc = (8 * iterations + 1)
        let xx = (-iterations)
        return Matrix3x3(values: [
            xx, xx, xx,
            xx, cc, xx,
            xx, xx, xx,
        ])
    }
    /// Sobel矩阵图像边缘提取,求梯度比较常用
    /// Sobel matrix image edge extraction, gradient is more commonly used
    public static func sobel(_ orientation: Bool) -> Matrix3x3 {
        if orientation {
            return Matrix3x3(values: [
                -1.0, 0.0, 1.0,
                -2.0, 0.0, 2.0,
                -1.0, 0.0, 1.0,
            ])
        } else {
            return Matrix3x3(values: [
                -1.0, -2.0, -1.0,
                 0.0,  0.0,  0.0,
                 1.0,  2.0,  1.0,
            ])
        }
    }
    /// BT.601, which is the standard for SDTV.
    public static let to601 = Matrix3x3(values: [
        1.164,  1.164, 1.164,
        0.000, -0.392, 2.017,
        1.596, -0.813, 0.000,
    ])
    /// BT.601 full range (ref: http://www.equasys.de/colorconversion.html)
    public static let to601FullRange = Matrix3x3(values: [
        1.0,  1.000, 1.000,
        0.0, -0.343, 1.765,
        1.4, -0.711, 0.000,
    ])
    /// BT.709, which is the standard for HDTV.
    public static let to709 = Matrix3x3(values: [
        1.164,  1.164, 1.164,
        0.000, -0.213, 2.112,
        1.793, -0.533, 0.000,
    ])
}


效果图


常见核卷积图

边缘检测矩阵 浮雕矩阵 45度的浮雕滤波器

1.png

1.png

1.png

锐化矩阵 拉普拉斯算子 Sobel矩阵图像边缘提取

1.png

1.png

1.png


Harbeth功能清单


支持ios系统和macOS系统

支持运算符函数式操作

支持多种模式数据源 UIImage, CIImage, CGImage, CMSampleBuffer, CVPixelBuffer.

支持快速设计滤镜

支持合并多种滤镜效果

支持输出源的快速扩展

支持相机采集特效

支持视频添加滤镜特效

支持矩阵卷积

支持使用系统 MetalPerformanceShaders.

支持兼容 CoreImage.

滤镜部分大致分为以下几个模块:

Blend:图像融合技术

Blur:模糊效果

Pixel:图像的基本像素颜色处理

Effect:效果处理

Lookup:查找表过滤器

Matrix: 矩阵卷积滤波器

Shape:图像形状大小相关

Visual: 视觉动态特效

MPS: 系统 MetalPerformanceShaders.


最后


关于3x3矩阵卷积效果滤镜介绍与设计到此为止吧。

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

滤镜Demo地址,目前包含100+种滤镜,同时也支持CoreImage混合使用。

再附上一个开发加速库KJCategoriesDemo地址

再附上一个网络基础库RxNetworksDemo地址

喜欢的老板们可以点个星🌟,谢谢各位老板!!!✌️.

相关文章
|
存储 缓存 算法
哈希函数:保护数据完整性的关键
哈希函数:保护数据完整性的关键
|
PyTorch 算法框架/工具
Pytorch中最大池化层Maxpool的作用说明及实例使用(附代码)
Pytorch中最大池化层Maxpool的作用说明及实例使用(附代码)
1976 0
|
存储 资源调度 算法
Opencv(C++)系列学习---SIFT、SURF、ORB算子特征检测
Opencv(C++)系列学习---SIFT、SURF、ORB算子特征检测
1558 0
|
9月前
|
人工智能 IDE 数据可视化
【RuoYi-SpringBoot3-Pro】:将 AI 编程融入传统 java 开发
【RuoYi-SpringBoot3-Pro】将AI编程深度融入Java开发:基于Claude Code + Antigravity主力组合,集成openskills技能管理、OpenSpec需求规范工作流,支持智能创建/更新项目专属Skill,并实现IDEA与Antigravity一键切换,兼顾传统工程规范与AI提效。(239字)
1105 2
【RuoYi-SpringBoot3-Pro】:将 AI 编程融入传统 java 开发
|
4月前
|
算法 安全 前端开发
国密改造落地实战:用 OpenSSL 子进程透传,零成本支持 sm2/sm3/sm4
本文介绍yyzTools桌面工具如何通过“子进程透传算法名”实现国密(SM2/SM3/SM4)零编译改造:不修改主程序二进制,仅替换内置openssl.exe即可支持国密,一天内快速落地。兼顾升级便捷、审计透明与国密/国际算法统一,代价仅为单次计算性能损耗,适合等保、密评等低频高合规场景。
385 0
|
8月前
|
SQL 关系型数据库 MySQL
MySQL IN 里塞 10000 个值?90% 开发者都踩过的坑,底层原理 + 全场景解决方案一次讲透
本文深入剖析MySQL IN子句的底层执行逻辑,纠正常见误区(如“1000值硬限制”“IN=OR”),揭示大IN列表引发的性能、稳定性及安全风险,并提供分批查询、临时表JOIN、关联/EXISTS查询、流式查询四类场景化解决方案,附实测性能对比与生产避坑指南。
1236 4
|
缓存 监控 Java
《深入理解Spring》拦截器(Interceptor)——请求处理的艺术
Spring拦截器是Web开发中实现横切关注点的核心组件,基于AOP思想,可在请求处理前后执行日志记录、身份验证、权限控制等通用逻辑。相比Servlet过滤器,拦截器更贴近Spring容器,能访问Bean和上下文,适用于Controller级精细控制。通过实现`HandlerInterceptor`接口的`preHandle`、`postHandle`和`afterCompletion`方法,可灵活控制请求流程。结合配置类注册并设置路径匹配与执行顺序,实现高效复用与维护。常用于认证鉴权、性能监控、统一异常处理等场景,提升应用安全性与可维护性。
|
人工智能 算法 关系型数据库
AI编码不是梦:手把手教你指挥Agent开发需求
AI编码不是梦:手把手教你指挥Agent开发需求
4047 24
|
存储 数据采集 数据处理
Pandas与NumPy:Python数据处理的双剑合璧
Pandas与NumPy是Python数据科学的核心工具。NumPy以高效的多维数组支持数值计算,适用于大规模矩阵运算;Pandas则提供灵活的DataFrame结构,擅长处理表格型数据与缺失值。二者在性能与功能上各具优势,协同构建现代数据分析的技术基石。
1105 0