【问题标题】:How to interpret the pixel array derived from CMSampleBuffer in Swift如何在 Swift 中解释从 CMSampleBuffer 派生的像素数组
【发布时间】:2020-07-15 19:52:14
【问题描述】:

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

我没有得到的是为什么数组长度是宽度 * 高度。不应该是宽*高*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)

}

【问题讨论】:

  • 你是如何创建数组的?能否请您发布一些代码?
  • @FrankSchlegel 代码已添加。你能看看吗

标签: ios swift image-processing avfoundation


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多