opencv学习笔记(六)寻找凸包和分水岭算法

凸包检测

    cv::Mat src = cv::imread("1.jpg");
    if (!src.data)
    {
        cout << "error" << endl;
        return -1;
    }
    cv::Mat gray, dst, thresholdImage;
    cv::RNG rng(12345);
    vector<vector<cv::Point> > contours;//用于存放找到的轮廓
    // 将原图转换成灰度图并进行模糊降
    cv::cvtColor(src, gray, cv::COLOR_BGR2GRAY);
    cv::blur(gray, gray, cv::Size(3, 3));
    // 对图像进行二值化,控制阈值
    cv::threshold(gray, thresholdImage, 170, 255, CV_THRESH_BINARY);
    // 寻找轮廓
    cv::findContours(thresholdImage, //输入图像,需为二进制8位单通道图像
                     contours, //检测到的轮廓
                     CV_RETR_TREE, //轮廓检索模式
                     CV_CHAIN_APPROX_SIMPLE); //轮廓的近似方法         
    // 遍历每个轮廓,寻找其凸包
    vector<vector<cv::Point>>hull(contours.size());
    for (unsigned int i = 0; i < contours.size(); i++)
    {
        cv::convexHull(cv::Mat(contours[i]), //输入的二维点集
                       hull[i], //找到的凸包
                       false);//标识符为真时,输出的凸包为顺时针方向,否则,就为逆时针方向
    }
    // 绘出轮廓及其凸包
    dst = cv::Mat::zeros(thresholdImage.size(), CV_8UC3);
    for (unsigned int i = 0; i< contours.size(); i++)
    {
        cv::Scalar color = cv::Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
        drawContours(dst, contours, i, color, 1, 8, vector<cv::Vec4i>(), 0, cv::Point());
        drawContours(dst, hull, i, color, 1, 8, vector<cv::Vec4i>(), 0, cv::Point());
    }
    cv::imshow("原图", src);
    cv::imshow("凸包检测效果图", dst);

分水岭算法

Mat g_maskImage, g_srcImage;
Point prevPt(-1, -1);

static void on_Mouse(int event, int x, int y, int flags, void*);
int main(int argc, _TCHAR* argv[])
{
    g_srcImage = cv::imread("1.jpg");
    if (!g_srcImage.data)
    {
        cout << "error" << endl;
        return -1;
    }
    imshow("原图", g_srcImage);
    Mat srcImage, grayImage;
    g_srcImage.copyTo(srcImage);
    cvtColor(g_srcImage, g_maskImage, COLOR_BGR2GRAY);
    cvtColor(g_maskImage, grayImage, COLOR_GRAY2BGR);
    g_maskImage = Scalar::all(0);
    //【2】设置鼠标回调函数
    setMouseCallback("原图", on_Mouse, 0);
    //【3】轮询按键,进行处理
    while (1)
    {
        //获取键值
        int c = waitKey(0);
        //若按键键值为ESC时,退出
        if ((char)c == 27)
            break;
        //按键键值为2时,恢复源图
        if ((char)c == '2')
        {
            g_maskImage = Scalar::all(0);
            srcImage.copyTo(g_srcImage);
            imshow("image", g_srcImage);
        }
        //若检测到按键值为1或者空格,则进行处理
        if ((char)c == '1' || (char)c == ' ')
        {
            //定义一些参数
            int i, j, compCount = 0;
            vector<vector<Point> > contours;
            vector<Vec4i> hierarchy;
            //寻找轮廓
            findContours(g_maskImage, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
            //轮廓为空时的处理
            if (contours.empty())
                continue;
            //拷贝掩膜
            Mat maskImage(g_maskImage.size(), CV_32S);
            maskImage = Scalar::all(0);
            //循环绘制出轮廓
            for (int index = 0; index >= 0; index = hierarchy[index][0], compCount++)
                drawContours(maskImage, contours, index, Scalar::all(compCount + 1), -1, 8, hierarchy, INT_MAX);
            //compCount为零时的处理
            if (compCount == 0)
                continue;
            //生成随机颜色
            vector<Vec3b> colorTab;
            for (i = 0; i < compCount; i++)
            {
                int b = theRNG().uniform(0, 255);
                int g = theRNG().uniform(0, 255);
                int r = theRNG().uniform(0, 255);

                colorTab.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));
            }
            //使用分水岭算法
            watershed(srcImage, maskImage);
            //双层循环,将分水岭图像遍历存入watershedImage中
            Mat watershedImage(maskImage.size(), CV_8UC3);
            for (i = 0; i < maskImage.rows; i++)
            for (j = 0; j < maskImage.cols; j++)
            {
                int index = maskImage.at<int>(i, j);
                if (index == -1)
                    watershedImage.at<Vec3b>(i, j) = Vec3b(255, 255, 255);
                else if (index <= 0 || index > compCount)
                    watershedImage.at<Vec3b>(i, j) = Vec3b(0, 0, 0);
                else
                    watershedImage.at<Vec3b>(i, j) = colorTab[index - 1];
            }
            //混合灰度图和分水岭效果图并显示最终的窗口
            watershedImage = watershedImage*0.5 + grayImage*0.5;
            imshow("分水岭效果图", watershedImage);
        }
    }
    return 0;
}
static void on_Mouse(int event, int x, int y, int flags, void*)
{
    //处理鼠标不在窗口中的情况
    if (x < 0 || x >= g_srcImage.cols || y < 0 || y >= g_srcImage.rows)
        return;
    //处理鼠标左键相关消息
    if (event == EVENT_LBUTTONUP || !(flags & EVENT_FLAG_LBUTTON))
        prevPt = Point(-1, -1);
    else if (event == EVENT_LBUTTONDOWN)
        prevPt = Point(x, y);

    //鼠标左键按下并移动,绘制出白色线条
    else if (event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON))
    {
        Point pt(x, y);
        if (prevPt.x < 0)
            prevPt = pt;
        line(g_maskImage, prevPt, pt, Scalar::all(255), 5, 8, 0);
        line(g_srcImage, prevPt, pt, Scalar::all(255), 5, 8, 0);
        prevPt = pt;
        imshow("原图", g_srcImage);
    }
}

猜你喜欢

转载自blog.csdn.net/xuxunjie147/article/details/78295428
今日推荐