首页 > 解决方案 > 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
}

处理大约需要一秒钟。

这种将输出链接到过滤器输入的方式是最有效的吗?或更笼统地说:我可以做哪些性能优化?

标签: iosswiftperformancecifilter

解决方案


您应该使用 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因为创建它的成本很高,因为它保存并缓存了渲染图像所需的所有(金属)资源。


推荐阅读