将图像转换为黑白IOS?

时间:2014-04-09 19:40:45

标签: ios objective-c core-graphics

我找到了很多将图像转换为纯黑色和白色的代码。但这一切都没有。

我已经尝试过这段代码但是它将图像转换为灰度而不是黑白。

  -(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;
}

结果图片------------------------------------------->预期图像

enter image description here - enter image description here

2 个答案:

答案 0 :(得分:4)

将图像转换为灰度后,您必须threshold图像。由于输入图像是明亮背景上的暗文本,因此应该是直接的。当您对灰度图像进行阈值处理时,基本上就是说“强度值高于阈值t的所有像素应为白色,而所有其他像素应为黑色”。这是一种标准的图像处理技术,通常用于图像预处理。

如果您打算进行图像处理,我强烈推荐Brad Larson的GPUImage,它是为此目的而制作的硬件驱动的Objective-C框架。它配备了可以使用的阈值滤波器。

存在各种不同的阈值算法,但如果您的输入图像总是与给出的示例相似,我认为没有理由使用更复杂的方法。但是,如果存在不均匀照明,噪声或其他干扰因素的风险,建议使用adaptive thresholding或其他动态算法。据我所知,GPUImage的阈值滤波器是自适应的。

答案 1 :(得分:3)

我知道现在回答太迟了,但对于正在寻找此代码的其他人来说可能会有用

UIImage *image = [UIImage imageNamed:@"Image.jpg"];
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = image;
UIGraphicsBeginImageContextWithOptions(imageView.size, YES, 1.0);
CGRect imageRect = CGRectMake(0, 0, imageView.size.width, imageView.size.height);
// Draw the image with the luminosity blend mode.
[image drawInRect:imageRect blendMode:kCGBlendModeLuminosity alpha:1.0];
// Get the resulting image.
UIImage *filteredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageView.image = filteredImage;

谢谢

相关问题