如何获取相机屏幕上指定点的像素的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在此处概述的

然后你可以用CMSampleBufferRef做你喜欢的事。苹果的示例应用程序生成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的显示器上显示像素的位置时,你可能需要缩放它。

最新更新