Search code examples
iosobjective-cgpuimage

How do i make an image Black & White?


How do i make an image Black & White? Using GPUImage library or default IOS framework. I tried code below but not getting expected result. Any third party library or code snippet help is highly appreciated

  -(UIImage *)convertOriginalImageToBWImage:(UIImage *)originalImage
{
    UIImage *newImage;
    CGColorSpaceRef colorSapce = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, originalImage.size.width * originalImage.scale, originalImage.size.height * originalImage.scale, 8, originalImage.size.width * originalImage.scale, colorSapce, kCGImageAlphaNone);
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetShouldAntialias(context, NO);
    CGContextDrawImage(context, CGRectMake(0, 0, originalImage.size.width, originalImage.size.height), [originalImage CGImage]);

    CGImageRef bwImage = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSapce);

    UIImage *resultImage = [UIImage imageWithCGImage:bwImage];
    CGImageRelease(bwImage);

    UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, originalImage.scale);
    [resultImage drawInRect:CGRectMake(0.0, 0.0, originalImage.size.width, originalImage.size.height)];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


    return newImage;
}

Solution

  • There are a number of filters in the GPUImage framework that process a source image to a binary b&w one.

    Here's the list of filters with the copy pasted description from the GPUImage framework homepage:

    • GPUImageMonochromeFilter: Converts the image to a single-color version, based on the luminance of each pixel

      • intensity: The degree to which the specific color replaces the normal image color (0.0 - 1.0, with 1.0 as the default)
      • color: The color to use as the basis for the effect, with (0.6, 0.45, 0.3, 1.0) as the default.
    • GPUImageLuminanceThresholdFilter: Pixels with a luminance above the threshold will appear white, and those below will be black

      • threshold: The luminance threshold, from 0.0 to 1.0, with a default of 0.5
    • GPUImageAdaptiveThresholdFilter: Determines the local luminance around a pixel, then turns the pixel black if it is below that local luminance and white if above. This can be useful for picking out text under varying lighting conditions.

      • blurRadiusInPixels: A multiplier for the background averaging blur radius in pixels, with a default of 4.
    • GPUImageAverageLuminanceThresholdFilter: This applies a thresholding operation where the threshold is continually adjusted based on the average luminance of the scene.

      • thresholdMultiplier: This is a factor that the average luminance will be multiplied by in order to arrive at the final threshold to use. By default, this is 1.0.