Search code examples
iosswiftmetallidar

Write depthMap buffer to file (Swift)


I work with the new iPadPro and a LIDAR app and am kinda new to SWIFT5 (normaly working on CordovaApps with minimal native coding needed)

I want to dump the CVPixelBuffer I get for a frame to a .bin file.

I get the buffer like this: let depthMap = frame.sceneDepth!.depthMap It returns a DepthFloat32 buffer.

After that I lock the address and fetch it:

CVPixelBufferLockBaseAddress(depthMap, CVPixelBufferLockFlags(rawValue: 0))
var addr = CVPixelBufferGetBaseAddress(depthMap)

How can I save these values to a file on my iPad? Would be thankful for any help.


Solution

  • I solved it on my own. Here is my solution in case somebody needs it.

    Gather all the necessary values:

    let addr = CVPixelBufferGetBaseAddress(depthMap)
    let height = CVPixelBufferGetHeight(depthMap)
    let bpr = CVPixelBufferGetBytesPerRow(depthMap)
    

    Then I hand the bufferaddress to the Data obj to create a byte buffer in memory --> Data

    let data = Data(bytes: addr!, count: (bpr*height))
    do {
       let filename = getDirectory().appendingPathComponent(timestamp +"_depthbuffer.bin")
       try data.write(to: filename)
    } catch {
       // do smth with errors
    }
    

    getDirectory() is a custom function to find the Documents Directory. I can get the created Files from the App Container.

    Don't forgett to Lock & unlock the BufferAdress.