2012-01-21 66 views
0

我有一張圖片!自從我完成了像素檢測後,我記得你必須以某種方式將像素轉換爲數組,然後找到圖像的寬度,以瞭解像素何時到達一行的末尾並轉到下一個像素和啊,很多複雜的東西哈哈!無論如何,我現在不知道如何做到這一點了,但我需要檢測我的圖像名爲「image1」的y座標的最左邊最暗的像素的x & ...任何好的起始位置?檢測圖像上的大部分黑色像素 - objective-c iOS

回答

2

轉到您的書店,找到Erica Sadun編寫的名爲「iOS Developer's Cookbook」的書。轉到第378頁,並且在那裏有用於像素檢測的方法。你可以看看這個RGB值的數組,並運行一個for循環來排序並找到具有最小R,G和B值之和(這將是0-255)的像素,這將給你最接近黑色的像素。 如果需要,我也可以發佈代碼。但這本書是最好的資料來源,因爲它提供了方法和解釋。

這些是我的一些變化。方法名稱保持不變。我改變的是基本上來自圖像選擇器的圖像。

-(UInt8 *) createBitmap{ 
if (!self.imageCaptured) { 
     NSLog(@"Error: There has not been an image captured."); 
     return nil; 
    } 
    //create bitmap for the image 
    UIImage *myImage = self.imageCaptured;//image name for test pic 
    CGContextRef context = CreateARGBBitmapContext(myImage.size); 
    if(context == NULL) return NULL; 
    CGRect rect = CGRectMake(0.0f/*start width*/, 0.0f/*start*/, myImage.size.width /*width bound*/, myImage.size.height /*height bound*/); //original 
// CGRect rect = CGRectMake(myImage.size.width/2.0 - 25.0 /*start width*/, myImage.size.height/2.0 - 25.0 /*start*/, myImage.size.width/2.0 + 24.0 /*width bound*/, myImage.size.height/2.0 + 24.0 /*height bound*/); //test rectangle 

    CGContextDrawImage(context, rect, myImage.CGImage); 
    UInt8 *data = CGBitmapContextGetData(context); 
    CGContextRelease(context);  
    return data; 
} 
CGContextRef CreateARGBBitmapContext (CGSize size){ 

    //Create new color space 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    if (colorSpace == NULL) { 
     fprintf(stderr, "Error allocating color space\n"); 
     return NULL; 
    } 
    //Allocate memory for bitmap data 
    void *bitmapData = malloc(size.width*size.height*4); 
    if(bitmapData == NULL){ 
     fprintf(stderr, "Error: memory not allocated\n"); 
     CGColorSpaceRelease(colorSpace); 
     return NULL; 
    } 
    //Build an 8-bit per channel context 
    CGContextRef context = CGBitmapContextCreate(bitmapData, size.width, size.height, 8, size.width*4, colorSpace, kCGImageAlphaPremultipliedFirst); 
    CGColorSpaceRelease(colorSpace); 
    if (context == NULL) { 
     fprintf(stderr, "Error: Context not created!"); 
     free(bitmapData); 
     return NULL; 
    } 
    return context; 

} 
NSUInteger blueOffset(NSUInteger x, NSUInteger y, NSUInteger w){ 
    return y*w*4 + (x*4+3); 
} 
NSUInteger redOffset(NSUInteger x, NSUInteger y, NSUInteger w){ 
    return y*w*4 + (x*4+1); 
} 

底部,redOffset的方法,將讓你在ARGB(阿爾法 - 紅 - 綠 - 藍)規模的紅色值。要更改ARGB中查看的通道,請將添加到redOffset函數中x變量的值更改爲0以查找alpha,將其保持爲1以找到紅色,將其保持爲1以找到綠色,將其保留爲2以找到藍色。這是可行的,因爲它只是查看上述方法中創建的數組,以及對x索引值的補充。本質上,使用三種顏色(紅色,綠色和藍色)的方法,並找出每個像素的總和。無論哪個像素最低的紅色,綠色和藍色都是最黑的。

+0

啊!祝你好運!我有Erica的書「iPhone Developer's Cookbook」,但不是「iOS Developer's Cookbook」啊! :(哈哈!介意分享一些像素檢測方法的名稱? –

+0

這太棒了!但是如何檢測MOST黑色值?如果我沒有一個絕對黑色的像素,我該如何檢測下一個最接近黑色的顏色? –

+0

我發現了一種非常不同的方法,它適用於我...但這確實回答了問題! –