Qt OpenCV 旋转图片
展示效果:
代码很简单,copy可以直接使用

代码如下:
RotationWgt.h
#pragma once #include <QBoxLayout> #include <QLabel> #include <QSlider> #include <QWidget> class RotationWgt : public QWidget { Q_OBJECT public: RotationWgt(); ~RotationWgt(); void initUI(); QLabel *m_lblImg; QSlider *m_slider; public slots: void slot_valueChange(int value); };
RotationWgt.cpp
#include "RotationWgt.h" #include <QDebug> #include <QImage> #include <opencv2/core.hpp> #include <opencv2/opencv.hpp> cv::Mat mat; RotationWgt::RotationWgt() { setFixedSize(900, 800); initUI(); } RotationWgt::~RotationWgt() {} void RotationWgt::initUI() { QVBoxLayout *mainV = new QVBoxLayout(); mat = cv::imread("D:/opencv/code/source/aa.jpg"); QImage img(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_RGB888); m_lblImg = new QLabel(); m_lblImg->setPixmap(QPixmap::fromImage(img)); m_slider = new QSlider(); m_slider->setRange(0, 180); m_slider->setValue(0); m_slider->setOrientation(Qt::Horizontal); m_slider->setFixedWidth(400); connect(m_slider, &QSlider::valueChanged, this, &RotationWgt::slot_valueChange); mainV->addWidget(m_lblImg, 0, Qt::AlignHCenter); mainV->addStretch(); mainV->addWidget(m_slider, 0, Qt::AlignHCenter); mainV->addStretch(); setLayout(mainV); } void RotationWgt::slot_valueChange(int value) { // 定义旋转中心 cv::Point2f center(mat.cols / 2, mat.rows / 2); // 获取旋转矩阵 cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, value, 1); //旋转图像 cv::Mat rotatedImage; cv::warpAffine(mat, rotatedImage, rotationMatrix, mat.size()); QImage img(rotatedImage.data, rotatedImage.cols, rotatedImage.rows, rotatedImage.step, QImage::Format_RGB888); m_lblImg->setPixmap(QPixmap::fromImage(img)); }

浙公网安备 33010602011771号