从 QCustomplot官网 https://www.qcustomplot.com/index.php/download 下载支持文件。首页有些demo可以进行参考学习。
新建一个Qt工程,将下载得到的qcustomplot.h和qcustomplot.cpp文件加入到当前工程。pro文件中加上 printsupport
在ui界面中,添加一个Widget,将其提升为QCustomplot类型。
qt配置opencv,可见此篇文章 https://blog.csdn.net/bangtanhui/article/details/135583311
本次获取了一张图片的某一行的所有像素点灰度值,并以曲线的形式展现。
具体实现,见以下代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"#include <opencv2/imgcodecs.hpp>
#include <opencv2/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core/hal/interface.h>
#include <opencv2/features2d/hal/interface.h>
#include <opencv2/imgproc/hal/interface.h>
#include "qcustomplot.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);QString imgPath = "D:\\Qt\\File\\open_test\\background.PNG";
// cv::Mat imgMat = cv::imread(imgPath.toLatin1().data(), cv::IMREAD_GRAYSCALE);
// cv::cvtColor(imgMat, imgMat, cv::COLOR_BGR2RGB);
// QImage img((const unsigned char*)(imgMat.data), imgMat.cols, imgMat.rows, QImage::Format_RGB888);ui->wid_curve->xAxis->setLabel(tr("Pixel"));ui->wid_curve->yAxis->setLabel(tr("GrayVal"));// 设置坐标轴的结束箭头ui->wid_curve->xAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);ui->wid_curve->xAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);//设置背景色QLinearGradient plotGradient;plotGradient.setStart(0,0);//背景颜色起始点,从图左上角开始,y方向0~400之间为红色渐变,开始位置为红色plotGradient.setFinalStop(0,400);//y方向 >400 为绿色渐变,结束位置为绿色plotGradient.setColorAt(0,QColor(200,200,200));//黑色,透明度从 0 ~ 1,plotGradient.setColorAt(1,QColor(120,120,120));ui->wid_curve->setBackground(plotGradient);//添加图形ui->wid_curve->addGraph();ui->wid_curve->graph(0)->setPen(QPen(Qt::yellow)); // line color blue for first graphui->wid_curve->addGraph();//读取测试图片cv::Mat testMat;testMat = cv::imread(imgPath.toStdString(), CV_8UC1);if(testMat.empty()){return;}int rows = testMat.rows;int cols = testMat.cols;int maxGrayVal = 255;// 设置坐标轴的范围ui->wid_curve->xAxis->setRange(0,cols); // 下边ui->wid_curve->xAxis2->setRange(0,cols); // 上边ui->wid_curve->yAxis->setRange(0,maxGrayVal); // 左边ui->wid_curve->yAxis2->setRange(0,maxGrayVal); // 右边ui->wid_curve->xAxis2->setVisible(true);ui->wid_curve->xAxis2->setTickLabels(false);ui->wid_curve->yAxis2->setVisible(true);ui->wid_curve->yAxis2->setTickLabels(false);//获取200行的灰度值,更新x,y值QVector<double> x(cols),y(cols);for(int i=0; i<cols; i++){x[i] = i;//指定图片第200行的像素点int grayVal = (int)testMat.at<uchar>(200,i);y[i] = grayVal;}ui->wid_curve->graph(0)->setData(x,y);ui->wid_curve->graph(0)->rescaleAxes();ui->wid_curve->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);ui->wid_curve->replot();
}MainWindow::~MainWindow()
{delete ui;
}
效果如图: