2010-02-26 44 views
3

我是iphone軟件開發的初學者。 我開發了皮膚癌的應用程序,我想從UIImage計算或計算紅色像素,這是iphone camera捕獲的。可以從UIImage計數紅色像素嗎?我如何計算使用objective-C在iphone中的UIImage的紅色像素?

+0

看到這個問題:http://stackoverflow.com/questions/448125/how-to-get-pixel-data-from-a-uiimage-cocoa-touch-or-cgimage-core-graphics – 2010-02-26 16:39:14

+2

define「red 「#FF0000'純紅色,但'#FF0001'呢?那是紅色的?那麼'#FF0100'呢?或'#FE0000'?或者'#FF1C41'怎麼樣?這仍然是微紅的... – 2010-11-28 23:15:32

+0

@戴夫德隆,感謝您給我的建議,但我找到了它的巨大解決方案。 – Tirth 2010-11-29 04:39:21

回答

8

由於這是一個幾乎每週都會被問到的問題,因此我決定做一個小例子項目來說明如何做到這一點。你可以看一下代碼爲:

http://github.com/st3fan/iphone-experiments/tree/master/Miscellaneous/PixelAccess/

最重要的一點是下面的代碼,這需要一個UIImage然後計算純紅色的像素數。這是一個例子,你可以使用它,修改它自己的算法:

/** 
* Structure to keep one pixel in RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA format 
*/ 

struct pixel { 
    unsigned char r, g, b, a; 
}; 

/** 
* Process the image and return the number of pure red pixels in it. 
*/ 

- (NSUInteger) processImage: (UIImage*) image 
{ 
    NSUInteger numberOfRedPixels = 0; 

    // Allocate a buffer big enough to hold all the pixels 

    struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel)); 
    if (pixels != nil) 
    { 
     // Create a new bitmap 

     CGContextRef context = CGBitmapContextCreate(
      (void*) pixels, 
      image.size.width, 
      image.size.height, 
      8, 
      image.size.width * 4, 
      CGImageGetColorSpace(image.CGImage), 
      kCGImageAlphaPremultipliedLast 
     ); 

     if (context != NULL) 
     { 
      // Draw the image in the bitmap 

      CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage); 

      // Now that we have the image drawn in our own buffer, we can loop over the pixels to 
      // process it. This simple case simply counts all pixels that have a pure red component. 

      // There are probably more efficient and interesting ways to do this. But the important 
      // part is that the pixels buffer can be read directly. 

      NSUInteger numberOfPixels = image.size.width * image.size.height; 

      while (numberOfPixels > 0) { 
       if (pixels->r == 255) { 
        numberOfRedPixels++; 
       } 
       pixels++; 
       numberOfPixels--; 
      } 

      CGContextRelease(context); 
     } 

     free(pixels); 
    } 

    return numberOfRedPixels; 
} 

如何調用一個簡單的例子:

- (IBAction) processImage 
{ 
    NSUInteger numberOfRedPixels = [self processImage: [UIImage imageNamed: @"DutchFlag.png"]]; 
    label_.text = [NSString stringWithFormat: @"There are %d red pixels in the image", numberOfRedPixels]; 
} 

在Github上的示例項目包含一個完整的工作示例。

+0

嗨St3fan,上面的代碼給我只有恆定的紅色像素(8000)值,即使我改變了照片。 我改變了許多圖像,但它給了我相同的計數值。 – Tirth 2010-02-27 07:13:32

+1

然後你做錯了什麼。代碼工作正常。 – 2010-02-27 14:18:37

+0

嗨St3fan,從上面的代碼我改變圖像DutchFlag.png而不是我自己的.png圖像,但我得到錯誤(Iphone模擬器去調試器)。 – Tirth 2010-03-02 08:43:56

相關問題