从CVPixelBuffer获取所需数据参考
问题描述:
我有一个程序实时查看相机输入并获取中间像素的颜色值。我用captureOutput:方法来从一个AVCaptureSession输出(恰好被读作CVPixelBuffer),然后我抢用下面的代码的像素的RGB值抢CMSampleBuffer:从CVPixelBuffer获取所需数据参考
// 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)];
我虽然该公式((宽度*高度)* 4)/ 2会让我成为中间像素,但它给了我图像的顶部中间像素。我想知道什么公式需要用来访问屏幕中间的像素。我有点卡住,因为我不知道这些像素缓冲区的内部结构。
在未来,我想抓住4个中间像素,并将它们平均以获得更准确的颜色读数,但现在我只想了解这些东西是如何工作的。
答
用于定位中间像素的公式的主要问题是,它仅适用于不均匀扫描线数。如果你有一个偶数,它会选择中间下方扫描线上的第一个像素。这是左中间像素。由于iPhone视频帧旋转了90度,因此该像素实际上是顶部中间像素。
因此,对于定位中像素更好的计算公式为:
(height/2) * bytesPerRow + (width/2) * 4
是,两个摄像头在iOS设备的默认方向是横向的,所以如果你在做任何肖像模式工作,你”你需要处理一个旋转的帧。 – 2012-04-15 21:07:43
@Codo有什么建议吗? http://stackoverflow.com/questions/37611593/how-to-create-cvpixelbufferref-with-yuv420i420-data – 2016-06-07 03:47:23
好奇,为什么宽度部分乘以4? – OutOnAWeekend 2017-02-15 15:12:41