如何在相机屏幕上的指定点获取像素的RGB值?

时间:2012-08-30 09:39:19

标签: iphone ios

我希望在RGB上获得相机屏幕上指定点的颜色值(不捕获)。

我有以下代码段,但它提供了视图背景颜色的值,而不是相机屏幕上的图片。

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]);

1 个答案:

答案 0 :(得分:7)

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

您首先需要捕获视频缓冲区 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的显示屏上显示像素的位置,您可能需要对此进行缩放。