[英]capture UIImage from CMSampleBuffer (swift 3)
我嘗試從CMSampleBuffer捕獲UIImage來讀取文本。 但是我總是得到錯誤:
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!)
}
親切的問候!
CIImage.cgImage
僅在從CGImage
創建CIImage
時適用。 從像素緩沖區創建CIImage
,它沒有基礎的CGImage
因此該屬性為nil。
您可以直接從CIImage
初始化UIImage
,但是它如何工作取決於您在哪里/如何渲染該圖像。 (例如,如果實時進行渲染,則在UIImageView
渲染由CI支持的UIImage
導致在iOS 9及UIImageView
性能不佳。)
要通過CIImage獲取UIImage,您應該使用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 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.