本案例的目的是理解如何用Metal实现虚假颜色效果滤镜,使用图像的亮度在两种用户指定的颜色之间进行混合;


Demo

  • HarbethDemo地址

实操代码

// 混合颜色
let filter = C7FalseColor.init(fristColor: .blue, secondColor: .green)// 方案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

效果对比图

  • 不同参数下颜色混合效果
蓝色~绿色 黄色~棕色 绿色~蓝色

实现原理

  • 过滤器

这款滤镜采用并行计算编码器设计.compute(kernel: "C7FalseColor")

对外开放参数

  • fristColor: 第一和第二种颜色分别指定了哪些颜色取代了图像的深色和浅色区域;
  • secondColor: 第二种颜色;
/// 使用图像的亮度在两种用户指定的颜色之间进行混合
/// Uses the luminance of the image to mix between two user-specified colors
public struct C7FalseColor: C7FilterProtocol, ComputeFiltering {/// The first and second colors specify what colors replace the dark and light areas of the image, respectively.public var fristColor: C7Color = .zeropublic var secondColor: C7Color = .zeropublic var modifier: Modifier {return .compute(kernel: "C7FalseColor")}public func setupSpecialFactors(for encoder: MTLCommandEncoder, index: Int) {guard let computeEncoder = encoder as? MTLComputeCommandEncoder else { return }var fristFactor = Vector3.init(color: fristColor).to_factor()computeEncoder.setBytes(&fristFactor, length: Vector3.size, index: index + 1)var secondFactor = Vector3(color: secondColor).to_factor()computeEncoder.setBytes(&secondFactor, length: Vector3.size, index: index + 2)}public init(fristColor: C7Color = .zero, secondColor: C7Color = .zero) {self.fristColor = fristColorself.secondColor = secondColor}
}
  • 着色器

计算出输入像素亮度点积dot(inColor.rgb, luminanceWeighting),然后再两种输入颜色当中混合mix(color1.rgb, color2.rgb, luminance)获取到rgb;

kernel void C7FalseColor(texture2d<half, access::write> outputTexture [[texture(0)]],texture2d<half, access::read> inputTexture [[texture(1)]],constant float3 *firstVector [[buffer(0)]],constant float3 *secondVector [[buffer(1)]],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 half3 color1 = half3(*firstVector);const half3 color2 = half3(*secondVector);const half4 outColor = half4(mix(half3(color1.rgb), half3(color2.rgb), half3(luminance)), inColor.a);outputTexture.write(outColor, grid);
}

Harbeth功能清单

最后