如何使用Core Image Framework为iOS创建简单的自定义过滤器?

Mat*_*der 5 image-processing core-image ios

我想在我的应用程序中使用自定义过滤器.现在我知道我需要使用Core Image框架,但我不确定这是正确的方法.Core Image框架用于Mac OSiOS 5.0 - 我不确定它是否可用于自定义CIFilter效果.你能帮我解决这个问题吗?谢谢大家!

Bra*_*son 21

正如Adam所说,目前iOS上的Core Image不支持像旧版Mac实现那样的自定义内核.这限制了您可以使用框架做某种现有过滤器的组合.

(更新:2012年2月13日)

出于这个原因,我为iOS创建了一个名为GPUImage的开源框架,它允许您使用OpenGL ES 2.0片段着色器创建应用于图像和视频的自定义过滤器.我在关于该主题的帖子中详细描述了该框架的运作方式.基本上,您可以提供自己的自定义OpenGL着色语言(GLSL)片段着色器来创建自定义过滤器,然后针对静态图像或实时视频运行该过滤器.该框架与支持OpenGL ES 2.0的所有iOS设备兼容,并且可以创建面向iOS 4.0的应用程序.

例如,您可以使用以下代码设置实时视频的过滤:

GPUImageVideoCamera *videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
GPUImageFilter *customFilter = [[GPUImageFilter alloc] initWithFragmentShaderFromFile:@"CustomShader"];
GPUImageView *filteredVideoView = [[GPUImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, viewWidth, viewHeight)];

// Add the view somewhere so it's visible

[videoCamera addTarget:thresholdFilter];
[customFilter addTarget:filteredVideoView];

[videoCamera startCameraCapture];
Run Code Online (Sandbox Code Playgroud)

作为定义过滤器的自定义片段着色器程序的示例,以下应用棕褐色调效果:

varying highp vec2 textureCoordinate;

uniform sampler2D inputImageTexture;

void main()
{
    lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
    lowp vec4 outputColor;
    outputColor.r = (textureColor.r * 0.393) + (textureColor.g * 0.769) + (textureColor.b * 0.189);
    outputColor.g = (textureColor.r * 0.349) + (textureColor.g * 0.686) + (textureColor.b * 0.168);    
    outputColor.b = (textureColor.r * 0.272) + (textureColor.g * 0.534) + (textureColor.b * 0.131);

    gl_FragColor = outputColor;
}
Run Code Online (Sandbox Code Playgroud)

用于在Mac上编写自定义Core Image内核的语言与GLSL非常相似.事实上,你可以在桌面Core Image中做一些你无法做到的事情,因为Core Image的内核语言缺少GLSL所拥有的一些东西(比如分支).


Tom*_*Bąk 9

原始接受的答案已折旧.从iOS 8开始,您可以为过滤器创建自定义内核.您可以在以下位置找到更多相关信息:


Ada*_*ght 5

过时的

您还无法在iOS中创建自己的自定义内核/过滤器.请参阅http://developer.apple.com/library/mac/#documentation/graphicsimaging/Conceptual/CoreImaging/ci_intro/ci_intro.html,具体如下:

尽管此文档包含在参考库中,但尚未针对iOS 5.0进行详细更新.即将发布的修订版将详细介绍iOS上Core Image的差异.特别是,关键的区别在于iOS上的Core Image不包括创建自定义图像过滤器的功能.

(Bolding矿)

  • iOS 8添加了自定义CoreImage过滤器(即自定义`CIKernel`). (2认同)