首页 > 其他分享 >vs2022 QT Opencv用到的一些代码

vs2022 QT Opencv用到的一些代码

时间:2024-07-26 20:08:10浏览次数:8  
标签:clicked QT temp label Opencv ui vs2022 image2 cv

 

MyFirstQT.cpp

#include "MyFirstQT.h"
#include "ui_MyFirstQT.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QPixmap>
#include <opencv2/opencv.hpp>
#include <QDebug> 
#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
  , ui(new Ui::MyFirstQTClass)
{
    ui->setupUi(this);
    //connect(ui->loadImageButton, &QPushButton::clicked, this, &MainWindow::on_loadImageButton_clicked);//这句如果不注释,打开文件窗口会跳2次
    //connect(ui->sharpenImageButton, &QPushButton::clicked, this, &MainWindow::on_sharpenImageButton_clicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

cv::Mat img_input;

cv::Mat tempRH;//锐化
void MainWindow::on_loadImageButton_clicked()
{

    QString filename = QFileDialog::getOpenFileName(this, "打开图像文件", "C:/Users", "Image Files (*.bmp;*.png;*.jpg)");

    if (filename.isEmpty()) {
        QMessageBox::information(this, "提示", "文件打开失败1!");
        return;
    }

    img_input = cv::imread(filename.toLocal8Bit().toStdString());

    if (img_input.empty()) {

        QMessageBox::information(this, "提示", "文件打开失败2!");
        return;
    }

    cv::Mat temp;
    cv::cvtColor(img_input, temp, cv::COLOR_BGR2RGB);

    // 直接将文件名传递给 QPixmap 进行加载
    QPixmap pixmap = QPixmap::fromImage(QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888));

    if (pixmap.isNull()) {
        QMessageBox::information(this, "提示", "文件打开失败2!");
        return;
    }

    // 获取 label 的尺寸
    int labelWidth = ui->label_image->width();
    int labelHeight = ui->label_image->height();

    // 将 QPixmap 进行缩放
    QPixmap scaledPixmap = pixmap.scaled(labelWidth, labelHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    // 将缩放后的图像设置到 label 中
    ui->label_image->setPixmap(scaledPixmap);
    ui->label_image->setScaledContents(false); 
    ui->label_image->setAlignment(Qt::AlignCenter); 



}

void MainWindow::on_sharpenImageButton_clicked()
{
    // 假设之前加载的图像存储在成员变量 img_input 中
    if (img_input.empty()) {
        QMessageBox::information(this, "提示", "尚未加载图片,无法进行锐化操作!");
        return;
    }

    // 定义锐化核
    cv::Mat kernel = (cv::Mat_<float>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);

    cv::Mat img_sharpened;
    cv::filter2D(img_input, img_sharpened, -1, kernel);

    cv::Mat temp;
    cv::cvtColor(img_sharpened, temp, cv::COLOR_BGR2RGB);

    tempRH = img_sharpened;

    // 直接将锐化后的图像转换为 QPixmap 并显示在 label_image2 中
    QPixmap pixmap = QPixmap::fromImage(QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888));

    if (pixmap.isNull()) {
        QMessageBox::information(this, "提示", "锐化后的文件打开失败!");
        return;
    }

    // 获取 label_image2 的尺寸
    int labelWidth2 = ui->label_image2->width();
    int labelHeight2 = ui->label_image2->height();

    // 将 QPixmap 进行缩放
    QPixmap scaledPixmap = pixmap.scaled(labelWidth2, labelHeight2, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    // 将缩放后的图像设置到 label_image2 中
    ui->label_image2->setPixmap(scaledPixmap);
    ui->label_image2->setScaledContents(false); 
    ui->label_image2->setAlignment(Qt::AlignCenter); 
}

void MainWindow::on_histogramImageButton_clicked()
{

	if (img_input.empty()) {
    QMessageBox::information(this, "提示", "尚未加载图片,无法获取直方图!");
    return;
    }

    cv::Mat grayImg;
    cv::cvtColor(img_input, grayImg, cv::COLOR_BGR2GRAY);

    // 计算直方图
    Mat hist;
    int histSize = 256;
    float range[] = { 0, 256 };
    const float* histRange = { range };
    calcHist(&grayImg, 1, 0, Mat(), hist, 1, &histSize, &histRange);

    // 绘制直方图
    int hist_w = 500;  // 缩小宽度
    int hist_h = 400;
    int bin_w = cvRound((double)hist_w / histSize);

    Mat histImage(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0));
    normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, -1, Mat());

    for (int i = 1; i < histSize; i++) {
        line(histImage, Point(bin_w * (i - 1), hist_h - cvRound(hist.at<float>(i - 1))),
             Point(bin_w * i, hist_h - cvRound(hist.at<float>(i))),
             Scalar(255, 255, 255), 2);
    }

    // 绘制横坐标
    for (int x = 0; x <= 255; x += 50) {
        line(histImage, Point(bin_w * x, hist_h), Point(bin_w * x, hist_h - 10), Scalar(255, 255, 255), 1);
        putText(histImage, QString::number(x).toStdString(), Point(bin_w * x - 10, hist_h + 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255));
    }
    line(histImage, Point(bin_w * 255, hist_h), Point(bin_w * 255, hist_h - 10), Scalar(255, 255, 255), 1);  // 255 刻度线
    putText(histImage, "255", Point(bin_w * 255 - 10, hist_h + 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255));
    line(histImage, Point(hist_w, hist_h), Point(hist_w, hist_h - 10), Scalar(255, 255, 255), 1);  // 超出 255 的刻度线
    putText(histImage, "300", Point(hist_w - 20, hist_h + 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255));

    // 绘制纵坐标
    int y_interval = 250;
    for (int y = 0; y <= 2500; y += y_interval) {
        line(histImage, Point(0, hist_h - y / (2500.0 / hist_h)), Point(10, hist_h - y / (2500.0 / hist_h)), Scalar(255, 255, 255), 1);
        putText(histImage, QString::number(y).toStdString(), Point(20, hist_h - y / (2500.0 / hist_h) - 5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255));
    }

    // 将绘制的直方图转换为 QImage 并显示在 label_image2 中
    QImage qImg((const unsigned char*)(histImage.data), histImage.cols, histImage.rows, histImage.step, QImage::Format_RGB888);
    QPixmap pixmap = QPixmap::fromImage(qImg);
    ui->label_image2->setPixmap(pixmap);

}//直方图示范 https://blog.csdn.net/u010140856/article/details/79256015

