利用opencv来识别图片中的矩形。 
其中遇到的问题主要是识别轮廓时矩形内部的形状导致轮廓不闭合。 


1. 对输入灰度图片进行高斯滤波 
2. 做灰度直方图,提取阈值,做二值化处理 
3. 提取图片轮廓 
4. 识别图片中的矩形 
5. 提取图片中的矩形

1.对输入灰度图片进行高斯滤波

    cv::Mat src = cv::imread("F:\\t13.bmp",CV_BGR2GRAY);
    cv::Mat hsv;
    GaussianBlur(src,hsv,cv::Size(5,5),0,0);
2.做灰度直方图,提取阈值,做二值化处理 
由于给定图片,背景是黑色,矩形背景色为灰色,矩形中有些其他形状为白色,可以参考为: 
提取轮廓时,矩形外部轮廓并未闭合。因此,我们需要对整幅图做灰度直方图,找到阈值,进行二值化

处理。即令像素值(黑色)小于阈值的,设置为0(纯黑色);令像素值(灰色和白色)大于阈值的,设


置为255(白色)



* // Quantize the gray scale to 30 levels  
* int gbins = 16;  
* int histSize[] = {gbins};  
*    // gray scale varies from 0 to 256  
* float granges[] = {0,256};  
* const float* ranges[] = { granges };  
* cv::MatND hist;  
* // we compute the histogram from the 0-th and 1-st channels  
* int channels[] = {0};  
*   
* //calculate hist  
* calcHist( &hsv, 1, channels, cv::Mat(), // do not use mask  
*             hist, 1, histSize, ranges,  
*             true, // the histogram is uniform  
*             false );  
* //find the max value of hist  
* double maxVal=0;  
* minMaxLoc(hist, 0, &maxVal, 0, 0);  
*   
* int scale = 20;  
* cv::Mat histImg;  
* histImg.create(500,gbins*scale,CV_8UC3);  
*   
* //show gray scale of hist image  
* for(int g=0;g<gbins;g++){  
*     float binVal = hist.at<float>(g,0);  
*     int intensity = cvRound(binVal*255);  
*     rectangle( histImg, cv::Point(g*scale,0),  
*                        cv::Point((g+1)*scale - 1,binVal/maxVal*400),  
*                         CV_RGB(0,0,0),  
*                        CV_FILLED );  
* }  
* cv::imshow("histImg",histImg);  
*   
* //threshold processing  
* cv::Mat hsvRe;  
* threshold( hsv, hsvRe, 64, 255,cv::THRESH_BINARY);  
3.提取图片轮廓 
为了识别图片中的矩形,在识别之前还需要提取图片的轮廓。在经过滤波、二值化处理后,轮廓提取后
的效果比未提取前的效果要好很多。


4.识别矩形 


识别矩形的条件为:图片中识别的轮廓是一个凸边形、有四个顶角、所有顶角的角度都为90度。

 

* vector<Point> approx;  
*   
* for (size_t i = 0; i < contours.size(); i++)  
* {  
*     approxPolyDP(Mat(contours[i]), approx,   
*                  arcLength(Mat(contours[i]), true)*0.02, true);  
*   
*     if (approx.size() == 4 &&  
*         fabs(contourArea(Mat(approx))) > 1000 &&  
*         isContourConvex(Mat(approx)))  
*     {  
*         double maxCosine = 0;  
*   
*         for( int j = 2; j < 5; j++ )  
*         {  
*             double
 cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));  
*             maxCosine = MAX(maxCosine, cosine);  
*         }  
*   
*         if( maxCosine < 0.3 )  
*             squares.push_back(approx);  
*     }  
* }  

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信