【问题标题】:Convert RGB image to 1 channel image (black/white)将 RGB 图像转换为 1 通道图像(黑/白)
【发布时间】:2013-03-17 14:45:50
【问题描述】:

如何使用 ios5 将 RGB 图像转换为 1 通道图像(黑/白)?

输入图像通常是书页的照片。 目标是通过将复印件转换为 1 通道图像来减小复印件的大小。

【问题讨论】:

  • 灰度不完全是黑白图像。我只需要输出图像矩阵中每个像素的两个值,而不是 256
  • AFAIK,灰度是单通道图像(也是)。您应该更准确地定义问题。
  • 是的,你是对的,因此我提到了黑白而不是灰度 :) 但也许有点模棱两可,谢谢!

标签: ios ios5 core-image


【解决方案1】:

如果我理解您的问题,您想根据像素的亮度对图像应用黑白阈值。要快速完成此操作,您可以使用我的开源 GPUImage 项目(支持回 iOS 4.x)和它提供的一些图像处理操作。

特别是,GPUImageLuminanceThresholdFilter 和 GPUImageAdaptiveThresholdFilter 可能是您在这里寻找的。前者根据您设置的亮度阈值(默认值为 50%)将像素变为黑色或白色。后者在应用此阈值时会考虑局部平均亮度,这可以为书页上的文本产生更好的效果。

在 UIImage 上使用这些过滤器非常简单:

UIImage *inputImage = [UIImage imageNamed:@"book.jpg"];
GPUImageLuminanceThresholdFilter *thresholdFilter = [[GPUImageLuminanceThresholdFilter alloc] init];
UIImage *quickFilteredImage = [thresholdFilter imageByFilteringImage:inputImage];

这些也可以应用于实时相机源和相机拍摄的照片。

【讨论】:

  • 这太棒了!谢谢!
【解决方案2】:

您可以使用 Core Image 将图像处理为黑白。

使用CIEdgeWork,这会将您的图像转换为黑白

有关核心图像编程的更多信息,请访问:- https://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/CoreImaging/ci_tasks/ci_tasks.html#//apple_ref/doc/uid/TP30001185-CH3-TPXREF101

你要找的代码大概是这样的:

CIContext *context = [CIContext contextWithOptions:nil]; // 1
CIImage *image = [CIImage imageWithContentsOfURL:myURL]; // 2
CIFilter *filter = [CIFilter filterWithName:@"CIEdgeWork"]; // 3
[filter setValue:image forKey:kCIInputImgeKey];
[filter setValue:[NSNumber numberWithFloat:0.8f] forKey:@"InputIntensity"];
CIImage *result = [filter valueForKey:kCIOutputImageKey]; // 4
CGImageRef cgImage = [context createCGImage:result fromRect:[result extent];

【讨论】:

【解决方案3】:

这里有一些示例代码,可能会有所帮助:

@implementation UIImage (GrayImage)

-(UIImage*)grayImage
{
    int width = self.size.width;
    int height = self.size.height;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate
(nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);

    if (context == NULL) {
        return nil;
    }

    CGContextDrawImage(context,CGRectMake(0, 0, width, height), self.CGImage);
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage *grayImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    CGContextRelease(context);

    return grayImage;
}

@end

我只是把它写成 UIImage 的一个类别,但不支持具有透明像素的 png 图像,否则它将是黑色的。

【讨论】:

  • 黑白(1位)与灰度不同。
猜你喜欢
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多