11

次のコードを使用して、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 imageは次のようになります

- (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, 0, cols, rows), imge.CGImage);
    CGContextRelease(contextRef);
    CGColorSpaceRelease(colorSpace);

    return cvMat;
}

しかし、私はエラーが発生しました

OpenCV エラー: グラブカットの引数が正しくありません (イメージには CV_8UC3 タイプが必要です)。

cv::Mat cvMat(rows, cols, CV_8UC4);行をに変更 するとcv::Mat cvMat(rows, cols, CV_8UC3); 、 が得られ<Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 32 bits/pixel; 3-component color space; kCGImageAlphaNoneSkipLast; 342 bytes/row.ます。

ここでどうしようか迷っています。

助けてください

4

1 に答える 1

18

問題は、取得した画像にアルファ チャネルがあるのに対し、グラブカットはアルファ チャネルのない RGB 画像を想定していることです。したがって、追加のチャネルを取り除く必要があります。

たとえば、次の関数を使用してこれを行うことができます。

cv::cvtColor(img , img , CV_RGBA2RGB);
于 2013-05-14T11:04:44.340 に答える