Qt + halcon 基于形状的模板匹配

项目环境:win10      halcon18    Qt5.14

项目目的:1.halcon代码实现基于形状的模板匹配  2.Qt制作用户界面

项目运行效果:

Qt + halcon 基于形状的模板匹配_第1张图片

 Qt + halcon 基于形状的模板匹配_第2张图片

 Qt + halcon 基于形状的模板匹配_第3张图片

 Qt + halcon 基于形状的模板匹配_第4张图片

 项目主要使用的halcon算子

*相较其他,算子可以匹配多个目标,并且可以设置旋转角度,大小范围
create_scaled_shape_model (ImageReduced, 'auto', -0.39, 0.79, 'auto', 0.9, 1.1, 'auto', 'auto', 'use_polarity', 'auto', 'auto', ShapeModelID)

find_scaled_shape_models (SearchImage, ShapeModelID, rad(-180), rad(180), 0.9, 1.1, 0.09, 6, 0.5, 'least_squares', 0, 0.9, Row, Column, Angle, Scale, Score1, Model)

 项目.pro文件

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    widget.cpp

HEADERS += \
    widget.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

win32:{
   #halcon配置代码,已经将include、lib拷贝到项目之下
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhalcon
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhalconc
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhalconcpp
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhalconcppxl
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhalconcxl
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhalconxl
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhdevenginecpp
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -lhdevenginecppxl
   LIBS += -L$$PWD/halcon/win/lib/x64-win64/ -llibiomp5md

   #INCLUDEPATH += $$PWD/halcon/win/include
   #DEPENDPATH += $$PWD/halcon/win/include

   INCLUDEPATH += $$PWD/halcon/linux/include
   DEPENDPATH += $$PWD/halcon/linux/include
}


unix:{
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux -lhalcon
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux -lhalconc
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux -lhalconcpp
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux -lhalconcppxl
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux/ -lhalconcxl
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux -lhalconxl
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux -lhdevenginecpp
   LIBS += -L$$PWD/halcon/linux/lib/x64-linux -lhdevenginecppxl

   INCLUDEPATH += $$PWD/halcon/linux/include
   DEPENDPATH += $$PWD/halcon/linux/include
}

 Widget.h

#ifndef WIDGET_H
#define WIDGET_H


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include "halconcpp/HalconCpp.h"
#include "Halcon.h"

using namespace HalconCpp;

#pragma execution_character_set("utf-8") //支持中文

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
private:
    void createInterface();

    QLabel *label_ImageShow;
    QPushButton *btn_OpenImage;
    QPushButton *btn_OpenCamera;
    QPushButton *btn_CloseCamera;

    QTimer *timer;

    HTuple  hv_WindowHandle;
    HObject  ho_Image;
    HTuple  hv_Width, hv_Height;
    Hlong  MainWndID;
    HTuple hv_AcqHandle;

    QWidget *createTab0();
    QWidget *createTab1();
    QWidget *createTab2();
    QWidget *createTab3();

    //tab0
    QLabel *label_ImageROI;
    HTuple  hv_WindowHandleROI;
    //HObject  ho_ImageROI;
    //HTuple  hv_WidthROI, hv_HeightROI;
    Hlong  MainWndIDROI;

    QPushButton *btn_ROI;
    QPushButton *btn_Create;
    QPushButton *btn_Match;

    bool ROI;
    QPoint SPoint;
    QPoint EPoint;
    QPoint sPoint;
    QPoint ePoint;
    HObject ROIContour;
    HTuple  hv_rowsROI, hv_colsROI;
    HObject ho_ImageReducedROI;
    HObject ho_RectangleROI;

    bool IsMatching;
    //void Matching();
    HObject  ho_GrayImage;
    //Rgb1ToGray(ho_ImageROI, &ho_GrayImageROI);


    //QPushButton *btn_test;



    //tab1
    QSpinBox *input_Create_NumLevels;
    QSpinBox *input_Create_AngleStart;
    QSpinBox *input_Create_AngleExtent;
    QSpinBox *input_Create_AngleStep;
    QDoubleSpinBox *input_Create_ScaleMin;
    QDoubleSpinBox *input_Create_ScaleMax;
    QDoubleSpinBox *input_Create_ScaleStep;
    QComboBox *input_Create_Optimization;
    QComboBox *input_Create_Metric;
    QComboBox *input_Create_Contrast;
    QComboBox *input_Create_MinContrast;
    //QComboBox *input_Create_MinContrast;


    void Create_Scaled_Shape_Model();
    HTuple  hv_ModelID;


    //tab2
    QSpinBox *input_Find_AngleStart;
    QSpinBox *input_Find_AngleExtent;
    QDoubleSpinBox *input_Find_ScaleMin;
    QDoubleSpinBox *input_Find_ScaleMax;
    QDoubleSpinBox *input_Find_MinScore;
    QSpinBox *input_Find_NumMatches;
    QDoubleSpinBox *input_Find_MaxOverlap;
    QComboBox *input_Find_SubPixel;
    QSpinBox *input_Find_NumLevels;
    QDoubleSpinBox *input_Find_Greediness;

    void Find_Scaled_Shape_Models();
    HTuple  hv_RowCheck, hv_ColumnCheck ,hv_ScaleCheck ,hv_ScoreCheck;
    HTuple  hv_AngleCheck, hv_Model;

    //tab3
    QTableWidget *tableWidget;
    void get_Matching_Results();

