如何在Swift 4的ARKit中实现实时相机滤镜?

时间:2019-10-21 09:46:10

标签: ios camera swift4 arkit cifilter

我想将iPhone相机滤镜集成到我的项目中,我的项目基于ARKit,我想应用苹果在相机应用程序中提供的所有滤镜,特别是 VIVID,VIVID WARM和VIVID COOL >,

我已经尝试过各种可能性,我在下面提到。

func session(_ session: ARSession, didUpdate frame: ARFrame) {
        guard let currentBackgroundFrameImage = sceneView.session.currentFrame?.capturedImage,
        let pixelBufferAddressOfPlane = CVPixelBufferGetBaseAddressOfPlane(currentBackgroundFrameImage, 1) else { return }

       let x: size_t = CVPixelBufferGetWidthOfPlane(currentBackgroundFrameImage, 1)
       let y: size_t = CVPixelBufferGetHeightOfPlane(currentBackgroundFrameImage, 1)
       memset(pixelBufferAddressOfPlane, 128, Int(x * y) * 2) }

我使用上述代码获得了黑白相机滤镜。

func session(_ session: ARSession, didUpdate frame: ARFrame) {
        let bg = session.currentFrame?.capturedImage
        if (bg != nil) {
            let image = CIImage(cvPixelBuffer: bg!)
            let filter:CIFilter = CIFilter(name: "CIPixellate")!
            filter.setDefaults()
            filter.setValue(image, forKey: kCIInputImageKey)
            //let filteredImageData = filter.value(forKey: kCIOutputImageKey) as! CIImage

            let context = CIContext()
            //if let result = filter.outputImage,
            if let result = filter.value(forKey: kCIOutputImageKey) ,
                let cgImage = context.createCGImage(result as! CIImage, from: (result as! CIImage).extent) {
                let imageForUser = UIImage(cgImage: cgImage)
                sceneView.scene.background.contents = imageForUser
                sceneView.scene.background.contentsTransform = SCNMatrix4MakeRotation(.pi / 2, 0, 0, 1)
            }
        }
}

使用上述代码导致相机卡住,并且渲染速度非常慢,有时由于内存问题导致应用程序崩溃。 (在iPhone XR中测试)

请为我提供实时相机滤镜功能。如果您为我提供ARKit相机滤镜的任何代码,那就太好了。谢谢。

1 个答案:

答案 0 :(得分:0)

stream