2022-01-28

算法思路:
1图片灰度化
2ostu阈值分割
3形态学处理,去除细小噪声
4使用canny轮廓提取,根据面积大小作为约束条件

main.cpp


#include"Cal.h"
using namespace std;
using namespace cv;

int main(int argc, char* argv[])

{
    std::string folder_path = "D:\\Aluosang\\test.jpg"; //更改文件夹测试,或改为实时读取图片 img
    std::vector file_names;
    cv::glob(folder_path, file_names);

    cv::Mat img;

    for (int i = 0; i < file_names.size(); i++) {
        std::cout << file_names[i] << std::endl; //黑窗口输出文件名字,如果实时更新,for循环删改。
        img = cv::imread(file_names[i]);
        if (!img.data) {
            continue;
        }

        if (img.empty())                         // 判断读入图片是否为空
        {
            cout << "image is empty" << endl;
            return -1;
        }

        /*cv::Mat src_crop = img(cv::Rect(200, 300, 700, 500)); // 裁剪后的图 src_crop*/
        Cal ed(img);
        ed.cannyProcess(200, 220);
        ed.getContours();

        cv::imshow("img", img);  //输出显示
        cv::waitKey(2000);      //调时间快慢
        waitKey(0);
        return 0;
    }


   
}

Cal.cpp

#include "Cal.h"


Cal::Cal(cv::Mat image)
{
    m_img = image;
}

bool Cal::cannyProcess(unsigned int downThreshold, unsigned int upThreshold)
{
    bool ret = true;

    if (m_img.empty())
    {
        ret = false;
    }

    cv::Canny(m_img, m_canny, downThreshold, upThreshold);
    cv::imshow("Canny", m_canny);
    return ret;
}

bool Cal::getContours()
 {
       bool ret = true;
       if (m_canny.empty())
       {
               ret = false;
       }
    
        cv::Mat k = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3), cv::Point(-1, -1));
        cv::dilate(m_canny, m_canny, k);
        imshow("dilate", m_canny);
   
          // 轮廓发现与绘制
        vector > contours;
        vector hierarchy;
        findContours(m_canny, contours, cv::RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
   
        for (size_t i = 0; i < contours.size(); ++i)
        {
            // 最大外接轮廓
            cv::Rect rect = cv::boundingRect(contours[i]);
            cv::rectangle(m_img, rect, cv::Scalar(0, 255, 0), 2, LINE_8);
       
          
                // 最小外接轮廓
            RotatedRect rrt = minAreaRect(contours[i]);
            Point2f pts[4];
            rrt.points(pts);
                // 绘制旋转矩形与中心位置
            for (int i = 0; i < 4; i++) {
            line(m_img, pts[i % 4], pts[(i + 1) % 4], Scalar(0, 0, 255), 2, 8, 0);
           
            }
            Point2f cpt = rrt.center;
            circle(m_img, cpt, 2, Scalar(255, 0, 0), 2, 8, 0);
        }
   
      
        imshow("contours", m_img);
        return ret;
     }

 Cal::~Cal()
 {
     }

Cal.h


#pragma once
#include
#include

using namespace std;
using namespace cv;


class Cal
{
    cv::Mat m_img;
    cv::Mat m_canny;
public:
    Cal(cv::Mat iamge);
    bool cannyProcess(unsigned int downThreshold, unsigned int upThreshold);
    bool getContours();

    ~Cal();
};

你可能感兴趣的:(2022-01-28)