ios - CIFilter 链的性能改进?
问题描述
在照片应用程序(无视频)中,我有许多内置和自定义的 Metal CIFilters 在一个类中链接在一起,就像这样(我省略了设置过滤器参数的行,而不是输入图像):
var colorControlsFilter = CIFilter(name: "CIColorControls")!
var highlightShadowFilter = CIFilter(name: "CIHighlightShadowAdjust")!
func filter(image data: Data) -> UIImage
{
var outputImage: CIImage?
let rawFilter = CIFilter(imageData: imageData, options: nil)
outputImage = rawFilter?.outputImage
colorControlsFilter.setValue(outputImage, forKey: kCIInputImageKey)
outputImage = colorControlsFilter.setValue.outputImage
highlightShadowFilter.setValue(outputImage, forKey: kCIInputImageKey)
outputImage = highlightShadowFilter.setValue.outputImage
...
...
if let ciImage = outputImage
{
return renderImage(ciImage: ciImage)
}
}
func renderImage(ciImage: CIImage) -> UIImage?
{
var outputImage: UIImage?
let size = ciImage.extent.size
UIGraphicsBeginImageContext(size)
if let context = UIGraphicsGetCurrentContext()
{
context.interpolationQuality = .high
context.setShouldAntialias(true)
let inputImage = UIImage(ciImage: ciImage)
inputImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
return outputImage
}
处理大约需要一秒钟。
这种将输出链接到过滤器输入的方式是最有效的吗?或更笼统地说:我可以做哪些性能优化?
解决方案
您应该使用 aCIContext
来渲染图像:
var context = CIContext() // create this once and re-use it for each image
func render(image ciImage: CIImage) -> UIImage? {
let cgImage = context.createCGImage(ciImage, from: ciImage.extent)
return cgImage.map(UIImage.init)
}
只创建一次很重要,CIContext
因为创建它的成本很高,因为它保存并缓存了渲染图像所需的所有(金属)资源。
推荐阅读
- javascript - 如果在 [未定义] 上进行测试
- c# - C# 强制静态字段
- apache-kafka - apache kafka partiton log下Position的值是什么?
- c# - Unity 3D 布料拉伸
- haskell - Karatsuba 算法的分治法
- java - 以编程方式设置锁定超时 Spring Boot JPA
- python - pandas df 在列中选择唯一值并为每个唯一值创建单独的 df
- scala - Scala 错误:类型不匹配;找到:java.util.List[?0] 需要:java.util.List[B]
- c++ - 连接2 QTableWidget中的行选择
- r - 使用 R 从 ODS 文件中导入多个选项卡,同时在每个选项卡中指定精确范围