iOS小结(四) GPUImage加速图像处理

            在iOS中大量用到图像处理的app, 如果想要加速, 大体有三个办法可以选择:

  1.   Core Image framework
  2.   vImage, 在Accerlerate.framework中
  3.   GPUImage 第三方库
              GPUImage 是 BradLarson 写的开源库,主要提供了一些 filter 的 shader, 外包了一层与 iOS的 UIImage 和 CGImage 的输入输出,代码量较少,也比较好上手。

             用法也很简单,大体都是,先初始化一个filter,准备好输入, 输入输进filter, 导出输出。如果有参数的话再设定一下参数。

             先看一个最简单的灰度化的例子,输入输出都是 iOS 的 UIImage, 本篇的例子都是用objective c: 

+ (UIImage*) getGrayScaleImage : (UIImage*) srcImage {
    UIImage * filteredImage;
    GPUImageGrayscaleFilter *filter = [[GPUImageGrayscaleFilter alloc] init];
    filteredImage = [filter imageByFilteringImage:srcImage];
    return filteredImage;
}

          简单吧,这是一张图作为输入的,稍微复杂一点的,两张图作为输入的呢,比如alpha-blending:

+ (UIImage *)AlphaBlendingFiltering: (UIImage*) srcImage : (UIImage *) overImage : (CGFloat)filterMix {
    if (srcImage) {
        GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:srcImage];
        GPUImagePicture *overImageSource = [[GPUImagePicture alloc] initWithImage:overImage];
        
        GPUImageAlphaBlendFilter *filter = [[GPUImageAlphaBlendFilter alloc] init];
        filter.mix = filterMix;
        [stillImageSource addTarget:filter atTextureLocation:0];
        [overImageSource addTarget:filter atTextureLocation:1];
        [filter useNextFrameForImageCapture];
        
        [stillImageSource processImage];
        [overImageSource processImage];
        return [filter imageFromCurrentFramebufferWithOrientation:0];
    }
    else{
        NSLog(@"error in blending: srcImage = nil");
        return overImage;
    }
}

             关于什么是 alpha-blending,如果想进一步了解,可以 参照这个教程,讲的是 如何用纯像素操作做alpha-blending

             其实只是多了一步将输入图片转成GPUImagePicture类型,和设置参数,最后一步从filter这个工具箱中拿出结果图也可以用:

      filteredImage = [filter imageFromCurrentFramebuffer];
              我这里之所以用 withOrientation 是因为我的程序中在拍照之后,就有 fixOrientation 做了统一 Orientation 的工作,这一步已经将orientation 都设为 0 了, 所以我们这里是知道图片的 orientation 的。 (如果有人也遇到 拍照之后处理的照片自动旋转了90度等 orientation 问题, 可以参照这个解决方案)
              

             GPUImage 这个库里的其他的filter用法也很类似,而看看这些 filter 实际的源码,跟基本就是GLSL语言写的,也可以很方便的移植到 webGL 上。 源码可以从Github/GPUImage 上拉取下来看。

             至于为什么用GPUImage,GPUImage 和 其他两种 apple 提供的framework Core Image 和 Accelerate 有什么区别,下面两个回答是GPUImage的作者给出的:

             key difference between Core Image and GPUImage?   

             Another answer

             我当时是因为GPUImage开源,我能看到里面的是写的GL的shader,而且比较小巧方便。有人曾经比较过三者的性能,说vImage可能较快,有兴趣可以自己测一下。

你可能感兴趣的:(ios)