【发布时间】: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