QT+Halcon综合示例(一):clip回形针2D位姿检测
- 0、halcon源码:
- 1、Qt代码:
- 2、运行结果:
下载:clip回形针2D位姿检测
0、halcon源码:
* clip.hdev: Orientation of clips
*
dev_close_window ()
dev_update_window ('off')
*read_image (Clip, 'clip')
read_image (Clip, 'F:/C++/5. HALCON/qtest_hc/clip_3.png')
get_image_size (Clip, Width, Height)
dev_open_window (0, 0, Width / 2, Height / 2, 'black', WindowID)
dev_display (Clip)
*设置字体
set_display_font (WindowID, 14, 'mono', 'true', 'false')
stop ()
*二进制阈值分割
binary_threshold (Clip, Dark, 'max_separability', 'dark', UsedThreshold)
connection (Dark, Single)
*利用面积特征选择区域
select_shape (Single, Selected, 'area', 'and', 2000, 10000)
dev_set_draw ('fill')
dev_set_colored (12)
dev_display (Selected)
stop ()
*显示
dev_display (Clip)
dev_set_color ('green')
dev_display (Selected)
*区域的方向:计算了距重心与最大距离轮廓上的点连线角度(弧度制)
*- pi <= Phi && Phi < pi
orientation_region (Selected, Phi)
area_center (Selected, Area, Row, Column)
dev_set_line_width (3)
dev_set_draw ('margin')
*箭头长度
Length := 90
dev_set_color ('blue')
*显示 箭头图案
disp_arrow (WindowID, Row, Column, Row - Length * sin(Phi), Column + Length * cos(Phi), 4)
disp_message (WindowID, deg(Phi)$'3.1f' + ' deg', 'image', Row, Column - 100, 'black', 'false')
dev_update_window ('on')
halcon运行:
1、Qt代码:
界面
1).pro 添加:
macx {QMAKE_CXXFLAGS += -F/Library/FrameworksQMAKE_LFLAGS += -F/Library/FrameworksLIBS += -framework HALCONCpp
}
else {#defineswin32:DEFINES += WIN32#includesINCLUDEPATH += "$$(HALCONROOT)/include"INCLUDEPATH += "$$(HALCONROOT)/include/halconcpp"#libsQMAKE_LIBDIR += "$$(HALCONROOT)/lib/$$(HALCONARCH)"unix:LIBS += -lhalconcpp -lhalcon -lXext -lX11 -ldl -lpthreadwin32:LIBS += "$$(HALCONROOT)/lib/$$(HALCONARCH)/halconcpp.lib" \"$$(HALCONROOT)/lib/$$(HALCONARCH)/halcon.lib"
}
2)主函数 main.cpp 添加:
#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}
3)Widget.h 添加:
#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include "HalconCpp.h"
#include "HDevThread.h"#include <QFileDialog>
#include <QMessageBox>namespace Ui {
class Widget;
}
using namespace HalconCpp;class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();private slots:void on_pushButton_clicked(); // 读取图片void on_pushButton_2_clicked(); // connectionvoid on_pushButton_3_clicked(); // select_shapevoid on_pushButton_4_clicked(); // orientationvoid on_pushButton_6_clicked(); // auto 自动处理void on_pushButton_7_clicked(); // 重置resetprivate:Ui::Widget *ui;
public:HObject ho_Clip, ho_Dark, ho_Single, ho_Selected,ho_null;// Local control variablesHTuple hv_Width, hv_Height, hv_WindowID1, hv_WindowID2,hv_WindowID3,hv_WindowID4,hv_UsedThreshold,hv_WindowID0;HTuple hv_Phi, hv_Area, hv_Row, hv_Column, hv_Length;// Short Description: This procedure writes a text message.void disp_message (HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem, HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box);// Short Description: Set font independent of OSvoid set_display_font (HTuple hv_WindowHandle, HTuple hv_Size, HTuple hv_Font, HTuple hv_Bold,HTuple hv_Slant);private:int width_sc,height_sc; // 新键窗口的 宽高int row_o,col_o; // 新建窗口起点HTuple test_tqual_n;
};#endif // WIDGET_H
4)Widget.cpp 添加:
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);ui->label->setStyleSheet("background-color:lightGray;");ui->label_2->setStyleSheet("background-color:lightGray;");ui->label_3->setStyleSheet("background-color:lightGray;");ui->label_4->setStyleSheet("background-color:lightGray;");this->setWindowTitle("Clip(2D位姿识别)");GenEmptyObj(&ho_null);
}Widget::~Widget()
{delete ui;}// 一、读取图片
void Widget::on_pushButton_clicked()
{HObject ho_Clip0;QString fileName = QFileDialog::getOpenFileName(this, tr("文件对话框"),"F:/C++/5. HALCON/qtest_hc", tr("图片文件(*.png *.jpg *.jpeg *.bmp *.tif *.tiff);;所有文件(*)"));if(!fileName.isEmpty()){// 清空ui->pushButton_7->click();HTuple ImageName(fileName.toLocal8Bit().data());HTuple cout_channel;ReadImage(&ho_Clip0,ImageName);// 转灰度图(可以不转)CountChannels(ho_Clip0,&cout_channel);if(cout_channel ==3){Rgb1ToGray(ho_Clip0,&ho_Clip);}else{ho_Clip = ho_Clip0;}// 获取图片尺寸GetImageSize(ho_Clip, &hv_Width, &hv_Height);// 显示:新建窗口(根据label 尺寸缩放图片)float ratio_label = (float)ui->label->width()/(float)ui->label->height();float ratio_img = (float)hv_Width/(float)hv_Height;if(ratio_label< ratio_img) // 图像比 label 矮胖{width_sc =ui->label->width();height_sc = hv_Height*ui->label->width()/hv_Width;row_o = (ui->label->height()-height_sc)/2;col_o = 0;}else{width_sc = hv_Width*ui->label->height()/hv_Height;height_sc =ui->label->height();row_o = 0;col_o = (ui->label->width()-width_sc)/2;}// 显示Hlong winID =(Hlong)ui->label->winId();SetWindowAttr("background_color","black"); // 设置窗口背景OpenWindow(row_o,col_o,width_sc,height_sc,winID,"visible","",&hv_WindowID1);HDevWindowStack::Push(hv_WindowID1); //新窗口的Push句柄if (HDevWindowStack::IsOpen()){// 显示图片SetPart(hv_WindowID1, 0, 0, hv_Height-1, hv_Width-1); // 显示部分DispObj(ho_Clip, HDevWindowStack::GetActive()); // 显示图片}}}// 二、处理图片 connection 计算连通分量
void Widget::on_pushButton_2_clicked()
{BinaryThreshold(ho_Clip, &ho_Dark, "max_separability", "dark", &hv_UsedThreshold);Connection(ho_Dark, &ho_Single);SelectShape(ho_Single, &ho_Selected, "area", "and", 4500, 10000);// 显示:// 1.新建窗口Hlong winID =(Hlong)ui->label_2->winId();OpenWindow(row_o,col_o,width_sc,height_sc,winID,"visible","",&hv_WindowID2);HDevWindowStack::Push(hv_WindowID2);if (HDevWindowStack::IsOpen()){// 2.设置显示样式SetPart(hv_WindowID2, 0, 0, hv_Height-1, hv_Width-1);SetDraw(HDevWindowStack::GetActive(),"fill");SetColored(HDevWindowStack::GetActive(),12);// 3.显示图片DispObj(ho_Selected, HDevWindowStack::GetActive());}
}// 三、显示图片select_shape
void Widget::on_pushButton_3_clicked()
{Hlong winID =(Hlong)ui->label_3->winId();OpenWindow(row_o,col_o,width_sc,height_sc,winID,"visible","",&hv_WindowID3);HDevWindowStack::Push(hv_WindowID3);if (HDevWindowStack::IsOpen()){// 显示 ho_ClipSetPart(hv_WindowID3, 0, 0, hv_Height-1, hv_Width-1);DispObj(ho_Clip, HDevWindowStack::GetActive());SetColor(HDevWindowStack::GetActive(),"green"); // 设置显示样式// 显示 ho_SelectedDispObj(ho_Selected, HDevWindowStack::GetActive());}
}// 四、处理图片 orientation
void Widget::on_pushButton_4_clicked()
{OrientationRegion(ho_Selected, &hv_Phi);AreaCenter(ho_Selected, &hv_Area, &hv_Row, &hv_Column); // 找圆形Hlong winID =(Hlong)ui->label_4->winId();OpenWindow(row_o,col_o,width_sc,height_sc,winID,"visible","",&hv_WindowID4);HDevWindowStack::Push(hv_WindowID4);if (HDevWindowStack::IsOpen()){// 再显示一遍(ho_Clip,ho_Selected)SetPart(hv_WindowID4, 0, 0, hv_Height-1, hv_Width-1);DispObj(ho_Clip, HDevWindowStack::GetActive());SetColor(HDevWindowStack::GetActive(),"green");DispObj(ho_Selected, HDevWindowStack::GetActive());// 设置显示样式(箭头)SetLineWidth(HDevWindowStack::GetActive(),3);SetDraw(HDevWindowStack::GetActive(),"margin");SetColor(HDevWindowStack::GetActive(),"blue");// 显示 箭头标记hv_Length = 80; // 箭头长度DispArrow(hv_WindowID4, hv_Row, hv_Column, hv_Row-(hv_Length*(hv_Phi.TupleSin())), hv_Column+(hv_Length*(hv_Phi.TupleCos())), 4);// 设置、显示字体set_display_font(hv_WindowID4, 14, "mono", "true", "false");disp_message(hv_WindowID4 ,((hv_Phi.TupleDeg()).TupleString("3.1f"))+" deg", "image",hv_Row, hv_Column-100, "black", "false");}
}// 自动处理
void Widget::on_pushButton_6_clicked()
{TestEqualObj(ho_Clip,ho_null,&test_tqual_n); // 若相等则区域为空,否则区域不为空if(test_tqual_n==0){ui->pushButton_2->click();ui->pushButton_3->click();ui->pushButton_4->click();}else{QMessageBox::information(this, tr("提示"),tr("未载入图片!"), QMessageBox::Ok);}
// try
// {
// ui->pushButton_2->click();
// ui->pushButton_3->click();
// ui->pushButton_4->click();
// }
// catch (HalconCpp::HException)
// {
// QMessageBox::information(this, tr("提示"),tr("未载入图片!"), QMessageBox::Ok);
// }}// 重置reset
void Widget::on_pushButton_7_clicked()
{// 四个窗口,清空4次for(int i=0;i<4;i++){if (HDevWindowStack::IsOpen()){CloseWindow(HDevWindowStack::Pop());}}
}void Widget::set_display_font(HTuple hv_WindowHandle, HTuple hv_Size, HTuple hv_Font, HTuple hv_Bold, HTuple hv_Slant)
{// Local iconic variables// Local control variablesHTuple hv_OS, hv_Fonts, hv_Style, hv_Exception;HTuple hv_AvailableFonts, hv_Fdx, hv_Indices;//This procedure sets the text font of the current window with//the specified attributes.////Input parameters://WindowHandle: The graphics window for which the font will be set//Size: The font size. If Size=-1, the default of 16 is used.//Bold: If set to 'true', a bold font is used//Slant: If set to 'true', a slanted font is used//GetSystem("operating_system", &hv_OS);// dev_get_preferences(...); only in hdevelop// dev_set_preferences(...); only in hdevelopif (0 != (HTuple(hv_Size==HTuple()).TupleOr(hv_Size==-1))){hv_Size = 16;}if (0 != ((hv_OS.TupleSubstr(0,2))==HTuple("Win"))){//Restore previous behaviourhv_Size = (1.13677*hv_Size).TupleInt();}if (0 != (hv_Font==HTuple("Courier"))){hv_Fonts.Clear();hv_Fonts[0] = "Courier";hv_Fonts[1] = "Courier 10 Pitch";hv_Fonts[2] = "Courier New";hv_Fonts[3] = "CourierNew";}else if (0 != (hv_Font==HTuple("mono"))){hv_Fonts.Clear();hv_Fonts[0] = "Consolas";hv_Fonts[1] = "Menlo";hv_Fonts[2] = "Courier";hv_Fonts[3] = "Courier 10 Pitch";hv_Fonts[4] = "FreeMono";}else if (0 != (hv_Font==HTuple("sans"))){hv_Fonts.Clear();hv_Fonts[0] = "Luxi Sans";hv_Fonts[1] = "DejaVu Sans";hv_Fonts[2] = "FreeSans";hv_Fonts[3] = "Arial";}else if (0 != (hv_Font==HTuple("serif"))){hv_Fonts.Clear();hv_Fonts[0] = "Times New Roman";hv_Fonts[1] = "Luxi Serif";hv_Fonts[2] = "DejaVu Serif";hv_Fonts[3] = "FreeSerif";hv_Fonts[4] = "Utopia";}else{hv_Fonts = hv_Font;}hv_Style = "";if (0 != (hv_Bold==HTuple("true"))){hv_Style += HTuple("Bold");}else if (0 != (hv_Bold!=HTuple("false"))){hv_Exception = "Wrong value of control parameter Bold";throw HalconCpp::HException(hv_Exception);}if (0 != (hv_Slant==HTuple("true"))){hv_Style += HTuple("Italic");}else if (0 != (hv_Slant!=HTuple("false"))){hv_Exception = "Wrong value of control parameter Slant";throw HalconCpp::HException(hv_Exception);}if (0 != (hv_Style==HTuple(""))){hv_Style = "Normal";}QueryFont(hv_WindowHandle, &hv_AvailableFonts);hv_Font = "";{HTuple end_val48 = (hv_Fonts.TupleLength())-1;HTuple step_val48 = 1;for (hv_Fdx=0; hv_Fdx.Continue(end_val48, step_val48); hv_Fdx += step_val48){hv_Indices = hv_AvailableFonts.TupleFind(HTuple(hv_Fonts[hv_Fdx]));if (0 != ((hv_Indices.TupleLength())>0)){if (0 != (HTuple(hv_Indices[0])>=0)){hv_Font = HTuple(hv_Fonts[hv_Fdx]);break;}}}}if (0 != (hv_Font==HTuple(""))){throw HalconCpp::HException("Wrong value of control parameter Font");}hv_Font = (((hv_Font+"-")+hv_Style)+"-")+hv_Size;SetFont(hv_WindowHandle, hv_Font);// dev_set_preferences(...); only in hdevelopreturn;
}void Widget::disp_message (HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem, HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box)
{HTuple hv_GenParamName, hv_GenParamValue;if (0 != (HTuple(hv_Row==HTuple()).TupleOr(hv_Column==HTuple()))){return;}if (0 != (hv_Row==-1)){hv_Row = 12;}if (0 != (hv_Column==-1)){hv_Column = 12;}//Convert the parameter Box to generic parameters.hv_GenParamName = HTuple();hv_GenParamValue = HTuple();if (0 != ((hv_Box.TupleLength())>0)){if (0 != (HTuple(hv_Box[0])==HTuple("false"))){//Display no boxhv_GenParamName = hv_GenParamName.TupleConcat("box");hv_GenParamValue = hv_GenParamValue.TupleConcat("false");}else if (0 != (HTuple(hv_Box[0])!=HTuple("true"))){//Set a color other than the default.hv_GenParamName = hv_GenParamName.TupleConcat("box_color");hv_GenParamValue = hv_GenParamValue.TupleConcat(HTuple(hv_Box[0]));}}if (0 != ((hv_Box.TupleLength())>1)){if (0 != (HTuple(hv_Box[1])==HTuple("false"))){//Display no shadow.hv_GenParamName = hv_GenParamName.TupleConcat("shadow");hv_GenParamValue = hv_GenParamValue.TupleConcat("false");}else if (0 != (HTuple(hv_Box[1])!=HTuple("true"))){//Set a shadow color other than the default.hv_GenParamName = hv_GenParamName.TupleConcat("shadow_color");hv_GenParamValue = hv_GenParamValue.TupleConcat(HTuple(hv_Box[1]));}}//Restore default CoordSystem behavior.if (0 != (hv_CoordSystem!=HTuple("window"))){hv_CoordSystem = "image";}//if (0 != (hv_Color==HTuple(""))){//disp_text does not accept an empty string for Color.hv_Color = HTuple();}//DispText(hv_WindowHandle, hv_String, hv_CoordSystem, hv_Row, hv_Column, hv_Color,hv_GenParamName, hv_GenParamValue);return;
}
2、运行结果: