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

2020年02月14日 编程语言 ⁄ 共 1858字 ⁄ 字号 评论关闭

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.做灰度直方图，提取阈值，做二值化处理

// 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.识别矩形

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); } }