写了个程序,可在途图片,并切换成灰度图及伪彩图显示,主要代码如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
initRGBTable();//初始化颜色表
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_2_clicked()//
{
double fMax=0.0;
double fMin=0.0;
findMaxMin(m_vData,fMax,fMin);
double fDifference = fMax - fMin;
QVector<quint8> vnData;
vnData.resize(m_vData.size());
if(fDifference != 0)
{
for(int i = 0;i<m_nHeight;i++)
{
for(int j = 0;j<m_nWidth;j++)
{
vnData[i*m_nWidth+j] = static_cast<int>((m_vData.value(i*m_nWidth+j)-fMin)*1.0f/fDifference*255);
}
}
}
QImage img((uchar*)(&vnData[0]),m_nWidth,m_nHeight,QImage::Format_Indexed8);
img.setColorTable(m_vecGrayTable);
ShowImg(img);
}
void MainWindow::findMaxMin(QVector<double> vData, double &fMax, double &fMin)
{
if(vData.size()>1)
{
fMax = vData.value(0);
fMin = fMax;
for(int i=1;i<vData.size();i++)
{
if(fMax<vData.value(i))
{
fMax = vData.value(i);
}
if(fMin>vData.value(i))
{
fMin = vData.value(i);
}
}
}
}
void MainWindow::ShowImg(QImage img)
{
QPixmap qPix = QPixmap::fromImage(img);
qPix.scaled(ui->label->size(), Qt::KeepAspectRatio);
ui->label->setPixmap(qPix);
}
void MainWindow::initRGBTable()
{
//核心代码,请下载源码查看
}
void MainWindow::on_pushButton_clicked()
{
double fMax=0.0;
double fMin=0.0;
findMaxMin(m_vData,fMax,fMin);
double fDifference = fMax - fMin;
QVector<quint8> vnData;
vnData.resize(m_vData.size());
if(fDifference != 0)
{
for(int i = 0;i<m_nHeight;i++)
{
for(int j = 0;j<m_nWidth;j++)
{
vnData[i*m_nWidth+j] = static_cast<int>((m_vData.value(i*m_nWidth+j)-fMin)*1.0f/fDifference*255);
}
}
}
QImage img((uchar*)(&vnData[0]),m_nWidth,m_nHeight,QImage::Format_Indexed8);
img.setColorTable(m_vecColorTable);
ShowImg(img);
}
void MainWindow::on_pushButton_3_clicked()//打开图片
{
QFileDialog *fileDlg = new QFileDialog(this);
fileDlg->setWindowTitle("Choose Pictures");
QStringList qstrFilters;
qstrFilters<<"Any files (*)";
fileDlg->setNameFilters(qstrFilters);//设置文件过滤器
fileDlg->setFileMode(QFileDialog::ExistingFiles);//设置能选择多个文件,如果是单个文件就写成QFileDialog::ExistingFile
if(fileDlg->exec() == QDialog::Accepted)
{
QStringList strPathList = fileDlg->selectedFiles();
if(strPathList.count()>0)
{
qImg.load(strPathList.first());
m_nWidth = qImg.width();
m_nHeight = qImg.height();
ShowImg(qImg);
qImg = qImg.convertToFormat(QImage::Format_Grayscale8,Qt::AutoColor);
m_vData.resize(m_nWidth*m_nHeight);
unsigned char *ImgDataPtr = qImg.bits();
for(int i = 0;i<m_nHeight;i++)
{
for(int j = 0;j<m_nWidth;j++)
{
m_vData[i*m_nWidth+j]=*ImgDataPtr;
ImgDataPtr++;
}
}
}
}
fileDlg->close();
delete fileDlg;
fileDlg = nullptr;
}
源码下载地址:https://download.csdn.net/download/weixin_43935474/88232145