【问题标题】:Getting desired data from a CVPixelBuffer Reference从 CVPixelBuffer 参考中获取所需数据
【发布时间】:2012-04-15 15:24:09
【问题描述】:

我有一个程序可以实时查看相机输入并获取中间像素的颜色值。我使用 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 ios avcapturesession cmsamplebufferref cmsamplebuffer


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,iOS 设备上两个摄像头的默认方向是横向的,所以如果你在做任何纵向模式的工作,你需要处理一个旋转的框架。
    • 很好奇,为什么宽度部分要乘以 4?
    • 每个像素为 4 个字节。宽度以像素数给出,而不是字节数。
    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 2015-02-05
    • 2017-11-09
    • 2018-03-17
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多