2014-09-25 26 views
0

我正在检查UIImage是否较暗或较白。我想使用这种方法,但只能检查图像的第三个底部,而不是全部。 我不知道如何改变它来检查,我不熟悉像素的东西。检查图像是否只有深色底部

BOOL isDarkImage(UIImage* inputImage){ 

     BOOL isDark = FALSE; 

     CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(inputImage.CGImage)); 
     const UInt8 *pixels = CFDataGetBytePtr(imageData); 

     int darkPixels = 0; 

     long length = CFDataGetLength(imageData); 
     int const darkPixelThreshold = (inputImage.size.width*inputImage.size.height)*.25; 

//should i change here the length ? 
     for(int i=0; i<length; i+=4) 
     { 
      int r = pixels[i]; 
      int g = pixels[i+1]; 
      int b = pixels[i+2]; 

      //luminance calculation gives more weight to r and b for human eyes 
      float luminance = (0.299*r + 0.587*g + 0.114*b); 
      if (luminance<150) darkPixels ++; 
     } 

     if (darkPixels >= darkPixelThreshold) 
      isDark = YES; 

我只能裁剪图像的那一部分,但这不是有效的方式,并浪费时间。

回答

2

solution marked correct here是获取像素数据(更容忍不同格式)的更周到的方法,也演示了如何处理像素。有了一个小的调整,就可以得到图像的底部如下:

+ (NSArray*)getRGBAsFromImage:(UIImage*)image 
          atX:(int)xx 
         andY:(int)yy 
          toX:(int)toX 
          toY:(int)toY { 

    // ... 
    int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel; 
    int byteIndexEnd = (bytesPerRow * toY) + toX * bytesPerPixel; 
    while (byteIndex < byteIndexEnd) { 
     // contents of the loop remain the same 

    // ... 
} 

为了获得图像的倒数第三,与xx=0yy=2.0*image.height/3.0toXtoY等于图像的宽度和高度调用此方法,分别。循环返回数组中的颜色并按照您的帖子建议计算亮度。

+0

非常感谢,这很好的答案。 – Curnelious 2014-09-25 14:29:11

+0

很高兴帮助。未来的读者应该注意到,这种方法不会从图像数据中获取任何矩形的像素值。相反,它需要在参数暗示的“点”之间扫描线。 – danh 2014-09-25 14:37:11