如何解释Swift中从CMSampleBuffer派生的像素数组



也许这是一个非常愚蠢的问题。我在我的应用程序中使用AVFoundation,我能够获得帧(32BGRA格式(。帧的宽度为1504,高度为1128,每行字节数值为6016。当我从这个samplebuffer创建UInt8像素数组时,这个数组的长度(array.count(是1696512,恰好等于width*height。

我不明白为什么数组的长度是width*height。应该不是宽度*高度*4。

我在这里错过了什么?

编辑-1:编码

func BufferToArray(sampleBuffer: CMSampleBuffer) -> ([UInt8], Int, Int, Int) {
var rgbBufferArray = [UInt8]()
//Get pixel Buffer from CMSSampleBUffer
let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
//Lock the base Address
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
//get pixel count
let pixelCount = CVPixelBufferGetWidth(pixelBuffer) * CVPixelBufferGetHeight(pixelBuffer)
//Get base address
let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer)
//Get bytes per row of the image
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
//Cast the base address to UInt8. This is like an array now
let frameBuffer = baseAddress?.assumingMemoryBound(to: UInt8.self)

rgbBufferArray = Array(UnsafeMutableBufferPointer(start: frameBuffer, count: pixelCount))

//Unlock and release memory
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
return (rgbBufferArray, bytesPerRow, width, height)

}

罪魁祸首是数据类型(UInt8(与count:的组合

您假设内存包含pixelCount计数的UInt8值(assumingMemoryBound(to: UInt8.self)(。但正如你正确得出的结论,它应该是这个数字的四倍。

我建议您使用import simd,并使用simd_uchar4作为数据类型。这是一个包含4个UInt8的结构类型。然后,您的数组将包含4元组像素值的pixelCount值。您可以分别使用array[index].x.y.z.w访问通道。

最新更新