如何在cammera屏幕上的指定点获取pixcel的RGB值?

我希望在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]); 

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

您首先需要捕获Apple在此处概述的video缓冲区。

然后,您可以使用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:%ig:%ib:%i",r,g,b); 

这会获得相对于video输入本身像素的位置,这可能与您想要的不同:如果您想要在iPhone的显示屏上显示像素的位置,您可能需要对此进行缩放。