iphone - 从 CVPixelBuffer Reference 获取所需数据

标签 iphone ios avcapturesession cmsamplebufferref cmsamplebuffer

我有一个程序可以实时查看相机输入并获取中间像素的颜色值。我使用 captureOutput: 方法从 AVCaptureSession 输出(恰好被读取为 CVPixelBuffer)中获取 CMSampleBuffer,然后使用以下代码获取像素的 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 个像素并对它们进行平均以获得更准确的颜色读数,但现在我只想了解这些东西是如何工作的。

最佳答案

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

所以一个更好的定位中间像素的公式是:

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

关于iphone - 从 CVPixelBuffer Reference 获取所需数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10163346/

相关文章:

ios - 如何确保我的 AVCaptureSession 有足够的时间运行?

swift - AVCapturePhoto 为什么我的照片总是为零?

iphone - 定制 iPhone 键盘

iphone - UISegmentedControl - 在 Interface Builder 中改变高度

javascript - 无法使用 JavaScript 重定向到 iPhone、iPad

ios - 汉堡菜单 UIPanGestureRecogniser

ios - 如何使用 Realm 编写更好的数据访问层

ios - 如何在iOS openCV中使用CvPhotoCamera?

iphone - iPad内置词典

iphone - 更改NSDate的时间?