我希望在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]);
Run Code Online (Sandbox Code Playgroud)
假设您想要实时执行此操作(而不是使用屏幕截图,您明确表示不需要):
您首先需要捕获Apple在此处概述的视频缓冲区.
然后你就可以做你喜欢的事了CMSampleBufferRef
.Apple的示例应用程序制作了一个UIImage
,但您只需将其复制到一个unsigned char
指针(通过一个CVImageBufferRef
或CVPixelBufferRef
),然后拉出相关像素的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);
Run Code Online (Sandbox Code Playgroud)
这会获得相对于视频输入本身像素的位置,这可能与您想要的不同:如果您想要在iPhone的显示屏上显示像素的位置,您可能需要缩放它.
归档时间: |
|
查看次数: |
2438 次 |
最近记录: |