- #include "widget.h"
- #include <QVBoxLayout>
- #include <QImage>
- #include <QPixmap>
- #include <QDebug>
- #include <QFile>
- Widget::Widget(QWidget *parent) : QWidget(parent) {
- // 创建布局和标签
- QVBoxLayout *layout = new QVBoxLayout(this);
- imageLabel = new QLabel(this);
- layout->addWidget(imageLabel);
- // 加载并显示图像
- loadAndDisplayImage("/home/xue/HalconQt/halcon_qt/logo.bmp");
- }
- Widget::~Widget() {
- // 资源清理(如果需要)
- }
- void Widget::loadAndDisplayImage(const QString &imagePath) {
- // 检查图像文件是否存在
- if (!QFile::exists(imagePath)) {
- qDebug() << "Image file does not exist:" << imagePath;
- return;
- }
- HObject ho_Image;
- try {
- ReadImage(&ho_Image, imagePath.toStdString().c_str());
- qDebug() << "Image loaded successfully.";
- } catch (HOperatorException &ex) {
- qDebug() << "Error reading image:" << ex.ErrorMessage();
- return;
- }
- // 检查图像是否有效
- HTuple hv_Num;
- CountObj(ho_Image, &hv_Num);
- if (hv_Num == 0) {
- qDebug() << "Loaded image is empty.";
- return;
- }
- // 处理图像
- HObject ho_ProcessedImage;
- try {
- processImage(ho_Image, ho_ProcessedImage);
- } catch (HOperatorException &ex) {
- qDebug() << "Error processing image:" << ex.ErrorMessage();
- return; // 处理失败,返回
- }
- // 检查处理后图像是否有效
- if (!ho_ProcessedImage.IsInitialized()) {
- qDebug() << "Processed image is empty, skipping display.";
- return; // 或者可以选择显示原始图像
- }
- // 获取处理后图像的尺寸
- HTuple hv_Width, hv_Height;
- GetImageSize(ho_ProcessedImage, &hv_Width, &hv_Height);
- // 创建QImage
- QImage qImage(hv_Width[0].I(), hv_Height[0].I(), QImage::Format_RGB888);
- for (int y = 0; y < hv_Height[0].I(); y++) {
- for (int x = 0; x < hv_Width[0].I(); x++) {
- HTuple hv_Pixel;
- GetGrayval(ho_ProcessedImage, x, y, &hv_Pixel);
- qImage.setPixel(x, y, qRgb(hv_Pixel[0].I(), hv_Pixel[0].I(), hv_Pixel[0].I()));
- }
- }
- // 显示图像
- imageLabel->setPixmap(QPixmap::fromImage(qImage));
- }
- void Widget::processImage(HObject &image, HObject &processedImage) {
- // 获取图像尺寸
- HTuple hv_Width, hv_Height;
- GetImageSize(image, &hv_Width, &hv_Height);
- // 输出图像尺寸
- qDebug() << "Processing image of size:" << hv_Width[0].I() << "x" << hv_Height[0].I();
- // 使用边缘检测
- try {
- EdgesSubPix(image, &processedImage, "canny", 3, 20, 40);
- } catch (HOperatorException &ex) {
- qDebug() << "Error in edge detection:" << ex.ErrorMessage();
- // 处理异常后返回一个默认图像或空图像
- processedImage = HObject(); // 或者设置为某个默认图像
- return;
- }
- }
复制代码
我写了一个这个,然后输出结果仍然是这样的
- Processing image of size: 640 x 640
- terminate called after throwing an instance of 'HalconCpp::HOperatorException'
复制代码
|