【问题标题】:OpenCV code causes leaks of UIImagesOpenCV 代码导致 UIImage 泄漏
【发布时间】:2014-09-09 15:22:44
【问题描述】:

我正在使用 OpenCV 在 iOS 上进行实时视频处理,而不使用 CvVideoCamera。由于内存压力,我的应用程序崩溃了。

iOS 原生摄像头每抓到一帧就会调用这个函数:

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    //convert the frame to a UIImage:
    UIImage *image = [self imageFromSampleBuffer:sampleBuffer];

    //convert the UIImage to a Mat:
    Mat srcMat = [self cvMatFromUIImage:image];

    //Process the Mat:
    Mat dst, cdst;
    Canny(srcMat, dst, 50, 200, 3);
    cvtColor(dst, cdst, COLOR_GRAY2BGR);
}

由于内存压力,应用程序在大约 15 秒后崩溃。

我正在使用Apple's code for imageFromSampleBuffer:OpenCV's code for cvMatFromUIImage。是的,我正在使用 ARC。

我使用 Allocations Instrument 分析了应用程序,发现崩溃是由于创建了大量 UIImage 而从未发布过。经过一番调查,我发现对Canny() 的调用是造成这种情况的原因,因为当对Canny() 的调用被注释掉时,UIImage 对象不会泄漏。

为什么对 Canny 的调用会使 UIImage 对象留在内存中?

【问题讨论】:

  • 我的印象是UIImage *image = [self imageFromSampleBuffer:sampleBuffer]; 不分配动态内存。它不只是创建一个指向现有内存位置的指针吗?但如果你是对的并且这确实发生了,请放心,它不应该是一个指针。您可以自己进行修复。这是什么版本的 OpenCV?
  • 嗨@karphillip。这是 OpenCV 2.4.9。 imageFromSampleBuffer 只是将 CMSampleBufferRef 转换为 UIImage。正如你在its code 中看到的那样,它会将其转换为Quartz Image,然后将其提供给+[UIImage imageWithCGImage:],从而分配一个新的UIImage。它确实会自行清理内存。但是泄漏来自对Canny()的调用。

标签: ios opencv memory-management uiimage


【解决方案1】:
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{

    CFRetain(sampleBuffer);

    dispatch_queue_t myQueue = dispatch_queue_create("my.dispatch.q", 0);
    dispatch_async(myQueue,
    ^{
        //convert the frame to a UIImage:
        UIImage *image = [self imageFromSampleBuffer:sampleBuffer];

        //convert the UIImage to a Mat:
        Mat srcMat = [self cvMatFromUIImage:image];

        //Process the Mat:
        Mat dst, cdst;
        Canny(srcMat, dst, 50, 200, 3);
        cvtColor(dst, cdst, COLOR_GRAY2BGR);
        CFRelease(sampleBuffer);
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2012-01-18
    • 2010-12-19
    • 1970-01-01
    相关资源
    最近更新 更多