private slots:
    void on_btn_OpenImage_clicked();
    void on_btn_OpenCamera_clicked();
    void on_btn_CloseCamera_clicked();
    void camera();
    void on_btn_ROI_clicked();
    void on_btn_Create_clicked();
    void on_btn_Match_clicked();

    //void on_btn_test_clicked();
protected:

    void mousePressEvent(QMouseEvent * e);
    void mouseMoveEvent(QMouseEvent * e);
    void mouseReleaseEvent(QMouseEvent * e);
};
#endif // WIDGET_H

Widget.cpp

#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    createInterface();
    timer = new QTimer(this);

    ROI = false;
    IsMatching = false;

    connect(btn_OpenImage,SIGNAL(clicked()),this,SLOT(on_btn_OpenImage_clicked()));
    connect(btn_OpenCamera,SIGNAL(clicked()),this,SLOT(on_btn_OpenCamera_clicked()));
    connect(btn_CloseCamera,SIGNAL(clicked()),this,SLOT(on_btn_CloseCamera_clicked()));
    connect(timer,SIGNAL(timeout()),this,SLOT(camera()));

    connect(btn_ROI,SIGNAL(clicked()),this,SLOT(on_btn_ROI_clicked()));
    connect(btn_Create,SIGNAL(clicked()),this,SLOT(on_btn_Create_clicked()));
    connect(btn_Match,SIGNAL(clicked()),this,SLOT(on_btn_Match_clicked()));



}

Widget::~Widget()
{
}

void Widget::createInterface(){
    this->setFixedSize(916,547);

    label_ImageShow =new QLabel(this);
    label_ImageShow->setGeometry(290,20,611,461);
    MainWndID = (Hlong)this->label_ImageShow->winId();
    SetWindowAttr("background_color","gray");//设置背景为灰色
    OpenWindow(0, 0, label_ImageShow->width(), label_ImageShow->height(), MainWndID,
               "visible", "", &hv_WindowHandle);
    HDevWindowStack::Push(hv_WindowHandle);


    btn_OpenImage = new QPushButton(this);
    btn_OpenImage->setGeometry(350,495,100,40);
    btn_OpenImage->setText("打开图片");

    btn_OpenCamera = new QPushButton(this);
    btn_OpenCamera->setGeometry(630,495,100,40);
    btn_OpenCamera->setText("打开相机");

    btn_CloseCamera = new QPushButton(this);
    btn_CloseCamera->setGeometry(780,495,100,40);
    btn_CloseCamera->setText("关闭相机");

    btn_OpenCamera->setEnabled(true);
    btn_CloseCamera->setEnabled(false);

    QTabWidget *tabwidget = new QTabWidget(this);
    QWidget *tab0 = createTab0();
    QWidget *tab1 = createTab1();
    QWidget *tab2 = createTab2();
    QWidget *tab3 = createTab3();
    tabwidget->addTab(tab0, "基础参数");
    tabwidget->addTab(tab1, "模板参数");
    tabwidget->addTab(tab2, "匹配参数");
    tabwidget->addTab(tab3, "匹配结果");
    tabwidget->setGeometry(20, 20, 250, 461);
    tabwidget->setTabShape(QTabWidget::Triangular);


}

void Widget::on_btn_OpenImage_clicked(){
    qDebug() << "读取图片";
    ClearWindow(hv_WindowHandle);
    QString file_name = QFileDialog::getOpenFileName(this,tr("open  file"),"."
                                                 ,tr("Video Files(*.bmp *.jpg *.pbm *.pgm *.png *.ppm *.xbm *.xpm *.jpeg)"));
    try
    {
        ReadImage(&ho_Image,file_name.toLocal8Bit().toStdString().c_str());
        //ReadImage(&ho_Image,file_name.toLatin1().data());
        GetImageSize(ho_Image, &hv_Width, &hv_Height);
        SetPart(hv_WindowHandle, 0, 0, hv_Height, hv_Width);
        if (HDevWindowStack::IsOpen())
        {
            ClearWindow(HDevWindowStack::GetActive());
            DispObj(ho_Image, HDevWindowStack::GetActive());
        }
    }
    catch (HException &HDevExpDefaultException)
    {
        HTuple  hv_Exception;
        HDevExpDefaultException.ToHTuple(&hv_Exception);
    }
}

