「这是我参与2022首次更文挑战的第15天,活动详情查看:2022首次更文挑战」
本文正在参加「金石计划 . 瓜分6万现金大奖」
本案例的目的是理解如何用Metal实现图像4维向量颜色效果滤镜,通过对像素点颜色进行4维向量叠加运算得到新的像素点;
Demo
实操代码
// 暖色系
let filter = C7ColorVector4(vector: Vector4.Color.warm)
// 方案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
效果对比图
origin: 原始 | warm: 暖色系 | cool_tone: 冷色系 |
---|---|---|
实现原理
- 过滤器
这款滤镜采用并行计算编码器设计.compute(kernel: "C7ColorVector4")
对外开放参数
vector
: 4维向量;
/// 四维向量颜色
public struct C7ColorVector4: C7FilterProtocol {
public var vector: Vector4
public var modifier: Modifier {
return .compute(kernel: "C7ColorVector4")
}
public func setupSpecialFactors(for encoder: MTLCommandEncoder, index: Int) {
guard let computeEncoder = encoder as? MTLComputeCommandEncoder else { return }
var factor = vector.to_factor()
computeEncoder.setBytes(&factor, length: Vector4.size, index: index + 1)
}
public init(vector: Vector4) {
self.vector = vector
}
}
- 着色器
对像素点颜色进行4维向量叠加运算inColor + half4(*vector)
;
kernel void C7ColorVector4(texture2d<half, access::write> outputTexture [[texture(0)]],
texture2d<half, access::read> inputTexture [[texture(1)]],
constant float4 *vector [[buffer(0)]],
uint2 grid [[thread_position_in_grid]]) {
const half4 inColor = inputTexture.read(grid);
const half4 outColor = inColor + half4(*vector);
outputTexture.write(outColor, grid);
}
4维向量
- 部分4维向量
extension Vector4 {
public struct Color { }
}
extension Vector4.Color {
/// 原始
public static let origin = Vector4(values: [0.0, 0.0, 0.0, 0.0])
/// 暖色,将rgb通道的颜色添加相应的红/绿色值
/// Warm color, add the color of the rgb channel to the corresponding red/green value.
public static let warm = Vector4(values: [0.3, 0.3, 0.0, 0.0])
/// 冷色,将rgb通道的颜色添加相应的蓝色值
/// Cold color, add the color of the rgb channel to the corresponding blue value.
public static let cool_tone = Vector4(values: [0.0, 0.0, 0.3, 0.0])
}
最后
- 慢慢再补充其他相关滤镜,喜欢就给我点个星🌟吧。
✌️.