本案例的目的是理解如何用Metal實現海報畫效果濾鏡,主要就是改變顏色級別數量從而獲取到新的像素顏色;
Demo
實操代碼
// 濾鏡
let filter = C7Posterize.init(colorLevels: 2.3)
// 方案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
效果對比圖
- 不同參數下效果
colorLevels: 1.03 | colorLevels: 2.3 | colorLevels: 5.03 |
---|---|---|
實現原理
- 過濾器
這款濾鏡採用並行計算編碼器設計.compute(kernel: "C7Posterize")
,參數因子[colorLevels]
;
對外開放參數
-
colorLevels
: 減少圖像空間的顏色級別數量;
public struct C7Posterize: C7FilterProtocol {
public static let range: ParameterRange<Float, Self> = .init(min: 1.0, max: 255.0, value: 10.0)
/// The number of color levels to reduce the image space to.
/// This ranges from 1 to 256, with a default of 10
public var colorLevels: Float = range.value
public var modifier: Modifier {
return .compute(kernel: "C7Posterize")
}
public var factors: [Float] {
return [colorLevels]
}
public init(colorLevels: Float = range.value) {
self.colorLevels = colorLevels
}
}
- 着色器
對輸入像素x顏色級別數量再加上平均亮度half4(0.5h)
取整floor
,再除以顏色級別數量得到最終的像素顏色;
kernel void C7Posterize(texture2d<half, access::write> outputTexture [[texture(0)]],
texture2d<half, access::read> inputTexture [[texture(1)]],
constant float *colorLevelsPointer [[buffer(0)]],
uint2 grid [[thread_position_in_grid]]) {
const half4 inColor = inputTexture.read(grid);
const half colorLevels = half(*colorLevelsPointer);
const half4 outColor = floor((inColor * colorLevels) + half4(0.5h)) / colorLevels;
outputTexture.write(outColor, grid);
}
Harbeth功能清單
- 支持ios系統和macOS系統
- 支持運算符函數式操作
- 支持多種模式數據源 UIImage, CIImage, CGImage, CMSampleBuffer, CVPixelBuffer.
- 支持快速設計濾鏡
- 支持合併多種濾鏡效果
- 支持輸出源的快速擴展
- 支持相機採集特效
- 支持視頻添加濾鏡特效
- 支持矩陣卷積
- 支持使用系統 MetalPerformanceShaders.
- 支持兼容 CoreImage.
- 濾鏡部分大致分爲以下幾個模塊:
最後
- 慢慢再補充其他相關濾鏡,喜歡就給我點個星🌟吧。
-
濾鏡Demo地址,目前包含
100+
種濾鏡,同時也支持CoreImage混合使用。 - 再附上一個開發加速庫KJCategoriesDemo地址
- 再附上一個網絡基礎庫RxNetworksDemo地址
- 喜歡的老闆們可以點個星🌟,謝謝各位老闆!!!
✌️.