OpenCV MatToUIImage causes memory leak

让人想犯罪 __ 提交于 2019-12-06 01:49:37

Important update (5.06.2017) Finally, to perform CFRelease manually turned out to be bad idea as it can raise more troubles than solve! Though, it gave me a clue that leaks are somehow connected with NSData (not-)releasing.

I noticed that it's released automatically as expected with ARC when called from block in background thread, like that:

- (void)runInBackgroundWithImageBuffer:(CVImageBufferRef)imageBuffer
                              callback:(void (^)())callback {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        [self processImageBuffer:imageBuffer];
        if (callback != nil) {
            callback();
        }
    });
}

- (void)previewOpenCVImage:(cv::Mat *)image {
    UIImage *preview = MatToUIImage(*image);

    dispatch_async(dispatch_get_main_queue(), ^{
        // _imagePreview has (UIImageView *) type
        [_imagePreview setImage:preview];
    });
}

I can confirm that for iPhone Simulator. Seems like current MatToUIImage implementation causes memory leaks on simulator. And I can't reproduce it on device.

For some reason they are not detected by profiler but memory usage just blows up after multiple calls.

I've added some tweaks to make it working:

  1. Add line CFRelease((CFTypeRef)data) before returning final image

  2. When image is not necessary we need to perform CFRelease(image.CGImage) and probably CFRelease((CFTypeRef)image)

Hope that helps. Actually I don't completely understand why this is happening, who is holding references and why do we need to manually perform release.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!