void MainWindow::on_SaveButton_clicked()
{
	 if (tempRH.empty()) {
        QMessageBox::information(this, "提示", "尚未进行锐化操作,无法保存!");
        return;
    }



    QString savePath = QFileDialog::getSaveFileName(this, "保存锐化后的图片", "", "Image Files (*.bmp;*.png;*.jpg;*.jpeg;*.tif;*.tiff)");
    if (savePath.isEmpty()) {
        return;
    }

    cv::imwrite(savePath.toLocal8Bit().toStdString(), tempRH);  // 保存锐化后的图片,保持原始尺寸
}

//自动色阶

void MainWindow::on_autoLevelsButton_clicked()
{

    if (img_input.empty()) {
        QMessageBox::information(this, "提示", "尚未加载图片,无法进行转换为漫画操作!");
        return;
    }

    cv::Mat grayImg;
    cv::cvtColor(img_input, grayImg, cv::COLOR_BGR2GRAY);

    // 双边滤波
    cv::Mat bilateralFilteredImg;
    cv::bilateralFilter(grayImg, bilateralFilteredImg, 9, 75, 75);

    // 自适应阈值
    cv::Mat adaptiveThresholdImg;
    cv::adaptiveThreshold(bilateralFilteredImg, adaptiveThresholdImg, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 9, 5);

    cv::Mat temp;
    cv::cvtColor(adaptiveThresholdImg, temp, cv::COLOR_GRAY2RGB);

    // 直接将处理后的图像转换为 QPixmap 并显示在 label_image2 中
    QPixmap pixmap = QPixmap::fromImage(QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888));

    if (pixmap.isNull()) {
        QMessageBox::information(this, "提示", "转换为漫画后的文件打开失败!");
        return;
    }

    // 获取 label_image2 的尺寸
    int labelWidth2 = ui->label_image2->width();
    int labelHeight2 = ui->label_image2->height();

    // 将 QPixmap 进行缩放
    QPixmap scaledPixmap = pixmap.scaled(labelWidth2, labelHeight2, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    // 将缩放后的图像设置到 label_image2 中
    ui->label_image2->setPixmap(scaledPixmap);
    ui->label_image2->setScaledContents(false);
    ui->label_image2->setAlignment(Qt::AlignCenter);
}

void MainWindow::on_toDmButton_clicked()
{
    if (img_input.empty())
    {
        QMessageBox::information(this, "提示", "尚未加载图片,无法进行平滑操作!");
        return;
    }

    cv::Mat smoothedImg;
    cv::GaussianBlur(img_input, smoothedImg, cv::Size(5, 5), 0);  // 使用高斯模糊进行平滑

    cv::Mat temp;
    cv::cvtColor(smoothedImg, temp, cv::COLOR_BGR2RGB);

    // 直接将平滑后的图像转换为 QPixmap 并显示在 label_image2 中
    QPixmap pixmap = QPixmap::fromImage(QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888));

    if (pixmap.isNull())
    {
        QMessageBox::information(this, "提示", "平滑后的文件打开失败!");
        return;
    }

    // 获取 label_image2 的尺寸
    int labelWidth2 = ui->label_image2->width();
    int labelHeight2 = ui->label_image2->height();

    // 将 QPixmap 进行缩放
    QPixmap scaledPixmap = pixmap.scaled(labelWidth2, labelHeight2, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    // 将缩放后的图像设置到 label_image2 中
    ui->label_image2->setPixmap(scaledPixmap);
    ui->label_image2->setScaledContents(false);
    ui->label_image2->setAlignment(Qt::AlignCenter);

}



