簡體   English   中英

如何獲得相機屏幕上指定點的像素的RGB值?

[英]How can I get RGB value of pixel at specified point on the camera screen?

我想獲取相機屏幕上指定點的顏色值(不捕獲),以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做您喜歡的事情。 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顯示屏上顯示的位置相同,則可能需要縮放比例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM