ios - 我的自定义图像过滤器非常慢。如何在没有 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)
}
}
解决方案
推荐阅读
- java - 从 jsonobj 中提取数据的 Java Stream 表示
- r - 使用 stat_summary 在箱线图上标注中线
- google-cloud-platform - 如何让 Google Cloud Build 在 VPC 边界内工作?
- pythonanywhere - 如何使用 Python Flask 上传照片并将其保存到网站中
- python - 在更新中隐藏特定字段,但在创建中不隐藏
- xml - 在 Apache NiFi 的 ExecuteScript 处理器中缓存文件内容
- javascript - 将鼠标图标更改为“等待”,无论它在哪里
- python - 意外的 Python 解释器输出
- c# - ASP.NET 和 Visual Studio 2019:如果 Web.config 中有 configSource,如何设置 Web.Debug 和 Web.Release?
- video-streaming - 有没有办法使用 VLC 从网络摄像头流式传输原始 YUY2?(错误:无法创建分包器输出(YUY2))