2014-04-09 126 views
-1

我发现很多代码将图像转换为纯黑色和白色。但没有这个工作。转换图像为黑色和白色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; 
} 

Result image ----------------------------------------- - >期望图像

enter image description here - enter image description here

回答

4

你将不得不threshold像你已经将它转换成灰度后。由于您的输入图像在明亮的背景上为黑色文字,因此应该直截了当。当您阈值灰度图像时,基本上是说“强度值超过阈值t的所有像素应该是白色,而所有其他像素应该是黑色”。这是一种标准图像处理技术,通常用于图像预处理。

如果您打算进行图像处理,我强烈建议Brad Larson的GPUImage,这是一个硬件驱动的Objective-C框架。它配备了可随时使用的阈值过滤器。

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

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; 

有用来不及感谢您

相关问题