void Widget::on_btn_OpenCamera_clicked(){
    qDebug() << "打开相机";
    ClearWindow(hv_WindowHandle);
    timer->start(20);//定时器开始工作,参数影响帧率
    try
    {
        OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb", -1, "false",
                         "default", "[0]", 0, -1, &hv_AcqHandle);//只会打开序号0的相机,修改"[0]",改变连接上的相机
        GrabImageStart(hv_AcqHandle, -1);
        //在openwindow前先抓取一帧图片
        GrabImage(&ho_Image, hv_AcqHandle);
        GetImageSize(ho_Image, &hv_Width, &hv_Height);
        btn_CloseCamera->setEnabled(true);
        btn_OpenCamera->setEnabled(false);
        btn_OpenImage->setEnabled(false);
    }
    catch (HException &HDevExpDefaultException)
    {
        HTuple  hv_Exception;
        HDevExpDefaultException.ToHTuple(&hv_Exception);
    }
}

void Widget::on_btn_CloseCamera_clicked(){
    qDebug() << "关闭相机";
    timer->stop();
    CloseFramegrabber(hv_AcqHandle);
    ClearWindow(hv_WindowHandle);
    btn_CloseCamera->setEnabled(false);
    btn_OpenCamera->setEnabled(true);
    btn_OpenImage->setEnabled(true);
}

void Widget::camera()
{
    try {
        GrabImage(&ho_Image, hv_AcqHandle);
        GetImageSize(ho_Image, &hv_Width, &hv_Height);
        SetPart(hv_WindowHandle, 0, 0, hv_Height, hv_Width);
        if(HDevWindowStack::IsOpen())
        {
            DispObj(ho_Image,HDevWindowStack::GetActive());
        }
        if(ROI){
            //ClearWindow(hv_WindowHandle);
            SetColor(HDevWindowStack::GetActive(),"green");
            SetLineWidth(HDevWindowStack::GetActive(),4);
            DispObj(ROIContour,HDevWindowStack::GetActive());
            //GenRectangle1(&ho_RectangleROI, sPoint.y(), sPoint.x(), ePoint.y(), ePoint.x());
            //对ROI区域进行裁剪
            ReduceDomain(ho_Image, ho_RectangleROI, &ho_ImageReducedROI);
            //qDebug()<<"成功截取感兴趣区域";
            //
        }
        if(IsMatching){
            //Matching();
            Find_Scaled_Shape_Models();
        }

    }
    catch (HException &HDevExpDefaultException)
    {
        HTuple  hv_Exception;
        HDevExpDefaultException.ToHTuple(&hv_Exception);
    }
}

QWidget *Widget::createTab0()
{
    //标签页0
    QWidget * qWidget = new QWidget;
    label_ImageROI =new QLabel(qWidget);
    label_ImageROI->setGeometry(22,20,200,200);
    MainWndIDROI = (Hlong)label_ImageROI->winId();
    SetWindowAttr("background_color","gray");//设置背景为灰色
    OpenWindow(0, 0, label_ImageROI->width(), label_ImageROI->height(), MainWndIDROI,
               "visible", "", &hv_WindowHandleROI);
    //HDevWindowStack::Push(hv_WindowHandleROI);

    btn_ROI = new QPushButton(qWidget);
    btn_ROI->setGeometry(50,230,140,50);
    btn_ROI->setText("感兴趣区域设置");
    btn_Create = new QPushButton(qWidget);
    btn_Create->setGeometry(50,300,140,50);
    btn_Create->setText("模板创建");
    btn_Match = new QPushButton(qWidget);
    btn_Match->setGeometry(50,370,140,50);
    btn_Match->setText("模板匹配");

    return qWidget;
}

