使用特定形状的轮廓包围
在实际应用中,经常会有将检测到的轮廓用多边形表示出来的应用,提取包围轮廓的多边形也方便我们做进一步分析,轮廓包围主要有几种
1.轮廓外接矩形
2.轮廓最小外接矩形(旋转)
3.轮廓最小包围圆形
4轮廓拟合椭圆
5.轮廓毕竟多边形曲线
轮廓外接矩形–boudingRect()
Rect boundingRect(InputArray points);
points:输入的二维点集,可以填Mat类型或std::vector
返回值:Rect类矩形对象
ex1:
vector<Rect>boundRect(contours.size());//定义外接矩形集合
int x0=0,y0=0,w0=0,h0=0;
for(int i=0;i<contours.size();i++)
{
drawContours(dstImg,ccontours,i,Scalar(0,0,255),2,8);
boundRect[i]=boundingRect(Mat(contours[i]));
x0=boundRect[i].x;
y0=boundRect[i].y;
w0=boundRect[i].width;
h0=boundRect[i].height;
rectangle(dstImg,Point(x0,y0),Point(x0+w0,yo+h0),Scalar(0,255,0),2,8);
}
void main()
{ //外接矩形的查找绘制
Mat srcImg=imread("12.jpg");
Mat dstImg=srcIMg.clone();原图备份
cvtColor(srcImg,srcIMg,CV_BGR2GRAY);//转为灰度图
threshold(srcImg,srcIMg,100,255,CV_THRESH_BINARY);//二值化
vector<vector<Point>>contours;
vector<Vec4i>hierarcy;
findContours(srcImg,contours,hierarcy,CV_EXTERNAL,CV_APPROX_NONE);//查找轮廓
vector<Rect>boundRect(contours.size());//定义外接矩形集合
//drawContours(dstImg,contours,-1,Scalar(0,0,255),2,8);//绘制轮廓
int x0=0;y0=0,w0=0,h0=0;
for(int i=0;i<contours.size();i++)
{
boundingRect[i]=boundingRect((Mat)contours[i]);//查找每个轮廓的外接矩形
drawContours(dstImg,contours,i,Scalar(0,0,255),2,8);//绘制轮廓
x0=boundRect[i].x;//外接矩形左上角的x坐标
y0=boundRect[i].y;//外接矩形左上角的y坐标
w0=boundRect[i].width;//获取第i个外接矩形的高度
h0=bounfRect[i].height;//获取第i个外接矩形的高度
rectangle(dstImg,Point(x0,y0),Point(x0+w0,y0+h0),Scalar(0,255,0),2,8);//绘制第i个外接矩形
}
imshow("boundRect",dstImg);
waitKey(0);
}
//分割硬币,,筛选的方法
长宽小于某个值就不显示
判断
if(w0>30&&h0>30)比如
有连通域才会标记外接矩形
可以做一个膨胀运算
或者利用ROI
车牌检测 简单字符车牌的分割
//首先在有车牌的图上先定位车牌
//字符的提取和分割
车牌不能找外轮廓
把字符设定在一个范围内
小于1/7 大于1/3 先设定一个阈值
if(w0>srcImg.cols/12&&w0<srcImg.cols/7&&h0>srcImg.rows/6&&w0<srcImg.rows*5/6)
大小范围不一样
根据车牌比例对应的大小 如上加范围
不是连通域不好分 字符
先滤波
char pic_name[10];
sprintf(pic_name,"%d.bmp",i);
Mat ROI=dstImg(Rect(x0,y0,w0,h0));
imwrite();