我正在创建一个将图片转换为二进制图片的应用。为此,我使用GPUimage框架。 首先,它会将其转换为灰度而不是变化,而不是将其转换为二值化图像。
当我使用灰度和对比度滤镜时,它会产生内存警告,如果我尝试在一个一个应用程序崩溃时转换多个图像(比方说10),会产生内存警告。
这是我的代码:
- (UIImage *) doBinarize:(UIImage *)sourceImage
{
UIImage * grayScaledImg = [self grayImage:sourceImage];
grayScaledImg = [self contrastImage:grayScaledImg];
GPUImagePicture *imageSource = [[GPUImagePicture alloc] initWithImage:grayScaledImg];
GPUImageAdaptiveThresholdFilter *stillImageFilter = [[GPUImageAdaptiveThresholdFilter alloc] init];
stillImageFilter.blurRadiusInPixels = 8.0;
[imageSource addTarget:stillImageFilter];
[imageSource processImage];
UIImage *retImage = [stillImageFilter imageByFilteringImage:grayScaledImg];
UIImage * aretImage = [self sharpenImage:retImage];
[imageSource removeAllTargets];
return aretImage;
}
- (UIImage *) grayImage :(UIImage *)inputImage
{
GPUImageGrayscaleFilter *selectedFilter = [[GPUImageGrayscaleFilter alloc] init];
UIImage *filteredImage = [selectedFilter imageByFilteringImage:inputImage];
return filteredImage;
}
- (UIImage *) sharpenImage :(UIImage *)inputImage
{
GPUImageSharpenFilter *sharpenFilter = [[GPUImageSharpenFilter alloc] init];
[sharpenFilter setSharpness:10];
UIImage *quickFilteredImage = [sharpenFilter imageByFilteringImage: inputImage];
return quickFilteredImage;
}
- (UIImage *) contrastImage :(UIImage *)inputImage
{
GPUImageContrastFilter *contrastfilter =[[GPUImageContrastFilter alloc]init];
[contrastfilter setContrast:3];
UIImage *ima= [contrastfilter imageByFilteringImage:inputImage];
return ima;
}
如果我关闭了灰色和对比度内存警告的代码,那么问题就在那个代码中。
答案 0 :(得分:5)
首先,你在那里做了很多不必要的工作。自适应阈值滤波器(以及所有其他边缘检测或阈值滤波器)自动将其输入转换为灰度,因此不需要。
您不应该与UIImages进行转换,因为每次通过UIImages都需要在CPU上进行昂贵的Core Graphics访问。此外,你将在内存中构建大量的临时UIImage,这可能是你的内存相关崩溃的原因,如果这些崩溃是在循环中累积的。
相反,请将输入图像一次性通过各种过滤器链接:
GPUImagePicture *imageSource = [[GPUImagePicture alloc] initWithImage:sourceImage];
GPUImageContrastFilter *contrastfilter =[[GPUImageContrastFilter alloc]init];
[contrastfilter setContrast:3];
GPUImageAdaptiveThresholdFilter *stillImageFilter = [[GPUImageAdaptiveThresholdFilter alloc] init];
stillImageFilter.blurRadiusInPixels = 8.0;
GPUImageSharpenFilter *sharpenFilter = [[GPUImageSharpenFilter alloc] init];
[sharpenFilter setSharpness:10];
[imageSource addTarget:contrastFilter];
[contrastFilter addTarget:stillImageFilter];
[stillImageFilter addTarget:sharpenFilter];
[sharpenFilter useNextFrameForImageCapture];
[imageSource processImage];
UIImage *outputImage = [sharpenFilter imageFromCurrentFramebuffer];
这将导致您的图像保留在GPU上直到最后一步,并且在框架中使用新的帧缓冲缓存机制,它将限制此处理的内存使用。