QWidget *Widget::createTab1()
{
    //标签页1 模板参数设置

    //https://www.mvtec.com/doc/halcon/1811/en/create_scaled_shape_model.html
    QWidget *qWidget = new QWidget;
    QLabel *label0 = new QLabel(qWidget);
    label0->setGeometry(20,20,100,30);
    label0->setText("Numlevels:");
    label0->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_NumLevels = new QSpinBox(qWidget);
    input_Create_NumLevels->setGeometry(120,20,100,30);
    input_Create_NumLevels->setRange(-1, 10);  // 范围
    input_Create_NumLevels->setSingleStep(1); // 步长
    //input_Create_NumLevels->setSpecialValueText(tr("auto")); // 特殊文本值
    input_Create_NumLevels->setSpecialValueText("auto"); // 特殊文本值
    //input_Create_NumLevels->setSpecialValueText("11"); // 特殊文本值
    //QSpinBox.setSpecialValueText('')                #设置最小值对应文本
    input_Create_NumLevels->setValue(-1);



    QLabel *label1 = new QLabel(qWidget);
    label1->setGeometry(20,55,100,30);
    label1->setText("AngleStart:");
    label1->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_AngleStart = new QSpinBox(qWidget);
    input_Create_AngleStart->setGeometry(120,55,100,30);
    input_Create_AngleStart->setRange(-360, 360);  // 范围
    input_Create_AngleStart->setSingleStep(10); // 步长
    //pSpinBox->setPrefix("$ ");  // 前缀
    input_Create_AngleStart->setSuffix("°");  // 后缀
    input_Create_AngleStart->setValue(-180);


    QLabel *label2 = new QLabel(qWidget);
    label2->setGeometry(20,90,100,30);
    label2->setText("AngleExtent:");
    label2->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_AngleExtent = new QSpinBox(qWidget);
    input_Create_AngleExtent->setGeometry(120,90,100,30);
    input_Create_AngleExtent->setRange(-360, 360);  // 范围
    input_Create_AngleExtent->setSingleStep(10); // 步长
    //pSpinBox->setPrefix("$ ");  // 前缀
    input_Create_AngleExtent->setSuffix("°");  // 后缀
    input_Create_AngleExtent->setValue(180);

    QLabel *label3 = new QLabel(qWidget);
    label3->setGeometry(20,125,100,30);
    label3->setText("AngleStep:");
    label3->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_AngleStep= new QSpinBox(qWidget);
    input_Create_AngleStep->setGeometry(120,125,100,30);
    input_Create_AngleStep->setRange(-1, 11);  // 范围
    input_Create_AngleStep->setSingleStep(1); // 步长
    //pSpinBox->setPrefix("$ ");  // 前缀
    input_Create_AngleStep->setSuffix("°");  // 后缀
    input_Create_AngleStep->setSpecialValueText("auto"); // 特殊文本值
    input_Create_AngleStep->setValue(-1);


    QLabel *label4 = new QLabel(qWidget);
    label4->setGeometry(20,160,100,30);
    label4->setText("ScaleMin:");
    label4->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_ScaleMin= new QDoubleSpinBox(qWidget);
    input_Create_ScaleMin->setGeometry(120,160,100,30);
    input_Create_ScaleMin->setRange(0.1, 1.0);  // 范围
    input_Create_ScaleMin->setDecimals(1);
    input_Create_ScaleMin->setSingleStep(0.1); // 步长
    input_Create_ScaleMin->setValue(0.9);

    QLabel *label5 = new QLabel(qWidget);
    label5->setGeometry(20,195,100,30);
    label5->setText("ScaleMax:");
    label5->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_ScaleMax= new QDoubleSpinBox(qWidget);
    input_Create_ScaleMax->setGeometry(120,195,100,30);
    input_Create_ScaleMax->setRange(1.0, 10.0);  // 范围
    input_Create_ScaleMax->setDecimals(1);
    input_Create_ScaleMax->setSingleStep(0.1); // 步长
    input_Create_ScaleMax->setValue(1.1);


    QLabel *label6 = new QLabel(qWidget);
    label6->setGeometry(20,230,100,30);
    label6->setText("ScaleStep:");
    label6->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_ScaleStep = new QDoubleSpinBox(qWidget);
    input_Create_ScaleStep->setGeometry(120,230,100,30);
    input_Create_ScaleStep->setRange(-0.01, 0.5);  // 范围
    input_Create_ScaleStep->setDecimals(2);
    input_Create_ScaleStep->setSingleStep(0.01); // 步长
    input_Create_ScaleStep->setSpecialValueText("auto"); // 特殊文本值
    input_Create_ScaleStep->setValue(-0.01);


    QLabel *label7 = new QLabel(qWidget);
    label7->setGeometry(20,265,100,30);
    label7->setText("Optimization:");
    label7->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_Optimization = new QComboBox(qWidget);
    input_Create_Optimization->setGeometry(120,265,100,30);
    QStringList str_Create_Optimization;
    str_Create_Optimization<<"auto"<<"no_pregeneration"<<"none"<<"point_reduction_high"
                          <<"point_reduction_low"<<"point_reduction_medium"<<"pregeneration";
    input_Create_Optimization->addItems(str_Create_Optimization);
    input_Create_Optimization->setCurrentIndex(0);
    //currentIndex



    QLabel *label8 = new QLabel(qWidget);
    label8->setGeometry(20,300,100,30);
    label8->setText("Metric:");
    label8->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_Metric = new QComboBox(qWidget);
    input_Create_Metric->setGeometry(120,300,100,30);
    QStringList str_Create_Metric;
    str_Create_Metric<<"ignore_color_polarity"<<"ignore_global_polarity"
                          <<"ignore_local_polarity"<<"use_polarity";
    input_Create_Metric->addItems(str_Create_Metric);
    input_Create_Metric->setCurrentIndex(3);
    //currentIndex8



    QLabel *label9 = new QLabel(qWidget);
    label9->setGeometry(20,335,100,30);
    label9->setText("Contrast:");
    label9->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_Contrast = new QComboBox(qWidget);
    input_Create_Contrast->setGeometry(120,335,100,30);
    QStringList str_Create_Contrast;
    str_Create_Contrast<<"auto"<<"auto_contrast"<<"auto_contrast_hyst"<<"auto_min_size"
                      <<"10"<<"20"<<"30"<<"40"<<"60"<<"80"<<"100"<<"120"<<"140"<<"160";
    input_Create_Contrast->addItems(str_Create_Contrast);
    input_Create_Contrast->setCurrentIndex(0);


    QLabel *label10 = new QLabel(qWidget);
    label10->setGeometry(20,370,100,30);
    label10->setText("MinContrast:");
    label10->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Create_MinContrast = new QComboBox(qWidget);
    input_Create_MinContrast->setGeometry(120,370,100,30);
    QStringList str_Create_MinContrast;
    str_Create_MinContrast<<"auto"<<"1"<<"2"<<"3"<<"5"<<"7"<<"10"<<"20"<<"30"<<"40";
    input_Create_MinContrast->addItems(str_Create_MinContrast);
    input_Create_MinContrast->setCurrentIndex(0);


    return qWidget;
}

