本案例的目的是理解如何用Metal實現去霧效果濾鏡,類似於UV過濾器;
Demo
實操代碼
// 去霧效果濾鏡
let filter = C7Haze.init(distance: 0.5, slope: 0.5)
// 方案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
效果對比圖
- 不同參數下效果
distance: 0.25, slope: 0.25 | distance: 0.25, slope: 0.5 | distance: 0.4, slope: 0.5 |
---|---|---|
實現原理
- 過濾器
這款濾鏡採用並行計算編碼器設計.compute(kernel: "C7Haze")
,參數因子[distance, slope]
;
對外開放參數
-
distance
: 應用顏色的強度; -
slope
: 顏色變化量;
/// 去霧,類似於UV過濾器
public struct C7Haze: C7FilterProtocol {
/// Strength of the color applied.
public var distance: Float = 0
/// Amount of color change.
public var slope: Float = 0
public var modifier: Modifier {
return .compute(kernel: "C7Haze")
}
public var factors: [Float] {
return [distance, slope]
}
public init(distance: Float = 0, slope: Float = 0) {
self.distance = distance
self.slope = slope
}
}
- 着色器
歸一化y乘以顏色變化量,加上強度,得到像素顏色(inColor - dd * white) / (1.0h - dd)
;
kernel void C7Haze(texture2d<half, access::write> outputTexture [[texture(0)]],
texture2d<half, access::read> inputTexture [[texture(1)]],
constant float *hazeDistance [[buffer(0)]],
constant float *slope [[buffer(1)]],
uint2 grid [[thread_position_in_grid]]) {
const half4 inColor = inputTexture.read(grid);
const half4 white = half4(1.0h);
const half dd = half(grid.y) / half(inputTexture.get_height()) * half(*slope) + half(*hazeDistance);
const half4 outColor = half4((inColor - dd * white) / (1.0h - dd));
outputTexture.write(outColor, grid);
}
Harbeth功能清單
- 支持ios系統和macOS系統
- 支持運算符函數式操作
- 支持多種模式數據源 UIImage, CIImage, CGImage, CMSampleBuffer, CVPixelBuffer.
- 支持快速設計濾鏡
- 支持合併多種濾鏡效果
- 支持輸出源的快速擴展
- 支持相機採集特效
- 支持視頻添加濾鏡特效
- 支持矩陣卷積
- 支持使用系統 MetalPerformanceShaders.
- 支持兼容 CoreImage.
- 濾鏡部分大致分爲以下幾個模塊:
最後
- 慢慢再補充其他相關濾鏡,喜歡就給我點個星🌟吧。
-
濾鏡Demo地址,目前包含
100+
種濾鏡,同時也支持CoreImage混合使用。 - 再附上一個開發加速庫KJCategoriesDemo地址
- 再附上一個網絡基礎庫RxNetworksDemo地址
- 喜歡的老闆們可以點個星🌟,謝謝各位老闆!!!
✌️.