欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《音视频直播------GPUImage》

程序员文章站 2022-06-10 10:44:04
...

美颜滤镜效果

GPUImage的介绍

  • GPUImage 是一个开源的基于GPU的图片或视频的处理框架,其本身内置了多达120多种常见的滤镜效果
  • GPUImage是利用GPU,使在图片和视频上应用不同的效果和滤镜变得非常的容易,同时它还拥有出色的性能,并且它的性能要比苹果内置的相关APIs出色

高斯模糊(毛玻璃)效果

  • 在iOS总实现毛玻璃效果方式有很多
    • UIToolBar本身有毛玻璃效果
    • iOS8之后UIVisualEffectView直接创建毛玻璃View
    • 系统CoreImage框架中直接修改图片
    • GPUImage框架给图片添加一层滤镜
  • 实现思路
    • 获取要修改成毛玻璃的图片
    • 给图片添加滤镜
    • 生成新的图片
  • 实现代码
  •  fileprivate func generateBlurImage(_ sourceImage : UIImage) -> UIImage {
            // 1.创建用于处理单张图片(类似于美图秀秀中打开相册中的图片进行处理)
            let processView = GPUImagePicture(image: sourceImage)
    
            // 2.创建滤镜
            let blurFilter = GPUImageGaussianBlurFilter()
            // 纹理大小
            blurFilter.texelSpacingMultiplier = 2.0
            blurFilter.blurRadiusInPixels = 5.0
            processView?.addTarget(blurFilter)
    
            // 3.处理图像
            blurFilter.useNextFrameForImageCapture()
            processView?.processImage()
    
            // 4.获取最新的图像
            return blurFilter.imageFromCurrentFramebuffer()
        }
    


其他滤镜效果

为多个target添加依赖库

  • 单个target
  • platform :ios, '8.0'
    use_frameworks!
    target 'targetName' do
        pod 'GPUImage'
    end
  • 多个target依赖相同的库(Ruby语法)
  • platform :ios, '9.0'
    use_frameworks!
    
    targetsArray = ['01-GPUImage毛玻璃', '02-GPUImage其他滤镜']
    
    targetsArray.each do |t|
        target t do
            pod 'GPUImage'
        end
    end
  • 不同target依赖不同的库
  • platform :ios, '8.0'
    use_frameworks!
    target 'targetName1' do
        pod 'Alamofire'
    end
    
    target 'targetName2' do
        pod 'Alamofire'
        pod 'Kingfisher'
    end

