首页 > 解决方案 > 我的自定义图像过滤器非常慢。如何在没有 Accelerate 的情况下使其更快?

问题描述

这只是我逐像素降低图像亮度的测试代码。然而,处理图像需要 2 - 3 秒。

我不想使用内置的 CI 过滤器。

如何在不使用 Accelerate 的情况下使其更快?因为它对我来说太复杂了。

这是我的整个图像过滤器代码

func applyFilter(_ filter: Filter, to image: UIImage) -> UIImage? {
    //SETUP
    guard let cgImage = image.cgImage else { return nil }
    
    // Redraw image for correct pixel format
    var colorSpace = CGColorSpaceCreateDeviceRGB()
    
    var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
    bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
    
    let width = Int(image.size.width)
    let height = Int(image.size.height)
    var bytesPerRow = width * 4
    
    let imageData = UnsafeMutablePointer<Pixel>.allocate(capacity: width * height)
    
    guard let imageContext = CGContext(
        data: imageData,
        width: width,
        height: height,
        bitsPerComponent: 8,
        bytesPerRow: bytesPerRow,
        space: colorSpace,
        bitmapInfo: bitmapInfo
    ) else { return nil }
    
    
    

绘制新图像:

    imageContext.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
    
    let pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height)

循环遍历像素并修改 RGB 值:

    for y in 0..<height {
        for x in 0..<width {
            let index = y * width + x
            var pixel = pixels[index]
         
            

            switch filter {
        
            case .dominant:

                pixel.red /= 2
                pixel.blue /= 2
                pixel.green /= 2

            }

            pixels[index] = pixel
            
        }
    }
   
    

一些配置:

    colorSpace = CGColorSpaceCreateDeviceRGB()
    bitmapInfo = CGBitmapInfo.byteOrder32Big.rawValue
    bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
    
    bytesPerRow = width * 4
    
    guard let context = CGContext(
        data: pixels.baseAddress,
        width: width,
        height: height,
        bitsPerComponent: 8,
        bytesPerRow: bytesPerRow,
        space: colorSpace,
        bitmapInfo: bitmapInfo,
        releaseCallback: nil,
        releaseInfo: nil
    ) else { return nil }
    
    guard let newCGImage = context.makeImage() else { return nil }
    return UIImage(cgImage: newCGImage)
}
}

标签: iosswiftimageaccelerate

解决方案


推荐阅读