opencv矩形轮廓查找

  • 之前公司软件版本是在通过调用摄像头再手动圈定仪器数字区域进行识别,现在在此基础上实现自动定位,检测出所有的矩形通过其宽高之比和面积进行筛选,部分关键代码如下


//自动定位数字区域
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <opencv2\imgproc\imgproc.hpp>
#include <stdio.h>
#include <iostream>

using namespace cv;
using namespace std;
  
cv::Mat frame,tmp;  

void Dectector(Mat frame)
{
    Mat gray_image;
    cvtColor(frame, gray_image, CV_RGB2GRAY);
    
    //滤波处理
    Mat blur_image;
    GaussianBlur(gray_image, blur_image, Size(3,3),0,0);
    //Canny边缘检测
    Mat canny_image;
    Canny(blur_image, canny_image, 100, 150, 3);
    imshow("Canny",canny_image);

    //查找轮廓
    Mat contour_image;
    contour_image = canny_image.clone();
    vector<vector<Point>>contours;
    findContours(contour_image, contours, CV_RETR_LIST, CHAIN_APPROX_SIMPLE);

    //绘制轮廓
    drawContours(contour_image, contours, -1, Scalar(255), 1);
    
    //矩形
    
    vector<Point> rectPoint;
    for (int i = 0;i < contours.size();i++)
    {
        //获得矩形外包围框
        Rect r = boundingRect(Mat(contours[i]));
        
        //RotatedRect r = minAreaRect(Mat(contours[i]));
        //cout << "contours" << i << "height=" << r.height << "width =" << r.width << "rate =" << ((float)r.width / r.height) << endl;
        
        //根据矩形宽高比和面积筛选矩形
        if ((float)r.width / r.height >= 1.5&& (float)r.width / r.height <= 2.2&& (float)r.width * r.height>=3000&& (float)r.width * r.height<=10000)
        {
            cout << "r.x = " << r.x << "  r.y  = " << r.y <<"rate =" << ((float)r.width / r.height) << " area = " << ((float)r.width * r.height) << endl;
            
            Point p1, p2, p3, p4;
            p1.x = r.x;
            p1.y = r.y;
            p2.x = r.x + r.width;
            p2.x = r.y;
            p3.x = r.x + r.width;
            p3.y = r.y + r.height;
            p4.x = r.x;
            p4.y = r.y + r.height;
            rectPoint.push_back(p1);
            rectPoint.push_back(p2);
            rectPoint.push_back(p3);
            rectPoint.push_back(p4);
            //画矩形
            rectangle(frame, r, Scalar(0, 0, 255), 2);
            
        }
    }
    imshow("检测",frame);
    imwrite("03.jpg",frame);
}
void main()  
{  
    VideoCapture cap(0);
    if(!cap.isOpened())
    {
        printf("error");
        return;
    }
    cap.set(CV_CAP_PROP_FRAME_WIDTH,640);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT,480);
    while(1)
    {
        cap>>frame;
        flip(frame,frame,-1);
        Dectector(frame);

        if(27==waitKey(30))//按ESC键退出
            break;
    }
    //cap.release();

}  

  • 如图所示,红色矩形框是数字所在区域

猜你喜欢

转载自blog.csdn.net/kangshuaibing/article/details/82898171
今日推荐