void MainWindow::on_clearButton_clicked()
{
	ui->label_image->clear();
    ui->label_image2->clear();
    tempRH.release();
    img_input.release();
}

 

MyFirstQT.h

#pragma once

#include <QMainWindow>
#include <QPushButton>
#include <QLabel>
#include <opencv2/opencv.hpp>

namespace Ui {
class MainWindow;
class MyFirstQTClass;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_loadImageButton_clicked();
    void on_sharpenImageButton_clicked();
    void on_histogramImageButton_clicked();
    void on_SaveButton_clicked();
    void on_clearButton_clicked();
    void on_autoLevelsButton_clicked();
    void on_toDmButton_clicked();

    
	

private:
    Ui::MyFirstQTClass *ui;
    cv::Mat image;

};

 

标签:clicked,QT,temp,label,Opencv,ui,vs2022,image2,cv
From: https://www.cnblogs.com/kfcalf/p/18326157

相关文章

  • Qt自定义控件
    开发系统:ubuntu22.04IDE:clion构建工具:cmakeQt自定义控件之插件形式插件形式是指将自定义控件按照一定的规则,生成动态库,放到Qtdesigner插件加载目录/usr/lib/x86_64-linux-gnu/qt5/plugins/designer下,Qtdesigner启动时加载,自定义控件就像内置控件一样可以直接拖拽。下面......
  • qt 连接扫码枪,检查串口插拔
    boolMainWindow::nativeEvent(constQByteArray&eventType,void*message,long*result){Q_UNUSED(result);Q_UNUSED(eventType);MSG*pMsg=reinterpret_cast<MSG*>(message);if(pMsg->message==WM_KEYUP){ushort......
  • 巧用 QLineF 从 QTransform 提取角度
    我们在对QGraphicsItem进行变换时,QT提供了很多便捷的方法。但当我们想获取当前变换的角度时却有些困难,因为QTransform没有提供获取角度的方法。在文章Qt从QTransform逆向解出Translate/Scale/Rotate(平移/缩放/旋转)分析分析过,使用QTransform进行多种变换组合后,由于组合......
  • 【QT】QT 窗口(菜单栏、工具栏、状态栏、浮动窗口、对话框)
    Qt窗口是通过QMainWindow类来实现的。QMainWindow是一个为用户提供主窗口程序的类,继承自 QWidget类,并且提供了⼀个预定义的布局。QMainWindow包含一个菜单栏(MenuBar)、多个工具栏(ToolBars)、多个浮动窗口(铆接部件)(DockWidgets)、⼀个状态栏(StatusBar)和一个中心部件(Cent......
  • MFC制作MQTT(EMQX)客户端 - 开、关功能实现(附源码)
    前言全局说明MFC制作MQTT客户端(附源码)一、说明环境:Windows7旗舰版VisualStudio2013CMakeversion3.19.8paho.mqtt.cV1.3.13二、MFC功能代码:2.1引入h头文件#include"include\MQTTAsync.h"#include"include\MQTTClient.h"2.2添加连接服务器信息......
  • MFC制作MQTT(EMQX)客户端 - 约定、依赖文件放置(附源码)
    前言全局说明MFC制作MQTT客户端(附源码)一、说明环境:Windows7旗舰版VisualStudio2013CMakeversion3.19.8paho.mqtt.cV1.3.13二、说明、约定:说明:因为MFC调用paho.mqtt.c的API所以,要把编译出来的相关文件,放到MFC的工程中,方便调用约定:为了方便后续描......
  • C#版OpenCV:OpenCVSharp 最详细最全面教程(万字详细总结)
    文章目录1.OpenCVSharp简介2.图像基本操作3.图像颜色空间转换4.图像几何变换5.图像阈值处理6.平滑图像7.图像梯度8.图像边缘检测9.图像直方图10.图像轮廓检测11.图像特征匹配12.视频读取与显示13.图像形态学操作14.图像混合与透明度处理15.霍夫变换16.傅......
  • opencv - py_calib3d - py_calibration 相机校准
    文章目录CameraCalibration相机校准目标基础知识代码设置校准去失真1.使用**cv.undistort()**2.使用**remapping**重新投影误差CameraCalibration相机校准目标在本节中,我们将学习相机造成的失真类型如何找到相机的内在和外在属性如何根据这些属性消除图......
  • SpringBoot 结合官网对MQTT消息队列整合记录
    SpringBoot结合官网对MQTT消息队列整合首先是mavenPom的引入MqttClient<dependency><groupId>org.eclipse.paho</groupId><artifactId>org.eclipse.paho.client.mqttv3</artifactId><version>1.2.......
  • Qt/C++使用小记1【.exe程序拖拽文件使程序启动时,获取该文件路径】
    写一写小小的收获吧,因为踏足也有一定时间了,自己也平时有记录,但是总感觉文件转来转去很麻烦,有时甚至找不到,就放在网上,自己需要的时候也可以翻一翻~第一个小收获:众所周知,qt生成的默认的.exe也是支持拖拽文件到.exe图标上的时候打开程序的,但是程序内不会有任何表现,仅仅是启动程......