#include <QApplication>
#include <QMainWindow>
#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>
#include <QStatusBar>
#include <QFileDialog>
#include <QStatusBar>
#include <QElapsedTimer>
#include "HalconCpp.h"
using namespace HalconCpp;
class HalconQtApp: public QMainWindow {
Q_OBJECT
public:
HalconQtApp(QWidget *parent = nullptr) : QMainWindow(parent)
{
setupUI();
setupHalcon();
}
~HalconQtApp(){
if(windowHandle.IsInitialized())
{
windowHandle.CloseWindow();
}
}
private slots:
void loadImage(){
QString filename = QFileDialog::getOpenFileName(this, "打开图像", "", "图像文件 (*.jpg *.png *.bmp *.tif)");
if(!filename.isEmpty())
{
QElapsedTimer timer;
timer.start();
try{
//读取图像
image.ReadImage(filename.toStdString().c_str());
//处理图像
processImage();
//显示处理结果
displayResult();
//更新状态栏
statusBar()->showMessage(
QString("图像加载处理完成 | 尺寸:%1x%2 | 耗时:%3 ms")
.arg(image.Width()).arg(image.Height())
.arg(timer.elapsed())
);
}
catch (HException &ex)
{
statusBar()->showMessage("错误: " + QString(ex.ErrorMesssage().Text()));
}
}
}
void processEdges()
{
if(!image.IsInitialized())
return;
QElapsedTimer timer;
timer.start();
try{
//Sobel边缘检测
HImage sobel;
sobel = image.SobelAmp("sum_abs", 3);
//阈值处理
HRegion region = sobel.Threshold(50, 255);
//区域处理
region = region.Connection();
region = region.SelectShape("area", "and", 500, 99999);
region = region.DilationCircle(1.5);
//创建轮廓
HXLDCont edges = region.GenContourRegionX1d("border");
//在原始图像上绘制边缘
resultImage = image;
HTuple row, col;
edges.GetContourX1d(&row, &col);
resultImage = resultImage.PaintX1d(edges, QColor(255, 0, 0).rgb(), "fill");
//显示结果
displayResult();
statusBar()->showMessage(QString("边缘检测完成 | 耗时: %1 ms").arg(timer.elapsed()));
}
catch (HException &ex) {
statusBar()->showMessage("处理错误: "+QString(ex.ErrorMessage().Text()));
}
}
void processBlobs()
{
if(!image.IsInitialized())
return;
QElapsedTimer timer;
timer.start();
try{
//颜色空间转换
HImage gray;
image.RgblToGray();
//阈值处理
HRegion region = gray.Threshold(100, 255);
//区域处理
region = region.Connection();
region = region.SelectShape("area", "and", 500, 99999);
region = region.FillUp();
//特征提取
HTuple area, row, col;
region.AreaCenter(&area, &row, &col);
//在原始图像上绘制结果
resultImage = image;
for(int i = 0; i < area.Length(); i++)
{
//绘制区域
resultImage = resultImage.PaintRegin(region.SelectObj(i+1),
QColor(0,255,0).rgb(),
"fill");
//绘制中心点
resultImage = resultImage.PAintXld(HXLDCont(row[i].D(), col[i].D()),
QColor(0,255,0).rgb(),
"fill");
//绘制面积值
resultImage = resultImage.WriteString(
HTuple("Area: ") + area[i],
row[i].D(),
col[i].D() - 30,
"Arial", 12, "bold", QColor(255, 255, 0).rgb());
}
//显示结果
displayResult();
statusBar()->showMessage(QString("边缘检测完成 | 耗时: %1 ms").arg(timer.elapsed()));
}
catch (HException &ex) {
statusBar()->showMessage("处理错误: "+QString(ex.ErrorMessage().Text()));
}
}
}