QWidget *Widget::createTab2()
{
    //标签页2
    QWidget *qWidget = new QWidget;


    QLabel *label0 = new QLabel(qWidget);
    label0->setGeometry(20,20,100,30);
    label0->setText("AngleStart:");
    label0->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_AngleStart = new QSpinBox(qWidget);
    input_Find_AngleStart->setGeometry(120,20,100,30);
    input_Find_AngleStart->setRange(-360, 360);  // 范围
    input_Find_AngleStart->setSingleStep(10); // 步长
    input_Find_AngleStart->setSuffix("°");  // 后缀
    input_Find_AngleStart->setValue(-180);


    QLabel *label1 = new QLabel(qWidget);
    label1->setGeometry(20,55,100,30);
    label1->setText("AngleExtent:");
    label1->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_AngleExtent = new QSpinBox(qWidget);
    input_Find_AngleExtent->setGeometry(120,55,100,30);
    input_Find_AngleExtent->setRange(-360, 360);  // 范围
    input_Find_AngleExtent->setSingleStep(10); // 步长
    input_Find_AngleExtent->setSuffix("°");  // 后缀
    input_Find_AngleExtent->setValue(180);


    QLabel *label2 = new QLabel(qWidget);
    label2->setGeometry(20,90,100,30);
    label2->setText("ScaleMin:");
    label2->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_ScaleMin= new QDoubleSpinBox(qWidget);
    input_Find_ScaleMin->setGeometry(120,90,100,30);
    input_Find_ScaleMin->setRange(0.1, 1.0);  // 范围
    input_Find_ScaleMin->setDecimals(1);
    input_Find_ScaleMin->setSingleStep(0.1); // 步长
    input_Find_ScaleMin->setValue(0.9);

    QLabel *label3 = new QLabel(qWidget);
    label3->setGeometry(20,125,100,30);
    label3->setText("ScaleMax:");
    label3->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_ScaleMax= new QDoubleSpinBox(qWidget);
    input_Find_ScaleMax->setGeometry(120,125,100,30);
    input_Find_ScaleMax->setRange(1.0, 10.0);  // 范围
    input_Find_ScaleMax->setDecimals(1);
    input_Find_ScaleMax->setSingleStep(0.1); // 步长
    input_Find_ScaleMax->setValue(1.1);

    QLabel *label4 = new QLabel(qWidget);
    label4->setGeometry(20,160,100,30);
    label4->setText("MinScore:");
    label4->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_MinScore= new QDoubleSpinBox(qWidget);
    input_Find_MinScore->setGeometry(120,160,100,30);
    input_Find_MinScore->setRange(0, 1);  // 范围
    input_Find_MinScore->setDecimals(2);
    input_Find_MinScore->setSingleStep(0.05); // 步长
    input_Find_MinScore->setValue(0.5);

    QLabel *label5 = new QLabel(qWidget);
    label5->setGeometry(20,195,100,30);
    label5->setText("NumMatches:");
    label5->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_NumMatches= new QSpinBox(qWidget);
    input_Find_NumMatches->setGeometry(120,195,100,30);
    input_Find_NumMatches->setRange(0, 99);  // 范围
    //input_Find_NumMatches->setDecimals(2);
    input_Find_NumMatches->setSingleStep(1); // 步长
    input_Find_NumMatches->setValue(1);


    QLabel *label6 = new QLabel(qWidget);
    label6->setGeometry(20,230,100,30);
    label6->setText("MaxOverlap:");
    label6->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_MaxOverlap = new QDoubleSpinBox(qWidget);
    input_Find_MaxOverlap->setGeometry(120,230,100,30);
    input_Find_MaxOverlap->setRange(0, 1);  // 范围
    input_Find_MaxOverlap->setDecimals(2);
    input_Find_MaxOverlap->setSingleStep(0.05); // 步长
    input_Find_MaxOverlap->setValue(0.5);



    QLabel *label7 = new QLabel(qWidget);
    label7->setGeometry(20,265,100,30);
    label7->setText("SubPixel:");
    label7->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_SubPixel = new QComboBox(qWidget);
    input_Find_SubPixel->setGeometry(120,265,100,30);
    QStringList str_Find_SubPixel;
    str_Find_SubPixel<<"interpolation"<<"least_squares"<<"least_squares_high"<<
            "least_squares_very_high"<<"max_deformation 1"<<"max_deformation 2"<<
            "max_deformation 3"<<"max_deformation 4"<<"max_deformation 5"<<
            "max_deformation 6"<<"none";
    input_Find_SubPixel->addItems(str_Find_SubPixel);
    input_Find_SubPixel->setCurrentIndex(1);


    QLabel *label8 = new QLabel(qWidget);
    label8->setGeometry(20,300,100,30);
    label8->setText("NumLevels:");
    label8->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_NumLevels = new QSpinBox(qWidget);
    input_Find_NumLevels->setGeometry(120,300,100,30);
    input_Find_NumLevels->setRange(0, 10);  // 范围
    input_Find_NumLevels->setSingleStep(1); // 步长
    input_Find_NumLevels->setValue(0);


    QLabel *label9 = new QLabel(qWidget);
    label9->setGeometry(20,335,100,30);
    label9->setText("Greediness:");
    label9->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    input_Find_Greediness = new QDoubleSpinBox(qWidget);
    input_Find_Greediness->setGeometry(120,335,100,30);
    input_Find_Greediness->setRange(0, 1);  // 范围
    input_Find_Greediness->setDecimals(2);
    input_Find_Greediness->setSingleStep(0.05); // 步长
    input_Find_Greediness->setValue(0.9);


    return qWidget;
}

QWidget *Widget::createTab3()
{
    //标签页3
    QWidget *qWidget = new QWidget;

    tableWidget = new QTableWidget(qWidget);
    tableWidget->setRowCount(0);
    tableWidget->setColumnCount(5);
    //page2->addWidget();
    tableWidget->setGeometry(0,20,244,400);
    tableWidget->verticalHeader()->setVisible(false); //隐藏列表头
    tableWidget->setColumnWidth(0, 100);
    tableWidget->setColumnWidth(1, 100);
    tableWidget->setColumnWidth(2, 100);
    tableWidget->setColumnWidth(3, 100);
    tableWidget->setColumnWidth(4, 100);
    QStringList headerText;
    headerText<<"行"<<"列"<<"角度"<<"比例"<<"分数";
    tableWidget->setHorizontalHeaderLabels(headerText);
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableWidget->horizontalHeader()->setDisabled(true);//禁止用户拖动改变列宽
    tableWidget->verticalHeader()->setDisabled(true);//设置行不能拖动

    return qWidget;
}


void Widget::on_btn_ROI_clicked(){
    qDebug()<<"on_btn_ROI_clicked()";
    ROI = !ROI;
}


void Widget::on_btn_Create_clicked(){
    qDebug()<<"on_btn_Create_clicked()";
    Create_Scaled_Shape_Model();
}
void Widget::on_btn_Match_clicked(){
    qDebug()<<"on_btn_Matching_clicked()";
    //Matching();
    /*
    //创建形状模板
    HTuple  hv_ModelID;
    //HObject  ho_GrayImageROI;
    //Rgb1ToGray(ho_ImageROI, &ho_GrayImageROI);
    //qDebug()<<"Rgb1ToGray";

    CreateShapeModel(ho_ImageROI, 2, 0, HTuple(270).TupleRad(), "auto", "none",
        "ignore_global_polarity", 20, 10, &hv_ModelID);
    qDebug()<<"CreateShapeModel";
    */
    //Create_Scaled_Shape_Model();
    Find_Scaled_Shape_Models();

    IsMatching = !IsMatching;

}


//鼠标 点击
void Widget::mousePressEvent(QMouseEvent *e)
{
    //获取点击的下标
    if(ROI){
        if(label_ImageShow->geometry().contains(this->mapFromGlobal(QCursor::pos())) //鼠标是否在界面上
                    &&e->button()==Qt::LeftButton)
        {
            qDebug() << "左键" ;
            SPoint.setX(e->x());
            SPoint.setY(e->y());
            qDebug() <<"SX:"<< SPoint.x();
            qDebug() <<"SY:"<< SPoint.y();
        }

    }

}

//鼠标 移动
void Widget::mouseMoveEvent(QMouseEvent * e)
{
    if(ROI){
        if(label_ImageShow->geometry().contains(this->mapFromGlobal(QCursor::pos())))//鼠标是否在界面上
        {
            qDebug() << "左键位置移动到" ;
            EPoint.setX(e->x());
            EPoint.setY(e->y());
            qDebug() <<"EX:"<< SPoint.x();
            qDebug() <<"EY:"<< SPoint.y();
        }
        double scale_x;
        double scale_y;
        try
        {
            GetImageSize(ho_Image, &hv_Width, &hv_Height);
            scale_x = (double)hv_Width / label_ImageShow->width();
            scale_y = (double)hv_Height / label_ImageShow->height();
            sPoint.setX((SPoint.x()-label_ImageShow->geometry().x())*scale_x);
            sPoint.setY((SPoint.y()-label_ImageShow->geometry().y())*scale_y);
             ePoint.setX((EPoint.x()-label_ImageShow->geometry().x())*scale_x);
            ePoint.setY((EPoint.y()-label_ImageShow->geometry().y())*scale_y);
            hv_rowsROI.Clear();
            hv_rowsROI[0] = sPoint.y();
            hv_rowsROI[1] = ePoint.y();
            hv_rowsROI[2] = ePoint.y();
            hv_rowsROI[3] = sPoint.y();
            hv_rowsROI[4] = sPoint.y();
            hv_colsROI.Clear();
            hv_colsROI[0] = sPoint.x();
            hv_colsROI[1] = sPoint.x();
            hv_colsROI[2] = ePoint.x();
            hv_colsROI[3] = ePoint.x();
            hv_colsROI[4] = sPoint.x();
            GenContourPolygonXld(&ROIContour, hv_rowsROI, hv_colsROI);
            ClearWindow(HDevWindowStack::GetActive());
            SetColor(HDevWindowStack::GetActive(),"green");
            SetLineWidth(HDevWindowStack::GetActive(),4);
            DispObj(ho_Image, HDevWindowStack::GetActive());
            DispObj(ROIContour,HDevWindowStack::GetActive());
        }
        catch (HException &HDevExpDefaultException)
        {
            HTuple  hv_Exception;
            HDevExpDefaultException.ToHTuple(&hv_Exception);
            qDebug() <<"错误";
        }
    }

}


//鼠标 松开
void Widget::mouseReleaseEvent(QMouseEvent * e)
{
    if(ROI){
        try{
            GenRectangle1(&ho_RectangleROI, sPoint.y(), sPoint.x(), ePoint.y(), ePoint.x());
            //对ROI区域进行裁剪
            //Rgb1ToGray(ho_Image, &ho_GrayImage);
            //qDebug()<<"Rgb1ToGray(ho_Image, &ho_GrayImage);";
            ReduceDomain(ho_Image, ho_RectangleROI, &ho_ImageReducedROI);
            //ReduceDomain(ho_GrayImage, ho_RectangleROI, &ho_ImageReducedROI);
            //GetImageSize(ho_ImageReducedROI, &hv_WidthROI, &hv_HeightROI);

            //SetPart(hv_WindowHandleROI, sPoint.y(), sPoint.x(), ePoint.y(), ePoint.x());
            //DispObj(ho_ImageReducedROI, hv_WindowHandleROI);

            qDebug()<<"成功截取感兴趣区域";
        }
        catch (HException &HDevExpDefaultException)
        {
            HTuple  hv_Exception;
            HDevExpDefaultException.ToHTuple(&hv_Exception);
        }
    }
}


void Widget::Create_Scaled_Shape_Model(){
    qDebug()<<"Create_Scaled_Shape_Model()";
    //HTuple  hv_ModelID;

    //获得一个截图
    HObject ho_ModelImage;
    HTuple hv_ModelWidth,hv_ModelHeight;

    ho_ModelImage = ho_ImageReducedROI;

    GetImageSize(ho_ModelImage, &hv_ModelWidth, &hv_ModelHeight);
    SetPart(hv_WindowHandleROI,0,0,hv_ModelWidth, hv_ModelHeight);

    ClearWindow(hv_WindowHandleROI);
    DispObj(ho_ModelImage, hv_WindowHandleROI);

    ClearShapeModel(hv_ModelID);


    //CreateScaledShapeModel(ho_ImageReducedROI, "auto", HTuple(0).TupleRad(), HTuple(0).TupleRad(),
    //      "auto", 0.5, 2,"auto", "auto", "use_polarity", "auto", "auto", &hv_ModelID);

    /*
     *  HObject ho_SearchGrayImage;

    Rgb1ToGray(ho_Image, &ho_SearchGrayImage);
    */
    ///

    ///
    HTuple value_Create_NumLevels;
    HTuple value_Create_AngleStart;
    HTuple value_Create_AngleExtent;
    HTuple value_Create_AngleStep;
    HTuple value_Create_ScaleMin;
    HTuple value_Create_ScaleMax;
    HTuple value_Create_ScaleStep;
    HTuple value_Create_Optimization;
    HTuple value_Create_Metric;
    HTuple value_Create_Contrast;
    HTuple value_Create_MinContrast;

    value_Create_NumLevels = input_Create_NumLevels->value();
    if(value_Create_NumLevels.I()==-1){
        value_Create_NumLevels = "auto";
        qDebug()<<"value_Create_NumLevels:"<value();
    qDebug()<<"value_Create_AngleStart:"<value();
    qDebug()<<"value_Create_AngleExtent:"<value();
    if(value_Create_AngleStep.I()==-1){
        value_Create_AngleStepRad = "auto";
        qDebug()<<"value_Create_AngleStep:"<value();
    qDebug()<<"value_Create_ScaleMin:"<value();
    qDebug()<<"value_Create_ScaleMax:"<value();
    if(value_Create_ScaleStep.D()==-0.01){
        value_Create_ScaleStep = "auto";
        qDebug()<<"value_Create_ScaleStep:"<currentText();
    value_Create_Optimization = (input_Create_Optimization->currentText()).toLatin1().data();
    qDebug()<<"value_Create_Optimization:"<currentText()).toLatin1().data();
    qDebug()<<"value_Create_Metric:"<currentText()).toLatin1().data();
    qDebug()<<"value_Create_Contrast:"<currentText()).toLatin1().data();
    qDebug()<<"value_Create_MinContrast:"<value();
    qDebug()<<"value_Find_AngleStart:"<value();
    qDebug()<<"value_Create_AngleExtent:"<value();
    qDebug()<<"value_Find_ScaleMin:"<value();
    qDebug()<<"value_Find_ScaleMax:"<value();
    qDebug()<<"value_Find_MinScore:"<value();
    qDebug()<<"value_Find_NumMatches:"<value();
    qDebug()<<"value_Find_MaxOverlap:"<currentText()).toLatin1().data();
    qDebug()<<"value_Find_SubPixel:"<value();
    qDebug()<<"value_Find_NumLevels:"<value();
    qDebug()<<"value_Find_Greediness:"<setRowCount(hv_RowCheck.Length());
    for (int i=0 ;isetTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);//内容居中
        tableWidget->setItem(i, 0, item0);


        QTableWidgetItem *item1 = new QTableWidgetItem(QString::number((double)((const HTuple&)hv_ColumnCheck)[i]));
        item1->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);//内容居中
        tableWidget->setItem(i, 1, item1);


        QTableWidgetItem *item2 = new QTableWidgetItem(QString::number((double)((const HTuple&)hv_AngleCheck)[i]));
        item2->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);//内容居中
        tableWidget->setItem(i, 2, item2);


        QTableWidgetItem *item3 = new QTableWidgetItem(QString::number((double)((const HTuple&)hv_ScaleCheck)[i]));
        item3->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);//内容居中
        tableWidget->setItem(i, 3, item3);

        QTableWidgetItem *item4 = new QTableWidgetItem(QString::number((double)((const HTuple&)hv_ScoreCheck)[i]));
        item4->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);//内容居中
        tableWidget->setItem(i, 4, item4);
    }

}

你可能感兴趣的:(Qt+Halcon,Halcon,Qt,qt)