qt写一个图像处理程序
时间: 2023-09-12 14:13:25 浏览: 138
好的,下面是一个简单的图像处理程序的示例代码,基于Qt框架和OpenCV库实现图像的读取、处理和展示。
首先需要在.pro文件中添加OpenCV的链接库:
```
LIBS += -lopencv_core -lopencv_highgui -lopencv_imgproc
```
然后创建一个Qt窗口,添加一个按钮和一个标签用于显示图像:
```cpp
#include <opencv2/opencv.hpp>
#include <QMainWindow>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QFileDialog>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void openImage();
void processImage();
private:
QPushButton *openButton;
QPushButton *processButton;
QLabel *imageLabel;
cv::Mat originalImage;
};
```
在构造函数中初始化UI界面和信号槽:
```cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
openButton = new QPushButton(tr("Open"));
processButton = new QPushButton(tr("Process"));
imageLabel = new QLabel;
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(openButton);
layout->addWidget(processButton);
QWidget *centralWidget = new QWidget;
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
connect(openButton, &QPushButton::clicked, this, &MainWindow::openImage);
connect(processButton, &QPushButton::clicked, this, &MainWindow::processImage);
}
```
打开图像文件并显示:
```cpp
void MainWindow::openImage()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), ".", tr("Image Files (*.png *.jpg *.bmp)"));
if (!fileName.isEmpty())
{
originalImage = cv::imread(fileName.toStdString());
cv::cvtColor(originalImage, originalImage, cv::COLOR_BGR2RGB);
QImage qimage(originalImage.data, originalImage.cols, originalImage.rows, QImage::Format_RGB888);
imageLabel->setPixmap(QPixmap::fromImage(qimage));
}
}
```
图像处理:
```cpp
void MainWindow::processImage()
{
// 图像处理代码
cv::Mat grayImage;
cv::cvtColor(originalImage, grayImage, cv::COLOR_RGB2GRAY);
QImage qimage(grayImage.data, grayImage.cols, grayImage.rows, grayImage.step, QImage::Format_Grayscale8);
imageLabel->setPixmap(QPixmap::fromImage(qimage));
}
```
最后,添加main函数并运行程序:
```cpp
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
```
这个程序只是一个简单的示例,你可以根据自己的需要进行修改和扩展。
阅读全文