[英]capture UIImage from CMSampleBuffer (swift 3)
I try to capture an UIImage from a CMSampleBuffer to read the text. 我尝试从CMSampleBuffer捕获UIImage来读取文本。 But I always get the error: 但是我总是得到错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
I was looking around and tried a lot of versions. 我环顾四周,尝试了很多版本。 But I always get the same error. 但是我总是得到同样的错误。
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!)
}
kindly Regards! 亲切的问候!
CIImage.cgImage
applies only when the CIImage
was created from a CGImage
. CIImage.cgImage
仅在从CGImage
创建CIImage
时适用。 When you create a CIImage
from a pixel buffer, it has no underlying CGImage
so that property is nil. 从像素缓冲区创建CIImage
,它没有基础的CGImage
因此该属性为nil。
You can initialize a UIImage
direct from a CIImage
, but how that works for you will depend on where/how you render that image. 您可以直接从CIImage
初始化UIImage
,但是它如何工作取决于您在哪里/如何渲染该图像。 (For example rendering CI-backed UIImage
s in, say, UIImageView
gives poor performance in iOS 9 and older if you're doing it in realtime.) (例如,如果实时进行渲染,则在UIImageView
渲染由CI支持的UIImage
导致在iOS 9及UIImageView
性能不佳。)
To get the UIImage via CIImage you should use CIContext. 要通过CIImage获取UIImage,您应该使用CIContext。 Below is Obj-C code: 以下是Obj-C代码:
CIContext *context = [CIContext contextWithOptions:nil];
And then: 接着:
CGImageRef cgImage = [context createCGImage:yourCIImage fromRect:[yourCIImage extent] ];
UIImage *resultUIImage = [UIImage imageWithCGImage:cgImage scale:1.0 orientation:UIImageOrientationUp];
This approach claims it only uses GPU and thus is fast. 这种方法声称它仅使用GPU,因此速度很快。 But there are other methods to obtain UIImage from the CVPixelBuffer , like using CGContextRef . 但是还有其他方法可以从CVPixelBuffer获得UIImage,例如使用CGContextRef 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.