opencv 도형 윤곽 검 측 실현

17860 단어 opencv윤곽검출
윤곽 검 사 를 실현 하려 면 먼저 검 측 된 이미지 에 대해 이미지 처 리 를 해 야 합 니 다.
이미지 그 레이스 케 일,고 스 필터,Canny 테두리 검 측,테두리 검 측 확대 처리,윤곽 추출.
1.간단 한 전체 도형 검 측 실현
즉,draw Contours 의 세 번 째 매개 변 수 를-1 로 설정 하면 이미지 의 전체 도형 검 사 를 실현 할 수 있 습 니 다.
프로그램:

#include <iostream>
#include <opencv2/highgui.hpp> //    gui     gui    
#include <opencv2/imgcodecs.hpp> //      
#include <opencv2/imgproc.hpp> //        
using namespace std;
using namespace cv;
/*           
 *      ,       ,   Canny    
 *           
 */
Mat imgGray, imgBlur, imgCanny,imgDil;
void getContours(Mat imgDil,Mat& img);
 
int main()
{
    
 
    string path = "resources/shapes.png"; //        ,             !!!
    Mat img = imread(path); //  opencv            Mat 
 
 
    // pre-processing image       
    cvtColor(img, imgGray, COLOR_BGR2GRAY);
    GaussianBlur(imgGray, imgBlur,Size(3,3),3,0); //      
    Canny(imgBlur, imgCanny, 25, 75);// Canny     
    Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //    Size               
    dilate(imgCanny, imgDil, kernel);
 
    getContours(imgDil,img); //               ,              
 
    imshow("Image", img);
    waitKey(0); //   ,0       
}
void getContours(Mat imgDil, Mat& img)
{
    /* contour is a vector inside that vector there is more vector
     * {{Point(20,30),Point(50,60)},{},{}} each vector like a contour and each contour have some points
     *
     **/
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy; // Vec4i         4  int   typedef    Vec<int, 4>   Vec4i;                  
    findContours(imgDil, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // CV_CHAIN_APPROX_SIMPLE -         
    drawContours(img, contours, -1, Scalar(255,0,255),2); // contouridx = -1               
  }
실행 결과:

세심 한 독자 들 은 이 프로그램 이 작은 하 자 를 검출 했다 는 것 을 알 게 될 것 이다.
2.윤곽 하 자 제거
하 자 를 제거 하 는 방법 은 매우 간단 하 다.즉,모든 도형 의 면적 을 먼저 검 측 한 다음 에 도형 중의 최소 면적,즉 하 자 면적(우리 가 이미 알 고 있 는 이 하 자 면적<1000)을 발견 한 후에 if 를 사용 하여 면적 을 여과 하 는 것 이다.
프로그램:

#include <iostream>
#include <opencv2/highgui.hpp> //    gui     gui    
#include <opencv2/imgcodecs.hpp> //      
#include <opencv2/imgproc.hpp> //        
using namespace std;
using namespace cv;
/*           
 *      ,       ,   Canny    
 *           
 */
Mat imgGray, imgBlur, imgCanny,imgDil;
void getContours(Mat imgDil,Mat& img);
 
int main()
{
    
 
    string path = "resources/shapes.png"; //        ,             !!!
    Mat img = imread(path); //  opencv            Mat 
 
 
    // pre-processing image       
    cvtColor(img, imgGray, COLOR_BGR2GRAY);
    GaussianBlur(imgGray, imgBlur,Size(3,3),3,0); //      
    Canny(imgBlur, imgCanny, 25, 75);// Canny     
    Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //    Size               
    dilate(imgCanny, imgDil, kernel);
 
    getContours(imgDil,img); //               ,              
 
    imshow("Image", img);
    waitKey(0); //   ,0       
}
void getContours(Mat imgDil, Mat& img)
{
    /* contour is a vector inside that vector there is more vector
     * {{Point(20,30),Point(50,60)},{},{}} each vector like a contour and each contour have some points
     *
     **/
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy; // Vec4i         4  int   typedef    Vec<int, 4>   Vec4i;                  
    findContours(imgDil, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // CV_CHAIN_APPROX_SIMPLE -         
    drawContours(img, contours, -1, Scalar(255,0,255),2); // contouridx = -1               
 
    for(int i = 0;i <contours.size();i++)
    {
         int area = contourArea(contours[i]) ; //         
         if(area > 1000)
         {
             drawContours(img,contours,i,Scalar(255, 0, 255), 2);
         }
    }
  }
실행 결과:

우리 가 하 자 를 걸 러 내 는 데 성공 했다 는 것 을 알 수 있다.
3.윤곽 형상 판단
윤곽 을 판단 하기 전에 우 리 는 먼저 도형 의 코너 점 을 계산 해 야 한다.예 를 들 어 삼각형 은 세 개의 코너 점 이 있 고 사각형 은 네 개의 코너 점 이 있 으 며 원형 은 여러 개의 코너 점 이 있 기 때문에 코너 점 을 어떻게 얻 는 지 는 우리 가 윤곽 모양 을 검사 하 는 전제 이다.코너 의 핵심 함 수 를 approxPolyDP(contours[i],conpoly[i],0.02*peri,true)로 검사 합 니 다.즉 다각형 의합 함수.
프로그램:

#include <iostream>
#include <opencv2/highgui.hpp> //    gui     gui    
#include <opencv2/imgcodecs.hpp> //      
#include <opencv2/imgproc.hpp> //        
using namespace std;
using namespace cv;
/*           
 *      ,       ,   Canny    
 *           
 */
Mat imgGray, imgBlur, imgCanny,imgDil;
void getContours(Mat imgDil,Mat& img);
 
int main()
{
    
 
    string path = "resources/shapes.png"; //        ,             !!!
    Mat img = imread(path); //  opencv            Mat 
 
 
    // pre-processing image       
    cvtColor(img, imgGray, COLOR_BGR2GRAY);
    GaussianBlur(imgGray, imgBlur,Size(3,3),3,0); //      
    Canny(imgBlur, imgCanny, 25, 75);// Canny     
    Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //    Size               
    dilate(imgCanny, imgDil, kernel);
 
    getContours(imgDil,img); //               ,              
 
    imshow("Image", img);
    //imshow("Image Gray", imgGray);
    //imshow("Image Blur", imgBlur);
    //imshow("Image Canny", imgCanny);
    //imshow("Image Dilate", imgDil); //                    Canny     ,           dilation   
    waitKey(0); //   ,0       
}
//          ,              
void getContours(Mat imgDil, Mat& img)
{
    /* contour is a vector inside that vector there is more vector
     * {{Point(20,30),Point(50,60)},{},{}} each vector like a contour and each contour have some points
     *
     **/
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy; // Vec4i         4  int   typedef    Vec<int, 4>   Vec4i;                  
    findContours(imgDil, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // CV_CHAIN_APPROX_SIMPLE -         
    //drawContours(img, contours, -1, Scalar(255,0,255),2); // contouridx = -1               
    
    vector<vector<Point>> conpoly(contours.size());// conpoly(paprameter1) ,paprameter1   vector     ,      vector     point              
    vector<Rect> boundRect(contours.size());// Rect   x y               
    string objType; //       
    //         ,    area    
    for (int i = 0; i < contours.size(); i++) //   contours.size()            ,   vector::size()     vector       contours    (   )     
    {
        int area = contourArea(contours[i]); 
        
        if (area > 1000)
        {
            float peri = arcLength(contours[i], true);//           ,   bool             true        
            //    
            // conpoly                  1-9               
            approxPolyDP(contours[i],conpoly[i],0.02* peri,true); //  conpoly[i]   array   0.02*peri              !!!                
            cout << conpoly[i].size() << endl; //            
            boundRect[i] = boundingRect(conpoly[i]); //   conpoly[i]   boundingRect  
            drawContours(img, conpoly, i, Scalar(255, 0, 255), 2);
            //rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5);
        }
 
            
    }
}
실행 결과:

모든 도형 이 코너 포 인 트 를 가 져 야 한 다 는 것 을 감지 한 후에 if 로 도형 을 판단 하 는 포 인 트 를 추가 한 다음 에 puttext 함 수 를 통 해 도형 의 모양 을 표시 합 니 다.
프로그램:

#include <iostream>
#include <opencv2/highgui.hpp> //    gui     gui    
#include <opencv2/imgcodecs.hpp> //      
#include <opencv2/imgproc.hpp> //        
using namespace std;
using namespace cv;
/*           
 *      ,       ,   Canny    
 *           
 */
Mat imgGray, imgBlur, imgCanny,imgDil;
void getContours(Mat imgDil,Mat& img);
 
int main()
{
    
 
    string path = "resources/shapes.png"; //        ,             !!!
    Mat img = imread(path); //  opencv            Mat 
 
 
    // pre-processing image       
    cvtColor(img, imgGray, COLOR_BGR2GRAY);
    GaussianBlur(imgGray, imgBlur,Size(3,3),3,0); //      
    Canny(imgBlur, imgCanny, 25, 75);// Canny     
    Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //    Size               
    dilate(imgCanny, imgDil, kernel);
 
    getContours(imgDil,img); //               ,              
 
    imshow("Image", img);
    //imshow("Image Gray", imgGray);
    //imshow("Image Blur", imgBlur);
    //imshow("Image Canny", imgCanny);
    //imshow("Image Dilate", imgDil); //                    Canny     ,           dilation   
    waitKey(0); //   ,0       
}
//          ,              
void getContours(Mat imgDil, Mat& img)
{
    /* contour is a vector inside that vector there is more vector
     * {{Point(20,30),Point(50,60)},{},{}} each vector like a contour and each contour have some points
     *
     **/
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy; // Vec4i         4  int   typedef    Vec<int, 4>   Vec4i;                  
    findContours(imgDil, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // CV_CHAIN_APPROX_SIMPLE -         
    //drawContours(img, contours, -1, Scalar(255,0,255),2); // contouridx = -1               
    
    vector<vector<Point>> conpoly(contours.size());// conpoly(paprameter1) ,paprameter1   vector     ,      vector     point              
    vector<Rect> boundRect(contours.size());// Rect   x y               
    string objType; //       
    //         ,    area    
    for (int i = 0; i < contours.size(); i++) //   contours.size()            ,   vector::size()     vector       contours    (   )     
    {
        int area = contourArea(contours[i]); 
        
        if (area > 1000)
        {
            float peri = arcLength(contours[i], true);//           ,   bool             true        
            //    
            // conpoly                  1-9               
            approxPolyDP(contours[i],conpoly[i],0.02* peri,true); //  conpoly[i]   array   0.02*peri              !!!                
            //drawContours(img, contours , i, Scalar(255, 0, 255), 2);
             //   conpoly                     
            cout << conpoly[i].size() << endl; //            
            boundRect[i] = boundingRect(conpoly[i]); //   conpoly[i]   boundingRect         
            //rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5); //   
            
            int objCor = (int)conpoly[i].size(); //        
            if (3 == objCor) objType = "Triangle";
            else 
                if (4 == objCor) 
                {   //   float  ,        float     
                    float aspRatio = (float)boundRect[i].width/(float)boundRect[i].height;
                    if(aspRatio<1.05 && aspRatio>0.95)
                         objType = "Square";
                    else objType = "Rectangle";
                }
            else if (objCor > 4) objType = "Circle";
 
            putText(img, objType, Point(boundRect[i].x, boundRect[i].y-5), FONT_HERSHEY_PLAIN, 1, Scalar(0, 69, 255), 1);
            drawContours(img, conpoly, i, Scalar(255, 0, 255), 2);
            //rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5);
        }
 
            
    }
}
실행 결과:

4.검 측 된 도형 에 검 측 상 자 를 씌 웁 니 다.
핵심 함수,rectangle()을 사용 하여 직사각형 그림 을 그립 니 다.
프로그램:

#include <iostream>
#include <opencv2/highgui.hpp> //    gui     gui    
#include <opencv2/imgcodecs.hpp> //      
#include <opencv2/imgproc.hpp> //        
using namespace std;
using namespace cv;
/*           
 *      ,       ,   Canny    
 *           
 */
Mat imgGray, imgBlur, imgCanny,imgDil;
void getContours(Mat imgDil,Mat& img);
 
int main()
{
    
 
    string path = "resources/shapes.png"; //        ,             !!!
    Mat img = imread(path); //  opencv            Mat 
 
 
    // pre-processing image       
    cvtColor(img, imgGray, COLOR_BGR2GRAY);
    GaussianBlur(imgGray, imgBlur,Size(3,3),3,0); //      
    Canny(imgBlur, imgCanny, 25, 75);// Canny     
    Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); //    Size               
    dilate(imgCanny, imgDil, kernel);
 
    getContours(imgDil,img); //               ,              
 
    imshow("Image", img);
    //imshow("Image Gray", imgGray);
    //imshow("Image Blur", imgBlur);
    //imshow("Image Canny", imgCanny);
    //imshow("Image Dilate", imgDil); //                    Canny     ,           dilation   
    waitKey(0); //   ,0       
}
//          ,              
void getContours(Mat imgDil, Mat& img)
{
    /* contour is a vector inside that vector there is more vector
     * {{Point(20,30),Point(50,60)},{},{}} each vector like a contour and each contour have some points
     *
     **/
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy; // Vec4i         4  int   typedef    Vec<int, 4>   Vec4i;                  
    findContours(imgDil, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // CV_CHAIN_APPROX_SIMPLE -         
    //drawContours(img, contours, -1, Scalar(255,0,255),2); // contouridx = -1               
    
    vector<vector<Point>> conpoly(contours.size());// conpoly(paprameter1) ,paprameter1   vector     ,      vector     point              
    vector<Rect> boundRect(contours.size());//           
    string objType; //       
    //         ,    area    
    for (int i = 0; i < contours.size(); i++) //   contours.size()            ,   vector::size()     vector       contours    (   )     
    {
        int area = contourArea(contours[i]); 
        
        if (area > 1000)
        {
            float peri = arcLength(contours[i], true);//           ,   bool             true        
            //    
            // conpoly                  1-9               
            approxPolyDP(contours[i],conpoly[i],0.02* peri,true); //  conpoly[i]   array   0.02*peri              !!!                
            //drawContours(img, contours , i, Scalar(255, 0, 255), 2);
             //   conpoly                     
            cout << conpoly[i].size() << endl; //            
            boundRect[i] = boundingRect(conpoly[i]); //   conpoly[i]   boundingRect         
            //rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5); //   
            
            int objCor = (int)conpoly[i].size(); //        
            if (3 == objCor) objType = "Triangle";
            else 
                if (4 == objCor) 
                {   //   float  ,        float     
                    float aspRatio = (float)boundRect[i].width/(float)boundRect[i].height;
                    if(aspRatio<1.05 && aspRatio>0.95)
                         objType = "Square";
                    else objType = "Rectangle";
                }
            else if (objCor > 4) objType = "Circle";
 
            putText(img, objType, Point(boundRect[i].x, boundRect[i].y-5), FONT_HERSHEY_PLAIN, 1, Scalar(0, 69, 255), 1);
            drawContours(img, conpoly, i, Scalar(255, 0, 255), 2);
            rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5);
        }
 
            
    }
}
실행 결과:

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기