转换图像到黑色和白色的IOS?

我发现很多代码将图像转换为纯黑色和白色。 但没有这个工作。

我已经试过这个代码,但它的图像转换为灰度不是黑色和白色。

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

结果图像——————————————->期望的图像

在这里输入图像说明在这里输入图像说明

将图像转换为灰度后,必须对图像进行阈值设置。 由于您的input图像是在明亮的背景上的黑色文字,这应该是直截了当的。 当你阈值灰度图像,你基本上说, “所有像素的强度值超过阈值,应该是白色,而所有其他像素应该是黑色的” 。 这是图像预处理中常用的标准image processing技术。

如果您打算进行image processing,我强烈推荐Brad Larson的GPUImage ,这是一个硬件驱动的Objective-C框架。 它配备了可以使用的阈值filter。

存在各种不同的阈值algorithm,但是如果你的input图像总是与给定的例子类似,我没有理由使用更复杂的方法。 但是,如果存在不均匀照明,噪声或其他干扰因素的风险,则推荐使用自适应阈值或其他dynamicalgorithm。 据我所知,GPUImage的阈值滤波器是自适应的。

我知道这个回答已经太晚了,但是对于那些正在寻找这个代码的人来说可能是有用的

 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; 

谢谢