0

I am checking if UIImage is darker or more whiter . I would like to use this method ,but only to check the third bottom part of the image ,not all of it . I wonder how exactly to change it to check that,i am not that familiar with the pixels stuff .

    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;

I can just crop that part of the image, but this will be not efficient way, and wast time .

Curnelious
  • 1
  • 16
  • 76
  • 150

1 Answers1

2

The solution marked correct here is a more thoughtful approach for getting the pixel data (more tolerant of differing formats) and also demonstrates how to address pixels. With a small adjustment, you can get the bottom of the image as follows:

+ (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

    // ...
}

To get the bottom third of the image, call this with xx=0, yy=2.0*image.height/3.0 and toX and toY equal to the image width and height, respectively. Loop the colors in the returned array and compute luminance as your post suggests.

Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136
  • glad to help. future readers should note that this method doesn't grab any rectangle's worth of pixel from the image data. rather, it takes scan lines between the "points" implied by the params. – danh Sep 25 '14 at 14:37