本案例的目的是理解如何用Metal实现图像单色效果滤镜,将图像转换为单色版本,根据每个像素的亮度进行着色;


Demo

  • HarbethDemo地址

实操代码

// 去雾效果滤镜
let filter = C7Monochrome.init(intensity: 0.83, color: .blue)// 方案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

效果对比图

  • 不同参数下效果
intensity: 0.25, color: .blue intensity: 0.5, color: .blue intensity: 0.83, color: .blue
intensity: 0.5, color: .yellow intensity: 0.5, color: .red intensity: 0.5, color: .green

实现原理

  • 过滤器

这款滤镜采用并行计算编码器设计.compute(kernel: "C7Monochrome"),参数因子[intensity] + RGBAColor(color: color).toRGB()

对外开放参数

  • intensity: 特定颜色取代正常图像颜色的程度,从0.0到1.0,默认值为0.0;
  • color: 保留配色方案;
/// 将图像转换为单色版本,根据每个像素的亮度进行着色
public struct C7Monochrome: C7FilterProtocol {public static let range: ParameterRange<Float, Self> = .init(min: 0.0, max: 1.0, value: 0.0)/// The degree to which the specific color replaces the normal image color, from 0.0 to 1.0, with 0.0 as the default.@ZeroOneRange public var intensity: Float = range.value/// Keep the color schemepublic var color: C7Color = .zeropublic var modifier: Modifier {return .compute(kernel: "C7Monochrome")}public var factors: [Float] {return [intensity] + RGBAColor(color: color).toRGB()}public init(intensity: Float = range.value, color: C7Color = .zero) {self.intensity = intensityself.color = color}
}
  • 着色器

获取像素亮度值dot(inColor.rgb, luminanceWeighting),然后混合强度intensity原始像素和单色值三者获取新的像素颜色rgb;

kernel void C7Monochrome(texture2d<half, access::write> outputTexture [[texture(0)]],texture2d<half, access::read> inputTexture [[texture(1)]],constant float *intensity [[buffer(0)]],constant float *colorR [[buffer(1)]],constant float *colorG [[buffer(2)]],constant float *colorB [[buffer(3)]],uint2 grid [[thread_position_in_grid]]) {const half4 inColor = inputTexture.read(grid);const half3 luminanceWeighting = half3(0.2125, 0.7154, 0.0721);const half luminance = dot(inColor.rgb, luminanceWeighting);const half4 desat = half4(half3(luminance), 1.0h);const half r = desat.r < 0.5 ? (2.0 * desat.r * half(*colorR)) : (1.0 - 2.0 * (1.0 - desat.r) * (1.0 - half(*colorR)));const half g = desat.g < 0.5 ? (2.0 * desat.g * half(*colorG)) : (1.0 - 2.0 * (1.0 - desat.g) * (1.0 - half(*colorG)));const half b = desat.b < 0.5 ? (2.0 * desat.b * half(*colorB)) : (1.0 - 2.0 * (1.0 - desat.b) * (1.0 - half(*colorB)));const half4 outColor = half4(mix(inColor.rgb, half3(r, g, b), half(*intensity)), inColor.a);outputTexture.write(outColor, grid);
}

Harbeth功能清单

最后