gpt4 book ai didi

ios - 将 CMSampleBuffer 转换为 UIImage

转载 作者:搜寻专家 更新时间:2023-10-30 22:19:32 27 4
gpt4 key购买 nike

我正在尝试将 sampleBuffer 转换为 UIImage 并使用 colorspaceGray 在 ImageView 中显示它。但它显示如下图。我认为转换有问题。如何转换 CMSampleBuffer?

It is a gray version of a red colored image

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
print("buffered")
let imageBuffer: CVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
let width: Int = CVPixelBufferGetWidth(imageBuffer)
let height: Int = CVPixelBufferGetHeight(imageBuffer)
let bytesPerRow: Int = CVPixelBufferGetBytesPerRow(imageBuffer)
let lumaBuffer = CVPixelBufferGetBaseAddress(imageBuffer)

//let planeCount : Int = CVPixelBufferGetPlaneCount(imageBuffer)
let grayColorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
let context: CGContext = CGContext(data: lumaBuffer, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow , space: grayColorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue)!
let dstImageFilter: CGImage = context.makeImage()!
let imageRect : CGRect = CGRect(x: 0, y: 0, width: width, height: height)
context.draw(dstImageFilter, in: imageRect)
let image = UIImage(cgImage: dstImageFilter)
DispatchQueue.main.sync(execute: {() -> Void in
self.imageTest.image = image
})
}

最佳答案

转换很简单:

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
let ciimage = CIImage(cvPixelBuffer: imageBuffer)
let image = self.convert(cmage: ciimage)
}

// Convert CIImage to UIImage
func convert(cmage: CIImage) -> UIImage {
let context = CIContext(options: nil)
let cgImage = context.createCGImage(cmage, from: cmage.extent)!
let image = UIImage(cgImage: cgImage)
return image
}

关于ios - 将 CMSampleBuffer 转换为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com