如何从CVPixelBuffer读取单个像素



AVDepthData为我提供了深度数据的CVPixelBuffer。但我找不到一种方法来轻松访问这个CVPixelBuffer中的深度信息。Objective-C中有一个简单的方法可以做到这一点吗?

您必须使用CVPixelBuffer API来获得正确的格式,以便通过不安全的指针操作访问数据。以下是基本方法:

CVPixelBufferRef pixelBuffer = _lastDepthData.depthDataMap;
CVPixelBufferLockBaseAddress(pixelBuffer, 0);
size_t cols = CVPixelBufferGetWidth(pixelBuffer);
size_t rows = CVPixelBufferGetHeight(pixelBuffer);
Float32 *baseAddress = CVPixelBufferGetBaseAddress( pixelBuffer );
// This next step is not necessary, but I include it here for illustration,
// you can get the type of pixel format, and it is associated with a kCVPixelFormatType
// this can tell you what type of data it is e.g. in this case Float32
OSType type = CVPixelBufferGetPixelFormatType( pixelBuffer);
if (type != kCVPixelFormatType_DepthFloat32) {
NSLog(@"Wrong type");
}
// Arbitrary values of x and y to sample
int x = 20; // must be lower that cols
int y = 30; // must be lower than rows
// Get the pixel.  You could iterate here of course to get multiple pixels!
int baseAddressIndex = y  * (int)cols + x;
const Float32 pixel = baseAddress[baseAddressIndex];
CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 );

请注意,您需要确定的第一件事是CVPixelBuffer中的数据类型-如果您不知道这一点,则可以使用CVPixelBufferGetPixelFormatType((来查找。在这种情况下,我在Float32获得深度数据,如果您使用另一种类型,例如Float16,那么您需要用该类型替换Float33的所有出现。

请注意,使用CVPixelBufferLockBaseAddress和CVPixelBufferUnlockBaseAddress锁定和解锁基地址非常重要。

最新更新