2016-12-08 59 views
0

我尝试从CMSampleBuffer捕获UIImage以读取文本。但我总是得到错误:从CMSampleBuffer捕获UIImage(swift 3)

fatal error: unexpectedly found nil while unwrapping an Optional value 

我四处张望,并尝试了很多版本。但我总是得到同样的错误。

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) { 

     let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) 
     let image = CIImage(cvPixelBuffer: pixelBuffer!) 
      let uiImage = UIImage(cgImage: image.cgImage!) 
} 

亲切的问候!

+0

你不会说哪个解包是抛出错误。 'image'还是'uiImage'? –

+0

您正在使用错误的uiimage初始值设定项。你需要使用ciimage而不是cgimage –

回答

1

CIImage.cgImage仅当CIImageCGImage创建时适用。当您从像素缓冲区创建CIImage时,它没有标的CGImage,因此属性为零。

你可以initialize a UIImage direct from a CIImage,但这对你的作品将取决于你在哪里/如何渲染图像。 (例如渲染CI支持UIImage S IN,比方说,UIImageView给出的iOS 9业绩不佳和老年人,如果你在实时做这件事。)

-1

要获得的UIImage通过CIImage你应该使用CIContext。 下面是的OBJ-C代码:

CIContext *context = [CIContext contextWithOptions:nil]; 

然后:

CGImageRef cgImage = [context createCGImage:yourCIImage fromRect:[yourCIImage extent] ]; 
UIImage *resultUIImage = [UIImage imageWithCGImage:cgImage scale:1.0 orientation:UIImageOrientationUp]; 

该方法声称它仅使用GPU并因此快。 但是还有其他方法可以从CVPixelBuffer获得UIImage,就像使用CGContextRef一样。

相关问题