Opencv c ++检测并裁剪图像上的白色区域

时间:2014-04-28 14:56:31

标签: c++ opencv crop detection

我搜索过网络,我已经找到了一些方法来做我想做的事情,但这些方法与我需要的方法相比效率低下。

我有一个kinect(使用Microsoft SDK),目前正在获取一个删除背景的人,将结果保存在3通道垫中,并将该人从后台删除。现在我需要裁剪图像以仅适合那个人,忽略黑色区域。

这里有一个棘手的部分:我没有太多时间浪费在每一次操作上(我还需要做其他一些操作,这是实时工作的。我目前实现的是一个轮廓查找器给出了只有这个区域,但实际上它真的很慢。因为我只有一个白色区域做检测,并且该区域非常大(图像区域的50%)我认为有一些更快的方法来做到这一点,因为我只想要裁剪此白色区域的x和y的最小值和最大值。

这是我目前的裁剪功能:

cv::Mat thresh_canny;
cv::vector<cv::vector<cv::Point> > contours;
cv::vector<cv::Vec4i> hierarchy;
cv::threshold(src, thresh_canny, 0, 255, 0);
cv::Canny(thresh_canny, thresh_canny, 20, 80, 3);
cv::findContours(thresh_canny, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

if (contours.size() != 1)
    return false;

cv::Rect r = cv::boundingRect(contours.at(0));
src(r).copyTo(dst);
return true;

非常感谢!!

编辑:输入图片

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您的图像没有非黑色异常值(如噪声),您可以忽略canny和findContours,而只是从所有非黑色像素位置创建边界矩形:

int main()
{
cv::Mat in = cv::imread("CropWhite.jpg");

// vector with all non-black point positions
std::vector<cv::Point> nonBlackList;
nonBlackList.reserve(in.rows*in.cols);

// add all non-black points to the vector
//TODO: there are more efficient ways to iterate through the image
for(int j=0; j<in.rows; ++j)
    for(int i=0; i<in.cols; ++i)
    {
        // if not black: add to the list
        if(in.at<cv::Vec3b>(j,i) != cv::Vec3b(0,0,0))
        {
            nonBlackList.push_back(cv::Point(i,j));
        }
    }

// create bounding rect around those points
cv::Rect bb = cv::boundingRect(nonBlackList);

// display result and save it
cv::imshow("found rect", in(bb));
cv::imwrite("CropWhiteResult.png", in(bb));


cv::waitKey(-1);
return 0;
}

不知道是否有更有效的方法来创建矢量,在openCV中给出,但这仍然比canny和findContours快得多。

使用此输入:

enter image description here

我得到了这个结果:

enter image description here

轮廓周围有一些区域,因为你提供了一个jpg图像,其中轮廓的边框因压缩而不是黑色,我猜。