OpenCV GrabCut面具

时间:2017-02-26 16:57:21

标签: c++ opencv computer-vision image-segmentation

我利用OpenCV GrabCut功能执行图像分割。当按照以下代码查看分割图像时,分割是合理/正确的。但是,在查看(尝试使用)segmrntation掩码值时,我得到一些非常大的数字,而不是cv::GrabCutClasses enum所期望的枚举值。

void doGrabCut(){
        Vector2i imgDims = getImageDims();

        //Wite image to OpenCV Mat.
        const Vector4u *rgb = getRGB();
        cv::Mat rgbMat(imgDims.height, imgDims.width, CV_8UC3);
        for (int i = 0; i < imgDims.height; i++) {
            for (int j = 0; j < imgDims.width; j++) {
                int idx = i * imgDims.width + j;
                rgbMat.ptr<cv::Vec3b>(i)[j][2] = rgb[idx].x;
                rgbMat.ptr<cv::Vec3b>(i)[j][1] = rgb[idx].y;
                rgbMat.ptr<cv::Vec3b>(i)[j][0] = rgb[idx].z;
            }
        }

        //Do graph cut.
        cv::Mat res, fgModel, bgModel;
        cv::Rect bb(bb_begin.x, bb_begin.y, bb_end.x - bb_begin.x, bb_end.y - bb_begin.y);
        cv::grabCut(rgbMat, res, bb, bgModel, fgModel, 10, cv::GC_INIT_WITH_RECT);
        cv::compare(res, cv::GC_PR_FGD, res, cv::CMP_EQ);

        //Write mask.
        Vector4u *maskPtr = getMask();//uchar
        for (int i = 0; i < imgDims.height; i++) {
            for (int j = 0; j < imgDims.width; j++) {
                cv::GrabCutClasses classification = res.at<cv::GrabCutClasses>(i, j);
                int idx = i * imgDims.width + j;
                std::cout << classification << std::endl;//Strange numbers here.
                maskPtr[idx].x = (classification == cv::GC_PR_FGD) ? 255 : 0;//This always evaluates to 0.
            }
        }

        cv::Mat foreground(rgbMat.size(), CV_8UC3, cv::Scalar(255, 255, 255));
        rgbMat.copyTo(foreground, res);
        cv::imshow("GC Output", foreground);
}

为什么当分段在定性上正确时,会在枚举之外得到数字?

1 个答案:

答案 0 :(得分:0)

我怀疑您的//Write mask.步骤,为什么要重新res并将maskPtr修改为maskPtr[idx].x = (classification == cv::GC_PR_FGD) ? 255 : 0;,基本上您已经存储了单通道二进制图像在res变量中,cv::compare()返回二进制图像

但是,如果您仍想通过迭代调试值,则应使用标准技术迭代单个通道图像:

for (int i = 0; i < m.rows; i++) {
    for (int j = 0; j < m.cols; j++) {
        uchar classification = res.at<uchar>(i, j);
        std::cout << int(classification) << ", ";
    }
}

当您在迭代单个频道时,您必须使用res.at<uchar>(i, j)而不是res.at<cv::GrabCutClasses>