OpenCV 提取图像中的轮廓

nullnullptr 2016-08-30 04:14:06
最近在用OpenCV做轮廓提取,用到findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);本来想提取一张图片里面 不同形状的区域 的外轮廓,结果把图像的外轮廓也提取出来了。这是什么原因呢?
如果提取出来了,那么怎么判断提取出来的轮廓是整个图像的外轮廓呢?如果是外轮廓则丢弃。
...全文
822 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
penghuahuijuan 2016-09-02
  • 打赏
  • 举报
回复
对图像的边界进行判断吧,在图像边缘直接去掉
赵4老师 2016-08-30
  • 打赏
  • 举报
回复
Mat img,gray,bw;
Mat smallImg(600,600,CV_8UC1);
vector<Vec4i> hierarchy;
vector<vector<Point> > contours;
int threshval=90;
Rect r;
Rect maxrect,brect;
int idx,n;
const static Scalar colors[15]={
    CV_RGB(  0,  0,128),
    CV_RGB(  0,128,  0),
    CV_RGB(  0,128,128),
    CV_RGB(128,  0,  0),
    CV_RGB(128,  0,128),
    CV_RGB(128,128,  0),
    CV_RGB(128,128,128),
    CV_RGB(160,160,160),
    CV_RGB(  0,  0,255),
    CV_RGB(  0,255,  0),
    CV_RGB(  0,255,255),
    CV_RGB(255,  0,  0),
    CV_RGB(255,  0,255),
    CV_RGB(255,255,  0),
    CV_RGB(255,255,255),
};
Scalar color;
赵4老师 2016-08-30
  • 打赏
  • 举报
回复
仅供参考:
        findContours(bw,contours,hierarchy,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
        if (!contours.empty()&&!hierarchy.empty()) {
            idx=0;
            n=0;
            vector<Point> approx;
            for (;idx>=0;idx=hierarchy[idx][0]) {
                color=colors[idx%15];
//              drawContours(smallImg,contours,idx,color,1,8,hierarchy);
                approxPolyDP(Mat(contours[idx]), approx, arcLength(Mat(contours[idx]), true)*0.005, true);//0.005为将毛边拉直的系数
                const Point* p = &approx[0];
                int m=(int)approx.size();
                polylines(smallImg, &p, &m, 1, true, color);
                circle(smallImg,Point(p[0].x,p[0].y),2,color);
                circle(smallImg,Point(p[1].x,p[1].y),1,color);

                n++;
                if (1==n) {
                    maxrect=boundingRect(Mat(contours[idx]));
                } else {
                    brect=boundingRect(Mat(contours[idx]));
                    CvRect mr(maxrect),br(brect);
                    maxrect=cvMaxRect(&mr,&br);
                }
            }
            circle(smallImg,Point(maxrect.x+maxrect.width/2,maxrect.y+maxrect.height/2),2,CV_RGB(255,0,0));
        }
        imshow("display",smallImg);
        waitKey(0);

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