opencv3.0识别并提取图形中的矩形

利用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(白色)

  1. // Quantize the gray scale to 30 levels  
  2. int gbins = 16;  
  3. int histSize[] = {gbins};  
  4.    // gray scale varies from 0 to 256  
  5. float granges[] = {0,256};  
  6. const float* ranges[] = { granges };  
  7. cv::MatND hist;  
  8. // we compute the histogram from the 0-th and 1-st channels  
  9. int channels[] = {0};  
  10.   
  11. //calculate hist  
  12. calcHist( &hsv, 1, channels, cv::Mat(), // do not use mask  
  13.             hist, 1, histSize, ranges,  
  14.             true// the histogram is uniform  
  15.             false );  
  16. //find the max value of hist  
  17. double maxVal=0;  
  18. minMaxLoc(hist, 0, &maxVal, 0, 0);  
  19.   
  20. int scale = 20;  
  21. cv::Mat histImg;  
  22. histImg.create(500,gbins*scale,CV_8UC3);  
  23.   
  24. //show gray scale of hist image  
  25. for(int g=0;g
  26.     float binVal = hist.at<float>(g,0);  
  27.     int intensity = cvRound(binVal*255);  
  28.     rectangle( histImg, cv::Point(g*scale,0),  
  29.                        cv::Point((g+1)*scale - 1,binVal/maxVal*400),  
  30.                         CV_RGB(0,0,0),  
  31.                        CV_FILLED );  
  32. }  
  33. cv::imshow("histImg",histImg);  
  34.   
  35. //threshold processing  
  36. cv::Mat hsvRe;  
  37. threshold( hsv, hsvRe, 64, 255,cv::THRESH_BINARY);  

3.提取图片轮廓 
为了识别图片中的矩形,在识别之前还需要提取图片的轮廓。在经过滤波、二值化处理后,轮廓提取后
的效果比未提取前的效果要好很多。


4.识别矩形 

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

 

  1. vector approx;  
  2.   
  3. for (size_t i = 0; i < contours.size(); i++)  
  4. {  
  5.     approxPolyDP(Mat(contours[i]), approx,   
  6.                  arcLength(Mat(contours[i]), true)*0.02, true);  
  7.   
  8.     if (approx.size() == 4 &&  
  9.         fabs(contourArea(Mat(approx))) > 1000 &&  
  10.         isContourConvex(Mat(approx)))  
  11.     {  
  12.         double maxCosine = 0;  
  13.   
  14.         forint j = 2; j < 5; j++ )  
  15.         {  
  16.             double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));  
  17.             maxCosine = MAX(maxCosine, cosine);  
  18.         }  
  19.   
  20.         if( maxCosine < 0.3 )  
  21.             squares.push_back(approx);  
  22.     }  
  23. }  

你可能感兴趣的:(opencv3.0识别并提取图形中的矩形)