2011-02-18 44 views
1

我正在嘗試讀取iPhone攝像頭的中心像素(平均值)的RGB值。這應該幾乎在實時發生。因此我打開一個UIImagePickerController,使用計時器每隔x秒拍攝一張照片。處理圖片是在一個單獨的線程中進行的,因此它在計算RGB值時不會阻止應用程序。我嘗試了幾種方法來訪問拍攝圖像的RGB /像素值,但都存在問題,即它們太慢並導致相機視圖滯後。 我嘗試以下:實時訪問iPhone的攝像頭圖像

- (UIColor *)getAverageColorOfImage:(UIImage*)image { 
int pixelCount = kDetectorSize * kDetectorSize; 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

NSUInteger bytesPerPixel = 4; 
NSUInteger bytesPerRow = bytesPerPixel * kDetectorSize; 
NSUInteger bitsPerComponent = 8; 
unsigned char *rawData = malloc(pixelCount * bytesPerPixel); 
CGContextRef context = CGBitmapContextCreate(rawData, kDetectorSize, kDetectorSize, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
CGColorSpaceRelease(colorSpace); 
CGContextSetInterpolationQuality(context, kCGInterpolationNone); 

NSLog(@"Drawing image"); 
CGContextDrawImage(context, CGRectMake(0, 0, kDetectorSize, kDetectorSize), [image CGImage]); 
NSLog(@"Image drawn"); 

CGContextRelease(context); 

// rawData contains the image data in the RGBA8888 pixel format. Alpha values are ignored 
int byteIndex = 0; 
CGFloat red = 0.0; 
CGFloat green = 0.0; 
CGFloat blue = 0.0; 

for (int i = 0 ; i < pixelCount; ++i) { 
    red += rawData[byteIndex]; 
    green += rawData[byteIndex + 1]; 
    blue += rawData[byteIndex + 2]; 
    byteIndex += bytesPerPixel; 
} 

free(rawData); 

return [UIColor colorWithRed:red/pixelCount/255.0 green:green/pixelCount/255.0 blue:blue/pixelCount/255.0 alpha:1.0]; 
} 

kDetectorSize被設置爲6,使得所處理的圖像的尺寸6×6像素。其中一個圖像參數也被裁剪爲6x6像素。緩慢的部分是CGContextDrawImage大約需要500-600ms在我的iPhone 4,我想該行一些替代方案:

UIGraphicsPushContext(context); 
[image drawAtPoint:CGPointMake(0.0, 0.0)]; 
UIGraphicsPopContext(); 

UIGraphicsPushContext(context); 
[image drawInRect:CGRectMake(0.0, 0.0, kDetectorSize, kDetectorSize)]; 
UIGraphicsPopContext(); 

兩種方法都是上面那樣的慢。圖像大小沒有顯着影響(我認爲它沒有影響)。 有沒有人知道更快的方式來訪問RGB值?

如果線程不會導致攝像機視圖滯後,那也可以。我打電話給我的線程:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; 
    [NSThread detachNewThreadSelector:@selector(pickColorFromImage:) toTarget:self withObject:image]; 
} 

- (void)pickColorFromImage:(UIImage *)image { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    [NSThread setThreadPriority:0.0]; 

    [...cropping the image...] 
UIColor *averageColor = [self getAverageColorOfImage:croppedImage]; 

    [self performSelectorOnMainThread:@selector(applyPickedColor:) withObject:averageColor waitUntilDone:NO]; 

    [pool release]; 
} 

感謝您的幫助!

回答