#

  • 常见滤镜
  • #pragma mark - 调整颜色 Handle Color
    
        #import "GPUImageBrightnessFilter.h"                //亮度
        #import "GPUImageExposureFilter.h"                  //曝光
        #import "GPUImageContrastFilter.h"                  //对比度
        #import "GPUImageSaturationFilter.h"                //饱和度
        #import "GPUImageGammaFilter.h"                     //伽马线
        #import "GPUImageColorInvertFilter.h"               //反色
        #import "GPUImageSepiaFilter.h"                     //褐色(怀旧)
        #import "GPUImageLevelsFilter.h"                    //色阶
        #import "GPUImageGrayscaleFilter.h"                 //灰度
        #import "GPUImageHistogramFilter.h"                 //色彩直方图,显示在图片上
        #import "GPUImageHistogramGenerator.h"              //色彩直方图
        #import "GPUImageRGBFilter.h"                       //RGB
        #import "GPUImageToneCurveFilter.h"                 //色调曲线
        #import "GPUImageMonochromeFilter.h"                //单色
        #import "GPUImageOpacityFilter.h"                   //不透明度
        #import "GPUImageHighlightShadowFilter.h"           //提亮阴影
        #import "GPUImageFalseColorFilter.h"                //色彩替换(替换亮部和暗部色彩)
        #import "GPUImageHueFilter.h"                       //色度
        #import "GPUImageChromaKeyFilter.h"                 //色度键
        #import "GPUImageWhiteBalanceFilter.h"              //白平横
        #import "GPUImageAverageColor.h"                    //像素平均色值
        #import "GPUImageSolidColorGenerator.h"             //纯色
        #import "GPUImageLuminosity.h"                      //亮度平均
        #import "GPUImageAverageLuminanceThresholdFilter.h" //像素色值亮度平均,图像黑白(有类似漫画效果)
    
        #import "GPUImageLookupFilter.h"                    //lookup 色彩调整
        #import "GPUImageAmatorkaFilter.h"                  //Amatorka lookup
        #import "GPUImageMissEtikateFilter.h"               //MissEtikate lookup
        #import "GPUImageSoftEleganceFilter.h"              //SoftElegance lookup
    
        #pragma mark - 图像处理 Handle Image
    
        #import "GPUImageCrosshairGenerator.h"              //十字
        #import "GPUImageLineGenerator.h"                   //线条
    
        #import "GPUImageTransformFilter.h"                 //形状变化
        #import "GPUImageCropFilter.h"                      //剪裁
        #import "GPUImageSharpenFilter.h"                   //锐化
        #import "GPUImageUnsharpMaskFilter.h"               //反遮罩锐化
    
        #import "GPUImageFastBlurFilter.h"                  //模糊
        #import "GPUImageGaussianBlurFilter.h"              //高斯模糊
        #import "GPUImageGaussianSelectiveBlurFilter.h"     //高斯模糊,选择部分清晰
        #import "GPUImageBoxBlurFilter.h"                   //盒状模糊
        #import "GPUImageTiltShiftFilter.h"                 //条纹模糊,中间清晰,上下两端模糊
        #import "GPUImageMedianFilter.h"                    //中间值,有种稍微模糊边缘的效果
        #import "GPUImageBilateralFilter.h"                 //双边模糊
        #import "GPUImageErosionFilter.h"                   //侵蚀边缘模糊,变黑白
        #import "GPUImageRGBErosionFilter.h"                //RGB侵蚀边缘模糊,有色彩
        #import "GPUImageDilationFilter.h"                  //扩展边缘模糊,变黑白
        #import "GPUImageRGBDilationFilter.h"               //RGB扩展边缘模糊,有色彩
        #import "GPUImageOpeningFilter.h"                   //黑白色调模糊
        #import "GPUImageRGBOpeningFilter.h"                //彩色模糊
        #import "GPUImageClosingFilter.h"                   //黑白色调模糊,暗色会被提亮
        #import "GPUImageRGBClosingFilter.h"                //彩色模糊,暗色会被提亮
        #import "GPUImageLanczosResamplingFilter.h"         //Lanczos重取样,模糊效果
        #import "GPUImageNonMaximumSuppressionFilter.h"     //非最大抑制,只显示亮度最高的像素,其他为黑
        #import "GPUImageThresholdedNonMaximumSuppressionFilter.h" //与上相比,像素丢失更多
    
        #import "GPUImageSobelEdgeDetectionFilter.h"        //Sobel边缘检测算法(白边,黑内容,有点漫画的反色效果)
        #import "GPUImageCannyEdgeDetectionFilter.h"        //Canny边缘检测算法(比上更强烈的黑白对比度)
        #import "GPUImageThresholdEdgeDetectionFilter.h"    //阈值边缘检测(效果与上差别不大)
        #import "GPUImagePrewittEdgeDetectionFilter.h"      //普瑞维特(Prewitt)边缘检测(效果与Sobel差不多,貌似更平滑)
        #import "GPUImageXYDerivativeFilter.h"              //XYDerivative边缘检测,画面以蓝色为主,绿色为边缘,带彩色
        #import "GPUImageHarrisCornerDetectionFilter.h"     //Harris角点检测,会有绿色小十字显示在图片角点处
        #import "GPUImageNobleCornerDetectionFilter.h"      //Noble角点检测,检测点更多
        #import "GPUImageShiTomasiFeatureDetectionFilter.h" //ShiTomasi角点检测,与上差别不大
        #import "GPUImageMotionDetector.h"                  //动作检测
        #import "GPUImageHoughTransformLineDetector.h"      //线条检测
        #import "GPUImageParallelCoordinateLineTransformFilter.h" //平行线检测
    
        #import "GPUImageLocalBinaryPatternFilter.h"        //图像黑白化,并有大量噪点
    
        #import "GPUImageLowPassFilter.h"                   //用于图像加亮
        #import "GPUImageHighPassFilter.h"                  //图像低于某值时显示为黑
    
        #pragma mark - 视觉效果 Visual Effect
    
        #import "GPUImageSketchFilter.h"                    //素描
        #import "GPUImageThresholdSketchFilter.h"           //阀值素描,形成有噪点的素描
        #import "GPUImageToonFilter.h"                      //卡通效果(黑色粗线描边)
        #import "GPUImageSmoothToonFilter.h"                //相比上面的效果更细腻,上面是粗旷的画风
        #import "GPUImageKuwaharaFilter.h"                  //桑原(Kuwahara)滤波,水粉画的模糊效果;处理时间比较长,慎用
    
        #import "GPUImageMosaicFilter.h"                    //黑白马赛克
        #import "GPUImagePixellateFilter.h"                 //像素化
        #import "GPUImagePolarPixellateFilter.h"            //同心圆像素化
        #import "GPUImageCrosshatchFilter.h"                //交叉线阴影,形成黑白网状画面
        #import "GPUImageColorPackingFilter.h"              //色彩丢失,模糊(类似监控摄像效果)
    
        #import "GPUImageVignetteFilter.h"                  //晕影,形成黑色圆形边缘,突出中间图像的效果
        #import "GPUImageSwirlFilter.h"                     //漩涡,中间形成卷曲的画面
        #import "GPUImageBulgeDistortionFilter.h"           //凸起失真,鱼眼效果
        #import "GPUImagePinchDistortionFilter.h"           //收缩失真,凹面镜
        #import "GPUImageStretchDistortionFilter.h"         //伸展失真,哈哈镜
        #import "GPUImageGlassSphereFilter.h"               //水晶球效果
        #import "GPUImageSphereRefractionFilter.h"          //球形折射,图形倒立
    
        #import "GPUImagePosterizeFilter.h"                 //色调分离,形成噪点效果
        #import "GPUImageCGAColorspaceFilter.h"             //CGA色彩滤镜,形成黑、浅蓝、紫色块的画面
        #import "GPUImagePerlinNoiseFilter.h"               //柏林噪点,花边噪点
        #import "GPUImage3x3ConvolutionFilter.h"            //3x3卷积,高亮大色块变黑,加亮边缘、线条等
        #import "GPUImageEmbossFilter.h"                    //浮雕效果,带有点3d的感觉
        #import "GPUImagePolkaDotFilter.h"                  //像素圆点花样
        #import "GPUImageHalftoneFilter.h"                  //点染,图像黑白化,由黑点构成原图的大致图形
    
        #pragma mark - 混合模式 Blend
    
        #import "GPUImageMultiplyBlendFilter.h"             //通常用于创建阴影和深度效果
        #import "GPUImageNormalBlendFilter.h"               //正常
        #import "GPUImageAlphaBlendFilter.h"                //透明混合,通常用于在背景上应用前景的透明度
        #import "GPUImageDissolveBlendFilter.h"             //溶解
        #import "GPUImageOverlayBlendFilter.h"              //叠加,通常用于创建阴影效果
        #import "GPUImageDarkenBlendFilter.h"               //加深混合,通常用于重叠类型
        #import "GPUImageLightenBlendFilter.h"              //减淡混合,通常用于重叠类型
        #import "GPUImageSourceOverBlendFilter.h"           //源混合
        #import "GPUImageColorBurnBlendFilter.h"            //色彩加深混合
        #import "GPUImageColorDodgeBlendFilter.h"           //色彩减淡混合
        #import "GPUImageScreenBlendFilter.h"               //屏幕包裹,通常用于创建亮点和镜头眩光
        #import "GPUImageExclusionBlendFilter.h"            //排除混合
        #import "GPUImageDifferenceBlendFilter.h"           //差异混合,通常用于创建更多变动的颜色
        #import "GPUImageSubtractBlendFilter.h"             //差值混合,通常用于创建两个图像之间的动画变暗模糊效果
        #import "GPUImageHardLightBlendFilter.h"            //强光混合,通常用于创建阴影效果
        #import "GPUImageSoftLightBlendFilter.h"            //柔光混合
        #import "GPUImageChromaKeyBlendFilter.h"            //色度键混合
        #import "GPUImageMaskFilter.h"                      //遮罩混合
        #import "GPUImageHazeFilter.h"                      //朦胧加暗
        #import "GPUImageLuminanceThresholdFilter.h"        //亮度阈
        #import "GPUImageAdaptiveThresholdFilter.h"         //自适应阈值
        #import "GPUImageAddBlendFilter.h"                  //通常用于创建两个图像之间的动画变亮模糊效果
        #import "GPUImageDivideBlendFilter.h"               //通常用于创建两个图像之间的动画变暗模糊效果


GPUImage美颜相机

  • GPUImageStillCamera用于拍摄当前手机的画面, 但是通常不会用实时视频的录制(使用另外一个), 主要用户拍摄某一个画面, 并且保存(显示)图片
  • GPUImageStillCamera->GPUImageFilter->GPUImageView 这样,摄像机转到滤镜再转到view上显示出来.
  • //可以理解为设备
    GPUImageStillCamera* imageCamera;
    //filter滤镜
    GPUImageFilter* filter;
    //显示出来的view
    GPUImageView* iv;
  • sessionPreset参数设置

  • class ViewController: UIViewController {
    
        @IBOutlet var imageView : UIImageView!
        fileprivate var stillCamera : GPUImageStillCamera?
        fileprivate var filter : GPUImageBrightnessFilter!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // 1.创建相机
            stillCamera = GPUImageStillCamera(sessionPreset: AVCaptureSessionPreset640x480, cameraPosition: .front)
            stillCamera?.outputImageOrientation = .portrait
    
            // 2.创建滤镜
            filter = GPUImageBrightnessFilter()
            filter.brightness = 0.3
            stillCamera?.addTarget(filter)
    
            // 3.创建显示实时画面的View
            let showView = GPUImageView(frame: view.bounds)
            view.insertSubview(showView, at: 0)
            filter.addTarget(showView)
        }
    
        @IBAction func rotateCamera() {
            stillCamera?.startCapture()
        }
    
        @IBAction func start() {
            stillCamera?.rotateCamera()
        }
    
        @IBAction func stop() {
            stillCamera?.capturePhotoAsImageProcessedUp(toFilter: filter, withCompletionHandler: { (image :  UIImage?, error : Error?) in
                UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
                self.stillCamera?.stopCapture()
            })
        }
    }

    GPUImage滤镜效果(滤镜基本上都有属性可以设置,属性值设置的不同,滤镜效果不同)

    1、GPUImageSepiaFilter ,怀旧、褐色滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    2、GPUImageHalftoneFilter ,中间色调、黑白滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    3、GPUImageEmbossFilter, 浮雕滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    4、GPUImageToonFilter ,卡通滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    5、GPUImageSketchFilter  ,素描滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    6、GPUImageZoomBlurFilter ,放缩毛玻璃滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    7、GPUImageWhiteBalanceFilter,白平衡滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    8、GPUImageVignetteFilter,晕映滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    9、GPUImageTransformFilter,旋转滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    10、GPUImageSwirlFilter,螺旋滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    11、GPUImageStretchDistortionFilter,拉伸滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    12、GPUImageSphereRefractionFilter,球面滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    13、GPUImageSharpenFilter,尖锐滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    14、GPUImageSaturationFilter,饱和度滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    15、GPUImageRGBFilter,rgb滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    16、GPUImagePosterizeFilter,色调分离滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    17、GPUImagePolarPixellateFilter,边缘像素滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    18、GPUImagePixellatePositionFilter,局部像素化(马赛克)滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    19、GPUImagePixellateFilter,像素化(马赛克)滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    20、GPUImagePinchDistortionFilter,拉伸滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    21、GPUImageOpacityFilter,透明滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    22、GPUImageMotionBlurFilter,单色模糊滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    23、GPUImageMonochromeFilter,单色滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    24、GPUImageLuminanceThresholdFilter,黑白灰度滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    25、GPUImageLuminanceRangeFilter,灰度差值滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    26、GPUImageLevelsFilter,色阶滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    27、GPUImageKuwaharaRadius3Filter,叠原滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    28、GPUImageHueFilter,色调滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    29、GPUImageHighlightShadowFilter,高光阴影滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    30、GPUImageHazeFilter,朦胧滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    31、GPUImageGrayscaleFilter,黑白(灰度)滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    32、GPUImageGammaFilter,灰度系数滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    33、GPUImageFalseColorFilter,人工换色滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    34、GPUImageExposureFilter,曝光度滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    35、GPUImageDirectionalNonMaximumSuppressionFilter,定向抑制滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    36、GPUImageCrosshatchFilter,交叉阴影滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    37、GPUImageContrastFilter,对比度滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    38、GPUImageColorPackingFilter,彩色包装滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    39、GPUImageColorInvertFilter,反色滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    40、GPUImageChromaKeyFilter,色键滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    41、GPUImageCGAColorspaceFilter,CGA色彩滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    42、GPUImageBulgeDistortionFilter,凸镜滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    43、GPUImageBrightnessFilter,亮度滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    44、GPUImageBoxBlurFilter,盒状模糊滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》

    45、GPUImageGaussianBlurFilter,高斯模糊滤镜

    《音视频直播------GPUImage》《音视频直播------GPUImage》


    以上滤镜效果对应的代码如下

    //
    //  ViewController.swift
    //  GPUImageTest
    //
    //  Created by fe on 2018/6/12.
    //  Copyright © 2018年 fe. All rights reserved.
    //
    
    import UIKit
    import GPUImage
    class ViewController: UIViewController {
        fileprivate lazy var image : UIImage = UIImage(named: "test")!
        @IBOutlet var imageView: UIImageView!
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.imageView.image = gaussianBlur()
        }
        
        //0.使用GPUImage对图片做滤镜处理
        fileprivate func blurFilter(filter : GPUImageFilter) -> UIImage?{
            //1.使用GPUImage对图片进行高斯模糊处理(毛玻璃效果)
            
            //1.1获取GPUImagePicture
            let gpuimagepic = GPUImagePicture(image: image)
            
            //1.2添加需要处理的滤镜
            gpuimagepic?.addTarget(filter)
            
            //1.3处理图片
            filter.useNextFrameForImageCapture()
            gpuimagepic?.processImage()
            
            //1.4取出最新的图片
            let newimage = filter.imageFromCurrentFramebuffer()
            return newimage
        }
        
        //1.高斯模糊(毛玻璃效果)滤镜
        fileprivate func gaussianBlur() -> UIImage?{
            //创建需要处理的滤镜
            let blurFilter = GPUImageGaussianBlurFilter()
            //纹理大小
            blurFilter.texelSpacingMultiplier = 3
            //每个像素点的模糊程度
            blurFilter.blurRadiusInPixels = 2
            return self.blurFilter(filter: blurFilter)
        }
        
        //2.盒状模糊滤镜
        fileprivate func boxBlurFilter()->UIImage?{
            let boxBlurFilter =  GPUImageBoxBlurFilter()
            return self.blurFilter(filter: boxBlurFilter)
        }
        
        //3.亮度滤镜
        fileprivate func brightnessFilter()->UIImage?{
            let brightnessFilter =  GPUImageBrightnessFilter()
            // Brightness ranges from -1.0 to 1.0, with 0.0 as the normal level
            brightnessFilter.brightness = 0.3
            return self.blurFilter(filter: brightnessFilter)
        }
        
        //4.凸镜滤镜
        fileprivate func bulgeDistortionFilter()->UIImage?{
            let bulgeDistortionFilter =  GPUImageBulgeDistortionFilter()
            bulgeDistortionFilter.center = CGPoint(x: 0.5, y: 0.5)
            bulgeDistortionFilter.radius = 0.5
            bulgeDistortionFilter.scale = 0.6
            return self.blurFilter(filter: bulgeDistortionFilter)
        }
        
        //5.CGA色彩滤镜,形成黑、浅蓝、紫色块的画面
        fileprivate func colorspaceFilter()->UIImage?{
            let colorspaceFilter =  GPUImageCGAColorspaceFilter()
            return self.blurFilter(filter: colorspaceFilter)
        }
        
        //6.色键滤镜,(smoothing = 0.1 ,thresholdSensitivity = 0.5 可以把背景替换为白色)
        fileprivate func chromaKeyFilter()->UIImage?{
            let chromaKeyFilter =  GPUImageChromaKeyFilter()
            chromaKeyFilter.smoothing = 0.12
            chromaKeyFilter.thresholdSensitivity = 0.5
            return self.blurFilter(filter: chromaKeyFilter)
        }
        
        
        //7.反色滤镜,X光效果
        fileprivate func colorInvertFilter()->UIImage?{
            let colorInvertFilter =  GPUImageColorInvertFilter()
            return self.blurFilter(filter: colorInvertFilter)
        }
        
        //8.彩色包装滤镜
        fileprivate func colorPackingFilter()->UIImage?{
            let colorPackingFilter =  GPUImageColorPackingFilter()
            return self.blurFilter(filter: colorPackingFilter)
        }
        
        //9.对比度滤镜
        fileprivate func contrastFilter()->UIImage?{
            let contrastFilter =  GPUImageContrastFilter()
            /** Contrast ranges from 0.0 to 4.0 (max contrast), with 1.0 as the normal level
             */
            contrastFilter.contrast = 4.0
            return self.blurFilter(filter: contrastFilter)
        }
        
        //10.交叉阴影滤镜
        fileprivate func crosshatchFilter()->UIImage?{
            let crosshatchFilter =  GPUImageCrosshatchFilter()
            crosshatchFilter.crossHatchSpacing = 0.05
            crosshatchFilter.lineWidth = 0.002
            return self.blurFilter(filter: crosshatchFilter)
        }
    
    
        //11.定向抑制滤镜 
        fileprivate func suppressionFilter()->UIImage?{
            let suppressionFilter =  GPUImageDirectionalNonMaximumSuppressionFilter()
            //suppressionFilter.texelWidth = 0     //纹素像素宽度
            //suppressionFilter.texelHeight = 0    //文素像素高度
            //suppressionFilter.upperThreshold = 0 //亮度阀值
            //suppressionFilter.lowerThreshold = 0 //亮度阀值
            return self.blurFilter(filter: suppressionFilter)
        }
        
        //12.曝光度滤镜
        fileprivate func exposureFilter()->UIImage?{
            let exposureFilter =  GPUImageExposureFilter()
            exposureFilter.exposure = -1 //曝光度 -10~10 默认0
            return self.blurFilter(filter: exposureFilter)
        }
        
        
        //13.人工换色滤镜
        fileprivate func falseColorFilter()->UIImage?{
            let falseColorFilter = GPUImageFalseColorFilter()
            falseColorFilter.firstColor = GPUVector4(one: 0.8, two: 0.5, three: 0, four: 0.0) //用于替换图片上深色区域的颜色 ,设置参数类似RGB
            falseColorFilter.secondColor = GPUVector4(one: 0.5, two: 0.8, three: 0.7, four: 0.0)//用于替换图片上浅色区域的颜色 ,设置参数类似RGB
            return self.blurFilter(filter: falseColorFilter)
        }
        
        //14.灰度系数滤镜
        fileprivate func gammaFilter()->UIImage?{
            let gammaFilter = GPUImageGammaFilter()
            gammaFilter.gamma = 2.0 // 灰度系数 0.0~3.0  默认 1.0
            return self.blurFilter(filter: gammaFilter)
        }
        
        
        //15.黑白(灰度)滤镜
        fileprivate func grayscaleFilter()->UIImage?{
            let grayscaleFilter = GPUImageGrayscaleFilter()
            return self.blurFilter(filter: grayscaleFilter)
        }
        
        
        //16.朦胧路径
        fileprivate func hazeFilter()->UIImage?{
            let hazeFilter = GPUImageHazeFilter()
            hazeFilter.distance = -0.3  //色强  -0.3 ~ 0.3 效果最好
            hazeFilter.slope = -0.3     //饱和度 -0.3 ~ 0.3 效果最好
            return self.blurFilter(filter: hazeFilter)
        }
        
        //17.高光阴影滤镜
        fileprivate func highlightShadowFilter()->UIImage?{
            let highlightShadowFilter = GPUImageHighlightShadowFilter()
            /**
             * 0 - 1, increase to lighten shadows.
             * @default 0
             */
            highlightShadowFilter.highlights = 0.5
            /**
             * 0 - 1, decrease to darken highlights.
             * @default 1
             */
            highlightShadowFilter.shadows =  0.8
            return self.blurFilter(filter: highlightShadowFilter)
        }
        
        
        //18.色调滤镜
        fileprivate func hueFilter()->UIImage?{
            let hueFilter = GPUImageHueFilter()
            hueFilter.hue = 100  //色度
            return self.blurFilter(filter: hueFilter)
        }
        
        //19.叠原滤镜
        fileprivate func kuwaharaFilter()->UIImage?{
            let kuwaharaFilter = GPUImageKuwaharaFilter()
            /// The radius to sample from when creating the brush-stroke effect, with a default of 3. The larger the radius, the slower the filter.
            kuwaharaFilter.radius = 2
            return self.blurFilter(filter: kuwaharaFilter)
        }
        
        //20.叠原滤镜radius = 3
        fileprivate func kuwaharaRadius3Filter()->UIImage?{
            let kuwaharaRadius3Filter = GPUImageKuwaharaRadius3Filter()
            return self.blurFilter(filter: kuwaharaRadius3Filter)
        }
        
        //21.色阶滤镜
        fileprivate func levelsFilter()->UIImage?{
            let levelsFilter = GPUImageLevelsFilter()
            levelsFilter.setGreenMin(0.0, gamma: 0.5, max: 0.9) //绿色
            levelsFilter.setBlueMin(0.5, gamma: 0.4, max: 0.5) //蓝色
            levelsFilter.setRedMin(0.5, gamma: 0.4, max: 0.5)  //红色
            return self.blurFilter(filter: levelsFilter)
        }
        
        //22.灰度差值滤镜
        fileprivate func luminanceRangeFilter()->UIImage?{
            let luminanceRangeFilter = GPUImageLuminanceRangeFilter()
            luminanceRangeFilter.rangeReductionFactor = 0.9
            return self.blurFilter(filter: luminanceRangeFilter)
        }
        
        //23.黑白灰度滤镜
        fileprivate func luminanceThresholdFilter()->UIImage?{
            let luminanceThresholdFilter = GPUImageLuminanceThresholdFilter()
            /** Anything above this luminance will be white, and anything below black. Ranges from 0.0 to 1.0, with 0.5 as the default
             */
            luminanceThresholdFilter.threshold = 0.4
            return self.blurFilter(filter: luminanceThresholdFilter)
        }
        
        //24.单色滤镜
        fileprivate func monochromeFilter()->UIImage?{
            let monochromeFilter = GPUImageMonochromeFilter()
            monochromeFilter.intensity = 3  //光强
            return self.blurFilter(filter: monochromeFilter)
        }
        
        
        //25.单色模糊滤镜
        fileprivate func motionBlurFilter()->UIImage?{
            let motionBlurFilter = GPUImageMotionBlurFilter()
            /** A multiplier for the blur size, ranging from 0.0 on up, with a default of 1.0
             */
            motionBlurFilter.blurAngle = 0.5
            /** The angular direction of the blur, in degrees. 0 degrees by default
             */
            motionBlurFilter.blurSize = 0.5
            return self.blurFilter(filter: motionBlurFilter)
        }
        
        
        //26.透明滤镜
        fileprivate func opacityFilter()->UIImage?{
            let opacityFilter = GPUImageOpacityFilter()
            // Opacity ranges from 0.0 to 1.0, with 1.0 as the normal setting
            opacityFilter.opacity = 0.5
            return self.blurFilter(filter: opacityFilter)
        }
        
        //27.拉伸滤镜
        fileprivate func pinchDistortionFilter()->UIImage?{
            let pinchDistortionFilter = GPUImagePinchDistortionFilter()
            /** The center about which to apply the distortion, with a default of (0.5, 0.5)
             */
            pinchDistortionFilter.center = CGPoint(x: 0.5, y: 0.5)
            /** The radius of the distortion, ranging from 0.0 to 2.0, with a default of 1.0
             */
            pinchDistortionFilter.radius = 1.5
            /** The amount of distortion to apply, from -2.0 to 2.0, with a default of 0.5
             */
            pinchDistortionFilter.scale = 1.2
            return self.blurFilter(filter: pinchDistortionFilter)
        }
        
        //28.像素化滤镜(马赛克)
        fileprivate func pixellateFilter()->UIImage?{
            let pixellateFilter = GPUImagePixellateFilter()
            // The fractional width of the image to use as a size for the pixels in the resulting image. Values below one pixel width in the source image are ignored.
            pixellateFilter.fractionalWidthOfAPixel = 0.05
            return self.blurFilter(filter: pixellateFilter)
        }
        
        //29.局部像素化滤镜(马赛克)
        fileprivate func pixellatePositionFilter()->UIImage?{
            let pixellatePositionFilter = GPUImagePixellatePositionFilter()
            // The fractional width of the image to use as a size for the pixels in the resulting image. Values below one pixel width in the source image are ignored.
            pixellatePositionFilter.fractionalWidthOfAPixel = 0.05
            
            // the center point to start pixelation in texture coordinates, default 0.5, 0.5
            pixellatePositionFilter.center = CGPoint(x: 0.5, y: 0.10)
            
            // the radius (0.0 - 1.0) in which to pixelate, default 1.0
            pixellatePositionFilter.radius = 0.1
    
            return self.blurFilter(filter: pixellatePositionFilter)
        }
        
        
        //30.边缘像素滤镜
        fileprivate func polarPixellateFilter()->UIImage?{
            let polarPixellateFilter = GPUImagePolarPixellateFilter()
            // The center about which to apply the distortion, with a default of (0.5, 0.5)
            polarPixellateFilter.center = CGPoint(x: 0.5, y: 0.08)
            // The amount of distortion to apply, from (-2.0, -2.0) to (2.0, 2.0), with a default of (0.05, 0.05)
            polarPixellateFilter.pixelSize = CGSize(width: 0.01, height: 0.01)
            return self.blurFilter(filter: polarPixellateFilter)
        }
        
        
        //31.色调分离滤镜
        fileprivate func posterizeFilter()->UIImage?{
            let posterizeFilter = GPUImagePosterizeFilter()
            /** The number of color levels to reduce the image space to. This ranges from 1 to 256, with a default of 10.
             */
            posterizeFilter.colorLevels = 3
            return self.blurFilter(filter: posterizeFilter)
        }
        
        
        //32.RGB滤镜
        fileprivate func rgbFilter()->UIImage?{
            let rgbFilter = GPUImageRGBFilter()
            // Normalized values by which each color channel is multiplied. The range is from 0.0 up, with 1.0 as the default.
            rgbFilter.red = 2
            rgbFilter.green = 2
            rgbFilter.blue = 2
            return self.blurFilter(filter: rgbFilter)
        }
        
        //33.饱和度滤镜
        fileprivate func saturationFilter()->UIImage?{
            let saturationFilter = GPUImageSaturationFilter()
            /** Saturation ranges from 0.0 (fully desaturated) to 2.0 (max saturation), with 1.0 as the normal level
             */
            saturationFilter.saturation = 1.5
            return self.blurFilter(filter: saturationFilter)
        }
        
        //34.尖锐滤镜
        fileprivate func sharpenFilter()->UIImage?{
            let sharpenFilter = GPUImageSharpenFilter()
            // Sharpness ranges from -4.0 to 4.0, with 0.0 as the normal level
            sharpenFilter.sharpness = -1
            return self.blurFilter(filter: sharpenFilter)
        }
        
        
        //35.球面滤镜
        fileprivate func sphereRefractionFilter()->UIImage?{
            let sphereRefractionFilter = GPUImageSphereRefractionFilter()
            /// The center about which to apply the distortion, with a default of (0.5, 0.5)
            sphereRefractionFilter.center = CGPoint(x: 0.5, y: 0.5)
            /// The radius of the distortion, ranging from 0.0 to 1.0, with a default of 0.25
            sphereRefractionFilter.radius = 0.4
            /// The index of refraction for the sphere, with a default of 0.71
            sphereRefractionFilter.refractiveIndex = 0.5
            return self.blurFilter(filter: sphereRefractionFilter)
        }
        
        //36.拉伸滤镜
        fileprivate func stretchDistortionFilter()->UIImage?{
            let stretchDistortionFilter = GPUImageStretchDistortionFilter()
            /** The center about which to apply the distortion, with a default of (0.5, 0.5)
             */
            stretchDistortionFilter.center = CGPoint(x: 0.5, y: 0.5)
            return self.blurFilter(filter: stretchDistortionFilter)
        }
        
        
        //37.螺旋滤镜
        fileprivate func swirlFilter()->UIImage?{
            let swirlFilter = GPUImageSwirlFilter()
            /// The center about which to apply the distortion, with a default of (0.5, 0.5)
            swirlFilter.center = CGPoint(x: 0.5, y: 0.5)
            /// The radius of the distortion, ranging from 0.0 to 1.0, with a default of 0.5
            swirlFilter.radius = 0.5
            /// The amount of distortion to apply, with a minimum of 0.0 and a default of 1.0
            swirlFilter.angle = 0.25
            return self.blurFilter(filter: swirlFilter)
        }
        
        
        //38.旋转滤镜
        fileprivate func transformFilter()->UIImage?{
            let transformFilter = GPUImageTransformFilter()
            
            // You can either set the transform to apply to be a 2-D affine transform or a 3-D transform. The default is the identity transform (the output image is identical to the input).
            transformFilter.affineTransform = CGAffineTransform(a: 0.2, b: 0.1, c: 0.1, d: 0.5, tx: 0.1, ty: 0.1)
            //transformFilter.transform3D = CATransform3D(m11: 0, m12: 0, m13:  0, m14:  0, m21:  0.1, m22:  0, m23:  0, m24:  0.1, m31:  0.1, m32:  0, m33:  0, m34:  0, m41:  0, m42:  0, m43:  0, m44:  0.1)
            
            // This applies the transform to the raw frame data if set to YES, the default of NO takes the aspect ratio of the image input into account when rotating
            transformFilter.ignoreAspectRatio = false
            
            // sets the anchor point to top left corner
            transformFilter.anchorTopLeft = true
            return self.blurFilter(filter: transformFilter)
        }
        
        
        //39.晕映滤镜
        fileprivate func vignetteFilter()->UIImage?{
            let vignetteFilter = GPUImageVignetteFilter()
            // the center for the vignette in tex coords (defaults to 0.5, 0.5)
            vignetteFilter.vignetteCenter = CGPoint(x: 0.5, y: 0.5)
            
            // The color to use for the Vignette (defaults to black)
            vignetteFilter.vignetteColor = GPUVector3(one: 100, two: 0, three: 255)
            
            // The normalized distance from the center where the vignette effect starts. Default of 0.5.
            vignetteFilter.vignetteStart = 0.45
            
            // The normalized distance from the center where the vignette effect ends. Default of 0.75.
            vignetteFilter.vignetteEnd = 0.75
    
            return self.blurFilter(filter: vignetteFilter)
        }
        
        
        
        //40.白平衡滤镜
        fileprivate func whiteBalanceFilter()->UIImage?{
            let whiteBalanceFilter = GPUImageWhiteBalanceFilter()
            //choose color temperature, in degrees Kelvin
            whiteBalanceFilter.temperature = 0.1
            
            //adjust tint to compensate
            whiteBalanceFilter.tint = 0.1
    
            return self.blurFilter(filter: whiteBalanceFilter)
        }
        
        //41.放缩毛玻璃滤镜
        fileprivate func zoomBlurFilter()->UIImage?{
            let zoomBlurFilter = GPUImageZoomBlurFilter()
            /** A multiplier for the blur size, ranging from 0.0 on up, with a default of 1.0
             */
            zoomBlurFilter.blurSize = 0.5
            
            /** The normalized center of the blur. (0.5, 0.5) by default
             */
            zoomBlurFilter.blurCenter = CGPoint(x: 0.5, y: 0.5)
            return self.blurFilter(filter: zoomBlurFilter)
        }
        
        //42.怀旧滤镜
        fileprivate func sepiaFilter()->UIImage?{
            let sepiaFilter = GPUImageSepiaFilter()
            
            return self.blurFilter(filter: sepiaFilter)
        }
        
        
        //43.素描滤镜
        fileprivate func sketchFilter()->UIImage?{
            let sketchFilter = GPUImageSketchFilter()
            
            return self.blurFilter(filter: sketchFilter)
        }
        
        //44.卡通滤镜
        fileprivate func toonFilter()->UIImage?{
            let toonFilter = GPUImageToonFilter()
            /** The threshold at which to apply the edges, default of 0.2
             */
            toonFilter.threshold = 0.3
            
            /** The levels of quantization for the posterization of colors within the scene, with a default of 10.0
             */
            toonFilter.quantizationLevels = 20
            return self.blurFilter(filter: toonFilter)
        }
    
        //45.浮雕滤镜
        fileprivate func embossFilter()->UIImage?{
            let embossFilter = GPUImageEmbossFilter()
            // The strength of the embossing, from  0.0 to 4.0, with 1.0 as the normal level
            embossFilter.intensity = 4.0
            return self.blurFilter(filter: embossFilter)
        }
        
        //46.中间色调、黑白滤镜
        fileprivate func halftoneFilter()->UIImage?{
            let halftoneFilter = GPUImageHalftoneFilter()
            
            return self.blurFilter(filter: halftoneFilter)
        }
        
    }
    
    GPUImage实现视频直播实时美颜
  • //
    //  ViewController.swift
    //  BeautyCamera
    //
    //  Created by fe on 18/06/26.
    //  Copyright © 2018年 fe. All rights reserved.
    //
    
    import UIKit
    import GPUImage
    import AVKit
    
    class ViewController: UIViewController {
        @IBOutlet weak var beautyViewBottomCons: NSLayoutConstraint!
        
        // MARK: 懒加载属性
        // 创建视频源
        fileprivate lazy var camera : GPUImageVideoCamera? = GPUImageVideoCamera(sessionPreset: AVCaptureSessionPresetHigh, cameraPosition: .front)
        
        // 创建预览图层
        fileprivate lazy var preview : GPUImageView = GPUImageView(frame: self.view.bounds)
        
        // 初始化滤镜
        let bilateralFilter = GPUImageBilateralFilter() // 磨皮
        let exposureFilter = GPUImageExposureFilter() // 曝光
        let brightnessFilter = GPUImageBrightnessFilter() // 美白
        let satureationFilter = GPUImageSaturationFilter() // 饱和
        
        // 创建写入对象
        fileprivate lazy var movieWriter : GPUImageMovieWriter = { [unowned self] in
            // 创建写入对象
            let writer = GPUImageMovieWriter(movieURL: self.fileURL, size: self.view.bounds.size)
            
            // 设置写入对象的属性
            
            return writer!
        }()
        
        // MARK: 计算属性
        var fileURL : URL {
            return URL(fileURLWithPath: "\(NSTemporaryDirectory())123.mp4")
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
            print(fileURL)
            
            // 1.设置camera方向
            camera?.outputImageOrientation = .portrait
            camera?.horizontallyMirrorFrontFacingCamera = true
            
            // 2.创建预览的View
            view.insertSubview(preview, at: 0)
            
            // 3.获取滤镜组
            let filterGroup = getGroupFilters()
            
            // 4.设置GPUImage的响应链
            camera?.addTarget(filterGroup)
            filterGroup.addTarget(preview)
            
            // 5.开始采集视频
            camera?.startCapture()
            
            // 6.设置writer的属性
            // 是否对视频进行编码
            movieWriter.encodingLiveVideo = true
            
            // 将writer设置成滤镜的target
            filterGroup.addTarget(movieWriter)
            
            // 设置camera的编码
            camera?.delegate = self
            camera?.audioEncodingTarget = movieWriter
            let fileManage = FileManager()
            if fileManage.fileExists(atPath: "\(NSTemporaryDirectory())123.mp4") {
                try? fileManage.removeItem(atPath: "\(NSTemporaryDirectory())123.mp4")
            }
            movieWriter.startRecording()
        }
        
        
        fileprivate func getGroupFilters() -> GPUImageFilterGroup{
            // 1.创建滤镜组(用于存放各种滤镜:美白、磨皮等等)
            let filterGroup = GPUImageFilterGroup()
            
            // 2.创建滤镜(设置滤镜的引来关系)
            bilateralFilter.addTarget(brightnessFilter)
            brightnessFilter.addTarget(exposureFilter)
            exposureFilter.addTarget(satureationFilter)
            
            // 3.设置滤镜组链初始&终点的filter
            filterGroup.initialFilters = [bilateralFilter]
            filterGroup.terminalFilter = satureationFilter
            
            return filterGroup
        }
    }
    
    
    // MARK:- 控制方法
    extension ViewController {
        @IBAction func rotateCamera() {
            camera?.rotateCamera()
        }
        
        @IBAction func adjustBeautyEffect() {
            adjustBeautyView(constant: 0)
        }
        
        @IBAction func finishedBeautyEffect() {
            adjustBeautyView(constant: -250)
        }
        
        @IBAction func switchBeautyEffect(switchBtn : UISwitch) {
            if switchBtn.isOn {
                camera?.removeAllTargets()
                let group = getGroupFilters()
                camera?.addTarget(group)
                group.addTarget(preview)
            } else {
                camera?.removeAllTargets()
                camera?.addTarget(preview)
            }
        }
        
        private func adjustBeautyView(constant : CGFloat) {
            beautyViewBottomCons.constant = constant
            UIView.animate(withDuration: 0.5) {
                self.view.layoutIfNeeded()
            }
        }
        
        @IBAction func changeSatureation(_ sender: UISlider) {
            print(sender.value)
            satureationFilter.saturation = CGFloat(sender.value * 2)
        }
        
        @IBAction func changeBrightness(_ sender: UISlider) {
            // - 1 --> 1
            brightnessFilter.brightness = CGFloat(sender.value) * 2 - 1
        }
        
        @IBAction func changeExposure(_ sender: UISlider) {
            // - 10 ~ 10
            exposureFilter.exposure = CGFloat(sender.value) * 20 - 10
        }
        
        @IBAction func changeBilateral(_ sender: UISlider) {
            bilateralFilter.distanceNormalizationFactor = CGFloat(sender.value) * 8
        }
    }
    
    extension ViewController : GPUImageVideoCameraDelegate {
        func willOutputSampleBuffer(_ sampleBuffer: CMSampleBuffer!) {
            print("采集到画面")
        }
    }
    
    extension ViewController {
        @IBAction func stopRecording() {
            camera?.stopCapture()
            preview.removeFromSuperview()
            movieWriter.finishRecording()
        }
        
        @IBAction func playVideo() {
            print(fileURL)
            let playerVc = AVPlayerViewController()
            playerVc.player = AVPlayer(url: fileURL)
            present(playerVc, animated: true, completion: nil)
        }
    }
    


相关标签: 音视频 GPUImage