我使用以下代码使用grabCut算法:
cv::Mat img=[self cvMatFromUIImage:image]; cv::Rect rectangle(10,10,300,150); cv::Mat result; // segmentation (4 possible values) cv::Mat bgModel,fgModel; // the models (internally used) // GrabCut segmentation cv::grabCut(img,// input image result,// segmentation result rectangle,// rectangle containing foreground bgModel,fgModel,// models 3,// number of iterations cv::GC_INIT_WITH_RECT); // use rectangle // Get the pixels marked as likely foreground cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ); // Generate output image cv::Mat foreground(img.size(),CV_8UC3,cv::Scalar(255,255,255)); result=result&1; img.copyTo(foreground,result); result); image=[self UIImageFromCVMat:foreground]; ImgView.image=image;
将UIImage转换为Mat图像的代码如下所示
- (cv::Mat)cvMatFromUIImage:(UIImage *)imge { CGColorSpaceRef colorSpace = CGImageGetColorSpace(imge.CGImage); CGFloat cols = imge.size.width; CGFloat rows = imge.size.height; cv::Mat cvMat(rows,cols,CV_8UC4); // 8 bits per component,4 channels CGContextRef contextRef = CGBitmapContextCreate( cvMat.data,// Pointer to data cols,// Width of bitmap rows,// Height of bitmap 8,// Bits per component cvMat.step[0],// Bytes per row colorSpace,// Colorspace kCGImageAlphaNoneSkipLast | kCGBitmapByteOrderDefault); // Bitmap info flags CGContextDrawImage(contextRef,CGRectMake(0,rows),imge.CGImage); CGContextRelease(contextRef); CGColorSpaceRelease(colorSpace); return cvMat; }
但我得到了错误
OpenCV Error: Bad argument (image must have CV_8UC3 type) in grabCut.
如果我改变
cv :: Mat cvMat(rows,CV_8UC4); line to cv :: Mat cvMat(rows,CV_8UC3);
然后我得到<错误>:CGBitmapContextCreate:不支持的参数组合:8个整数位/组件; 32位/像素; 3组分色彩空间; kCGImageAlphaNoneSkipLast; 342字节/行..
我在这里感到很困惑.
请帮忙