Skip to content

Instantly share code, notes, and snippets.

@pcardoso
Created March 10, 2017 10:59
Show Gist options
  • Select an option

  • Save pcardoso/5ecc901062b3ac7e5160bfb308f3fd5f to your computer and use it in GitHub Desktop.

Select an option

Save pcardoso/5ecc901062b3ac7e5160bfb308f3fd5f to your computer and use it in GitHub Desktop.
OpenCV Grabcut implementation in ObjectiveC++
@implementation OpenCVWrapper : NSObject
- (id)initWithImage:(UIImage *)inputImage {
self = [self init];
if (self) {
self.image = inputImage;
self.inputImageMat = [inputImage CVMat3];
self.firstRun = true;
self.mask = cv::Mat(self.inputImageMat.size(), CV_8U, cv::Scalar(GC_PR_BGD));
}
return self;
}
- (UIImage *)processImage {
NSLog(@"image size: %@", NSStringFromCGSize(self.image.size));
NSLog(@"ROI: %@", NSStringFromCGRect(self.rect));
if (!_firstRun) {
[self _addMarkersToMask];
}
grabCut(_inputImageMat,
_mask,
cvRectFromCGRect(_rect),
_bgModel,
_fgModel,
1, // number of iterations
_firstRun ? cv::GC_INIT_WITH_RECT : cv::GC_INIT_WITH_MASK);
self.firstRun = false;
cv::Mat image = _inputImageMat.clone();
// Get the pixels marked as likely foreground AND foreground
cv::Mat maskPrFgd = _mask == cv::GC_PR_FGD;
cv::Mat maskFgd = _mask == cv::GC_FGD;
// Generate output image
cv::Mat foreground(image.size(), CV_8UC3, cv::Scalar(255, 0, 255));
image.copyTo(foreground, maskPrFgd | maskFgd); // bg pixels not copied
// image has magenta on transparent sections. replace before using
return [UIImage imageWithCVMat:foreground];
}
- (void)_addMarkersToMask {
NSLog(@"fg points:");
for (NSValue *r in self.foregroundPoints) {
CGRect rect = r.CGRectValue;
NSLog(@"%@", NSStringFromCGRect(rect));
rectangle(_mask, cvRectFromCGRect(rect), GC_FGD);
}
NSLog(@"bg points:");
for (NSValue *r in self.backgroundPoints) {
CGRect rect = r.CGRectValue;
NSLog(@"%@", NSStringFromCGRect(rect));
rectangle(_mask, cvRectFromCGRect(rect), GC_BGD);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment