CoreImage-1

概论

Core Image 是 Apple 用来最大化利用其所运行之上的硬件的。每个滤镜实际上的实现,即内核,是由一个 GLSL (即 OpenGL 的着色语言) 的子集(CIKL)来书写的。当多个滤镜连接成一个滤镜图表,Core Image 便把内核串在一起来构建一个可在 GPU 上运行的高效程序。(可以选择使用 CPU 或者 GPU)

CIFilter 处理

CIImage ~ UIImage 经过CIFilter 处理后的输出是 CIImage,可以挂载 CIContext 进行输出和转换,但是是在 CPU上; 我们可以挂载在 GPU上进行加速处理( EAGLContext)

  • 函数式组合滤镜
  • 自定义 CIFilter (CIkernel)

分类

  • CIColorKernel:用于处理色值变化的 Filter。
  • CIWarpKernel:用于处理形变的 Filter。
  • CIKernel:通用。

查看系统提供支持的滤镜集合:

NSArray<NSString *> *filterNames = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];

基础使用

CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
[filter setValue:inputImage  forKey:kCIInputImageKey];
[filter setValue:@40 forKey:@"inputScale"];
CIImage *outImage = [filter valueForKey:kCIOutputImageKey];
CIContext *context = [CIContext contextWithOptions:nil]; //
CGImageRef cgImage = [context createCGImage:outImage fromRect:[inputImage extent]];
UIImage *showImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);

滤镜链

CIContext有两种初始化方法,分别对应GPU和CPU
(1)创建基于GPU的CIContext对象:
    context = [CIContext contextWithOptions: nil];
(2)创建基于CPU的CIContext对象
    context = [CIContext contextWithOptions: [NSDictionary dictionaryWithObject:    [NSNumber numberWithBool:YES]
    forKey:kCIContextUseSoftwareRenderer]];

CIContext 是多线程共用的,这样创建 output UIImage 的时候就不需要进行内省的,避免资源浪费。

imageWithCIImage 会内部创建 CIContext 进行绘制。

指定使用 GPU 可以使用openGL 和 Metal 进行渲染。

CPU is still what will give you the best fidelity where as the GPU will give you the best performance.

利用实时渲染的特效,而不是每次操作都产生一个 UIImage,然后再设置到视图上。

// 实时渲染
[self.pixellateFilter setValue:@(sender.value) forKey:@"inputRadius"];

[self.context drawImage:_pixellateFilter.outputImage inRect:_targetBounds  fromRect:_inputImage.extent];
[self.glkView.context presentRenderbuffer:GL_RENDERBUFFER];

创建 context,那么它内部的渲染器会根据设备最优选择:依次为 Metal、OpenGLES、CoreGraphics。 ps: 模拟器不支持 Metal。

CoreImage && GPUImage

  1. 支持对原生 RAW 格式图片的处理。支持对大图进行处理。
  2. 自动增强图像效果,会分析图像的直方图,图像属性,脸部区域,然后通过一组滤镜来改善图像效果。
  3. 支持图像识别功能,人脸识别,条形码,文本等。
  4. 与 Metal SpriteKit,SceneKit,Core Animation 结合。

CoreImage and Metal

CIKL 自定义效果实现
(埋坑)

CoreImage and Vision

Vision Framework 是计算机视觉的高级框架。
Vision WWDC 2017

搭配组合进行效果处理的方式

  1. 预处理前处理 (裁剪,旋转,灰度等)
  2. 识别后进行分发处理 (识别到人脸后做逻辑处理 CI…)

对于校准和稳定性的处理

  • face detection
  • 矩形、barcode 、text detection

参考

Core Image介绍

自定义滤镜参考

Core Image Filter Reference

Core Image Video