本文共 2814 字,大约阅读时间需要 9 分钟。
OpenCV?????????GUI?????????????????????????????GUI????????????????Qt?????OpenCV????????
?QtCreator???????QMainWindow?????????????QImageShowWidget?????????????QMainWindow?centralwidget??
#ifndef QIMAGESHOWWIDGET_H#define QIMAGESHOWWIDGET_H#include#include class QImageShowWidget : public QWidget{ Q_OBJECTpublic: explicit QImageShowWidget(QWidget *parent = nullptr); ~QImageShowWidget(); bool LoadImage(const char *imagePath);protected: void paintEvent(QPaintEvent *event); void Release(); private: uchar *winBuf; int winWidth; int winHeight; int winBandNum;};#endif // QIMAGESHOWWIDGET_H
#include "qimageshowwidget.h"#include#include #include #include using namespace cv;using namespace std;QImageShowWidget::QImageShowWidget(QWidget *parent) : QWidget(parent){ setAutoFillBackground(true); setBackgroundRole(QPalette::Base); winBuf = nullptr; winWidth = rect().width(); winHeight = rect().height(); winBandNum = 3;}QImageShowWidget::~QImageShowWidget(){ if (winBuf) { delete[] winBuf; winBuf = nullptr; }}bool QImageShowWidget::LoadImage(const char *imagePath){ Mat img = imread(imagePath); if (img.empty()) { fprintf(stderr, "Can not load image %s\n", imagePath); return false; } Release(); winWidth = rect().width(); winHeight = rect().height(); size_t winBufNum = (size_t)winWidth * winHeight * winBandNum; winBuf = new uchar[winBufNum]; memset(winBuf, 255, winBufNum * sizeof(uchar)); for (int ri = 0; ri < img.rows; ++ri) { for (int ci = 0; ci < img.cols; ++ci) { for (int bi = 0; bi < winBandNum; ++bi) { size_t m = (size_t)winWidth * winBandNum * ri + winBandNum * ci + bi; size_t n = (size_t)img.cols * winBandNum * ri + winBandNum * ci + bi; winBuf[m] = img.data[n]; } } } update(); return true;}void QImageShowWidget::paintEvent(QPaintEvent *event){ if (!winBuf) { return; } QImage::Format imgFormat = QImage::Format_RGB888; QPainter painter(this); QImage qImg(winBuf, winWidth, winHeight, winWidth * winBandNum, imgFormat); painter.drawPixmap(0, 0, QPixmap::fromImage(qImg));}void QImageShowWidget::Release(){ if (winBuf) { delete[] winBuf; winBuf = nullptr; }}
QImageShowWidget???QWidget?????????????????LoadImage??????????paintEvent?????????
??QPainter??QImage?????winBuf??????????OpenCV?Mat???winBuf????????????????????
???????????????????????????
转载地址:http://qawx.baihongyu.com/