【问题标题】:CIFilter output image is showing previous output image at randomCIFilter 输出图像随机显示先前的输出图像
【发布时间】:2016-05-16 12:01:30
【问题描述】:

我发现 CIFilter 与 CIGaussianBlur 过滤器的行为非常奇怪。

我正在为不同的图像快速连续多次执行此方法。有时,会返回“最后处理的图像”而不是我发送的那个。例如,如果我有图像:

ABC

如果我快速连续执行模糊,有时我会得到如下结果:

模糊 A模糊 A模糊 C

+(UIImage *)applyBlurToImageAtPath:(NSURL *)imageUrlPath
{
    if (imageUrlPath == nil)
        return nil;

    //Tried to create new contexts each loop, and also tried to use a singleton context
    //    if(CIImageContextSingleton == nil)
    //    {
    //        CIImageContextSingleton = [CIContext contextWithOptions:nil];
    //    }
    CIContext *context = [CIContext contextWithOptions:nil];//[Domain sharedInstance].CIImageContextSingleton;

    CIFilter *gaussianBlurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [gaussianBlurFilter setDefaults];
    CIImage *inputImage = [CIImage imageWithContentsOfURL:imageUrlPath];
    [gaussianBlurFilter setValue:inputImage forKey:kCIInputImageKey];
    [gaussianBlurFilter setValue:@(1) forKey:kCIInputRadiusKey];

    //Tried both these methods for getting the output image
    CIImage *outputImage = [gaussianBlurFilter valueForKey:kCIOutputImageKey];
//    CIImage *outputImage = [gaussianBlurFilter outputImage];

    //If I'm doing this, the problem never occurs, so the problem is isolated to the gaussianBlurFilter:
    //outputImage = inputImage;

    CGImageRef cgimg     = [context createCGImage:outputImage fromRect:[inputImage extent]];
    UIImage *resultImage = [UIImage imageWithCGImage:cgimg];

    //Tried both with and without releasing the cgimg
    CGImageRelease(cgimg);

    return resultImage;
}

我已经在循环中尝试过,并且在做出手势等时运行该方法,并且出现了同样的问题。 (imageUrlPath 处的图像是正确的。)另外,请参阅代码中的 cmets 了解我尝试过的内容。

我错过了什么吗? CIFilter 是否有一些内部缓存?该方法始终在主线程上运行。

【问题讨论】:

  • 介意告诉我投反对票的原因吗?我很乐意改进这一点。仅仅因为它是一个重要的问题并且很难解释它不应该成为反对的目标。

标签: ios uiimage core-image cifilter ciimage


【解决方案1】:

根据给出的代码,并假设这个方法总是在主线程上调用,你应该没问题,但我确实看到代码中的一些不明智的事情:

  • 不要在每次调用该方法时重新创建您的CIContext。我建议以不同的方式构建,而不是作为单例。保留您的 CIContext,并在执行大量渲染时重复使用相同的上下文。
  • 如果你的CIFilter 没有改变,也不需要每次都重新创建。如果您在同一个线程上调用该方法,您可以简单地在过滤器上设置inputImage 键。每当更改输入图像时,您都需要从过滤器中获取新的outputImage

我的猜测是,问题可能是围绕核心图像上下文渲染到相同的底层图形环境(可能是 GPU 渲染),但由于您不断地重新创建 CIContext,因此可能会发生一些不正常的事情。

只是一个猜测,因为我没有方便的代码来测试自己。如果您有一个演示问题的测试项目,那么调试起来会更容易。另外-我仍然对线程持怀疑态度。它在不应用模糊的情况下工作的事实并不一定证明它是导致问题的模糊——根据我的经验,随机性更有可能涉及线程问题。

【讨论】:

  • 感谢您的回答。该问题现已通过使用高斯模糊代码 sn-p 得到解决。
猜你喜欢
  • 2015-04-07
  • 1970-01-01
  • 2019-05-16
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 2020-06-11
  • 2014-05-15
  • 2020-05-11
相关资源
最近更新 更多