【问题标题】:How can I get RGB value of pixel at specified point on the camera screen?如何在相机屏幕上的指定点获取像素的 RGB 值?
【发布时间】:2012-08-25 00:16:07
【问题描述】:

我想以 RGB 形式获取相机屏幕上指定点的颜色值(不捕获)。

我有以下代码 sn-p,但它给出了视图背景颜色的值,而不是相机屏幕上的图片。

CGPoint point=CGPointMake(100,200);
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast);

CGContextTranslateCTM(context, -point.x, -point.y);
[self.view.layer renderInContext:context];

CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

NSLog(@"pixel: R=%d G=%d B=%d Alpha=%d", pixel[0], pixel[1], pixel[2], pixel[3]);

【问题讨论】:

  • 有一个API可以进行全屏捕获,试试吧。可能会起作用,我真的不确定。
  • 感谢 David H,我知道那个 API,但我的问题是......我想获取该相机视图上指定点的 RGB 值。
  • 不,我明白你的问题。如果您知道相机视图的偏移量以及像素的偏移量,那么您可以计算出窗口(屏幕)中的偏移量。你甚至可以使用 UIView 方法为你做这个转换。如果快照确实抓取了相机视图(我不知道是否如此),那么您想要的像素偏移量就是一个简单的数学运算。

标签: iphone ios


【解决方案1】:

假设您想要实时执行此操作(而不是使用屏幕截图,您明确表示您想要):

您首先需要捕获视频缓冲区as outlined by Apple here

然后你可以用CMSampleBufferRef 做你喜欢的事。 Apple 的示例应用程序创建了 UIImage,但您可以简单地将其复制到 unsigned char 指针中(通过 CVImageBufferRefCVPixelBufferRef),然后提取相关像素的 BGRA 值,类似这样(未经测试代码:示例适用于 100x,200y 的像素):

int x = 100;
int y = 200;
CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer,0);
tempAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
int bufferSize = bytesPerRow * height;
uint8_t *myPixelBuf = malloc(bufferSize);
memmove(myPixelBuf, tempAddress, bufferSize);
tempAddress = nil;
// remember it's BGRA data
int b = myPixelBuf[(x*4)+(y*bytesPerRow)];
int g = myPixelBuf[((x*4)+(y*bytesPerRow))+1];
int r = myPixelBuf[((x*4)+(y*bytesPerRow))+2];
free(myPixelBuf);
NSLog(@"r:%i g:%i b:%i",r,g,b);

这会获取相对于视频源本身像素的位置,这可能不是您想要的:如果您希望像素的位置显示在 iPhone 的显示屏上,您可能需要对其进行缩放。

【讨论】:

  • 我偶然发现了这个很棒的解释。谢谢你。您能否详细说明 BGRA 的“A”。在分析 BGR 之前,我已经看到很多代码试图为 A 标准化。你能解释一下为什么在使用 BGR 数据之前进行标准化过程吗?谢谢
  • 这是阿尔法。在像这样的视频帧缓冲区的情况下,它始终是 100%,因此可以忽略(只是 iOS 在 32 位色彩空间中运行,即使它并不真正需要)。
猜你喜欢
  • 1970-01-01
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多