从CVPixelBuffer参考中获取所需数据

时间:2012-04-15 15:24:09

标签: iphone ios avcapturesession cmsamplebufferref cmsamplebuffer

我有一个程序可以实时查看摄像机输入并获取中间像素的颜色值。我使用captureOutput:方法从AVCaptureSession输出中获取CMSampleBuffer(恰好读作CVPixelBuffer),然后使用以下代码获取像素的rgb值:

// Get a CMSampleBuffer's Core Video image buffer for the media data
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); 
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer, 0); 

// Get the number of bytes per row for the pixel buffer
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); 
// Get the pixel buffer width and height
size_t width = CVPixelBufferGetWidth(imageBuffer); 
size_t height = CVPixelBufferGetHeight(imageBuffer); 
unsigned char* pixel = (unsigned char *)CVPixelBufferGetBaseAddress(imageBuffer);

NSLog(@"Middle pixel: %hhu", pixel[((width*height)*4)/2]);
int red = pixel[(((width*height)*4)/2)+2];
int green = pixel[(((width*height)*4)/2)+1];
int blue = pixel[((width*height)*4)/2];
int alpha = 1;

UIColor *color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha)];

我虽然那个公式((width * height)* 4)/ 2会让我得到中间像素,但它给了我图像的顶部中间像素。我想知道我需要使用什么公式来访问屏幕中间的像素。我有点卡住,因为我真的不知道这些像素缓冲区的内部结构。

将来我想抓住4个中间像素并对它们进行平均以获得更准确的颜色读数,但是现在我只想知道这些东西是如何工作的。

1 个答案:

答案 0 :(得分:4)

用于定位中间像素的公式的主要问题是它仅适用于不均匀数量的扫描线。如果你有一个偶数,它会选择中间正下方扫描线上的第一个像素。这是左中间的像素。由于iPhone视频帧旋转了90度,因此该像素实际上是顶部中间像素。

因此,找到中间像素的更好的公式是:

(height / 2) * bytesPerRow + (width / 2) * 4