2

I have a problem with my grabcut algorithm written in Objective-C++ with the OpenCV library. I want to detect balls with grabcut like you can see in this picture:

example picture

Here is my code:

Mat imageMat;
Mat grab;
Mat result;
Mat bgdModel;
Mat fgdModel;

//x,y: user selection
NSInteger xInt = [x integerValue];
NSInteger yInt = [y integerValue];

UIImageToMat(image, imageMat);
cv::cvtColor(imageMat , grab , CV_RGBA2RGB);
cv::Rect rectangle( xInt-125,yInt-125,250,250);

cv::grabCut(grab, result, rectangle, bgdModel, fgdModel, 1, cv::GC_INIT_WITH_RECT );
cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);
cv::Mat foreground(grab.size(),CV_8UC3, cv::Scalar(255,255,255));
result=result&1;
grab.copyTo(foreground, result);
return MatToUIImage(grab);

And here is the error message I get:

Boule(18731,0x1b3b33b40) malloc: *** mach_vm_map(size=1560002560) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc

Do you have an idea what's wrong? Thanks a lot in advance!

Marina
  • 63
  • 6
  • You may be running into a memory leak. Check to see if your application's memory usage grows in task manager. – Mateen Ulhaq Jul 10 '17 at 12:38
  • yes, but I don't understand why... This is a picture taken by my iPhone and I don't know why I'm running into a memory leak. – Marina Jul 10 '17 at 13:21

1 Answers1

1

The code is trying to allocate a huge image, according to the error message.

A few things that I would do straightaway:

  1. replace

    NSInteger xInt = [x integerValue]; NSInteger yInt = [y integerValue];

with

int xInt = [x intValue];
int yInt = [y intValue];

because I am not very sure if cv::Rect() will be getting the actual inputs sent to this method.

  1. Add a check to see if the origin of the rectangle is still within the image, and adjust the rectangle if it is not (grabCut seems to be fine with this, though).

I converted the code to C++, and it runs with no error after getting rid of the NSIntegers. Will update the answer after trying this on a phone, but do try the above changes.

Totoro
  • 3,398
  • 1
  • 24
  • 39
  • thanks, I changed the code to explicit numbers for the rectangle and checked if it appears correctly. It does, but I'm still running in the memory leak. :-/ – Marina Jul 11 '17 at 07:42
  • In that case, I will check it on iOS. Does the crash occur at the line "cv::grabCut(...), or after that? – Totoro Jul 11 '17 at 07:57
  • It ja always this line cv::grabcut(...). Thank you very much! – Marina Jul 11 '17 at 11:30
  • 1
    I solved this issue by scaling down the original UIImage based on this answer: https://stackoverflow.com/a/55327458/3151675 – Tamás Sengel Nov 19 '21 at 00:40