title: iOS + OpenCV - Mat memory leak
body: <p>I am using OpenCV 2.2 compiled and built from source for iOS. I used this <a href="http://niw.at/articles/2009/03/14/using-opencv-on-iphone/en" rel="nofollow">blog post</a> as a guide.</p>
  
  <p>I have played around with getting some stuff to work like making images grayscale, blurring them and even running FAST. My problem however is that my code is leaking memory and this very quickly causes the app to be killed when run on a device.</p>
  
  <p>From the blog post above I use the code below to turn a UIImage into an IplImage</p>
  
  <pre><code>+ (IplImage *)IplImageFromUIImage:(UIImage *)image 
  {
      // NOTE you SHOULD cvReleaseImage() for the return value when end of the code.
      CGImageRef imageRef = image.CGImage;
  
      CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
      IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 4);
      CGContextRef contextRef = CGBitmapContextCreate(iplimage-&gt;imageData, iplimage-&gt;width, iplimage-&gt;height,
                                                      iplimage-&gt;depth, iplimage-&gt;widthStep,
                                                      colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault);
      CGContextDrawImage(contextRef, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);
      CGContextRelease(contextRef);
      CGColorSpaceRelease(colorSpace);
  
      IplImage *ret = cvCreateImage(cvGetSize(iplimage), IPL_DEPTH_8U, 3);
      cvCvtColor(iplimage, ret, CV_RGBA2RGB);
  
      cvReleaseImage(&amp;iplimage);
  
      return ret;
  }
  </code></pre>
  
  <p>This works fine and does not seem to leak any memory however since I am using OpenCV 2.2 I am trying to use the C++ interface so I created the function below.</p>
  
  <pre><code>+ (Mat)MatFromUIImage:(UIImage *)image
  {
      IplImage *iplImage = [self IplImageFromUIImage:image];
      Mat result(iplImage, true);
      cvReleaseImage(&amp;iplImage);
      return result;
  }
  </code></pre>
  
  <p>Once I start using this method my app starts leaking and consequently gets killed.</p>
  
  <p>Any ideas on what I am doing wrong?</p>