DianLi/LandslidePredict/LandslidePredict.cpp
2023-03-13 16:17:55 +08:00

383 lines
11 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "LandslidePredict.h"
#include <qgsrasterlayer.h>
#include <qgsvectorlayer.h>
#include <qgsmapcanvas.h>
LandslidePredict::LandslidePredict()
{
//ui.setupUi(this);
}
QString LandslidePredict::PannelName()
{
return QString::fromLocal8Bit("華窐耀輸");
}
QString LandslidePredict::CategoryName()
{
return QString::fromLocal8Bit("華窐耀輸");
}
QString LandslidePredict::EnglishName()
{
return QString::fromLocal8Bit("LandslidePredict");
}
QString LandslidePredict::ChineseName()
{
return QString::fromLocal8Bit("賑亠妎梗");
}
QString LandslidePredict::Information()
{
return QString::fromLocal8Bit("賑亠妎梗");
}
QString LandslidePredict::IconPath()
{
return QString(":/LandslidePredict/resources/landslide.svg");
}
QWidget* LandslidePredict::CenterWidget()
{
QString gdal_path = qApp->applicationDirPath().toLocal8Bit() + "/share/gdal";
QString pro_lib_path = qApp->applicationDirPath().toLocal8Bit() + "/share/proj";
qputenv("GDAL_DATA", gdal_path.toLocal8Bit());
qputenv("PROJ_LIB", pro_lib_path.toLocal8Bit());
bool showWin = false;
if (myWidget == nullptr)
{
myWidget = new QDialog();
showWin = true;
qDebug() << "new QDialog()";
}
else
{
qDebug() << "already have myWidget";
//慾魂敦諳甜枑汔祫階脯
myWidget->activateWindow();
myWidget->raise();
return myWidget;
}
ui.setupUi(myWidget);
myWidget->setWindowTitle(QString::fromLocal8Bit("賑亠妎梗"));
myWidget->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);
myWidget->setWindowIcon(QIcon(":/LandslidePredict/resources/landslide.svg"));
myWidget->setAttribute(Qt::WA_QuitOnClose, false);
myWidget->setAttribute(Qt::WA_DeleteOnClose);
connect(myWidget, &QDialog::destroyed, this, [=]() {
qDebug() << "----Landslide Predict window close----";
QDir pluginsDir = QDir(qApp->applicationDirPath());
if (pluginsDir.cd("srsplugins\\SldModel"))
{
QString strConfigPath = pluginsDir.absoluteFilePath("sld_config.ini");
QFile f(strConfigPath);
if (f.exists())
{
WriteConfigPaths(strConfigPath);
f.close();
}
}
if (mWorkThread != nullptr)
{
mWorkThread->requestInterruption();//ワА盄最笢剿
mWorkThread->quit();
mWorkThread->wait();//覃蚚wait綴珂覃蚚finished陓瘍勤茼腔羞滲杅ㄛ硒俴俇傖綴婬厘狟軗
mWorkObject->on_cancel();
mWorkThread = nullptr;//mWorkThread, &QThread::finished, mWorkThread, &QObject::deleteLaterㄛ祥剒猁delete
mWorkObject = nullptr;//mWorkThread, &QThread::finished, mWorker, &QObject::deleteLater
}
myWidget->close();
myWidget = nullptr;
qDebug() << "--destroyed";
});
connect(ui.pbtInModel, &QPushButton::clicked, this, &LandslidePredict::chooseInModel);
connect(ui.pbtInDataset, &QPushButton::clicked, this, &LandslidePredict::chooseInDataset);
connect(ui.pbtPreResult, &QPushButton::clicked, this, &LandslidePredict::chooseResultPath);
connect(ui.pushButton_ok, &QPushButton::clicked, this, &LandslidePredict::readAndStart);
connect(ui.pushButton_cancel, &QPushButton::clicked, this, &LandslidePredict::pbCancel);
ui.pbtInModel->setFocus();
ui.progressBar->setTextVisible(true);
ui.progressBar->setRange(0, 100);
QFile qssFile(":/LandslidePredict/LandslidePredict.qss");
qssFile.open(QFile::ReadOnly); //眕硐黍源宒湖羲
if (qssFile.isOpen())
{
QString qss = QLatin1String(qssFile.readAll());
myWidget->setStyleSheet(qss);
qssFile.close();
}
else
qDebug() << "no qssFile";
QDir pluginsDir = QDir(qApp->applicationDirPath());
if (pluginsDir.cd("srsplugins\\SldModel"))
{
QString strConfigPath = pluginsDir.absoluteFilePath("sld_config.ini");
QFile f(strConfigPath);
if (f.exists())
{
ReadConfigHistoryPaths(strConfigPath);
f.close();
}
}
if (showWin)
myWidget->show();
return myWidget;
}
void LandslidePredict::startWorkThread()
{
if (mWorkObject != nullptr)
return;
mWorkThread = new QThread();
mWorkObject = new WorkObject();
mWorkObject->moveToThread(mWorkThread);
connect(mWorkThread, &QThread::finished, mWorkThread, &QObject::deleteLater);
connect(mWorkThread, &QThread::finished, mWorkObject, &QObject::deleteLater);
connect(mWorkObject, &WorkObject::progress, myWidget, [=](int value) {ui.progressBar->setValue(value); });
connect(mWorkObject, &WorkObject::preFinished, this, &LandslidePredict::finished);
connect(mWorkObject, &WorkObject::addShpDataToMap, this, &LandslidePredict::openResultData);
connect(this, &LandslidePredict::startTiffToShp, mWorkObject, &WorkObject::runFormatConvert);
connect(this, &LandslidePredict::start, mWorkObject, &WorkObject::runPredictWork);
mWorkThread->start();
}
void LandslidePredict::ReadConfigHistoryPaths(QString strPath)
{
QSettings configIni(strPath, QSettings::IniFormat);
//湖羲梓枙峈ㄩ[SldPredict] 腔郪
configIni.beginGroup("SldPredict");
ui.lineInDataset->setText(configIni.value("SrcDom").toString());
ui.linePreResult->setText(configIni.value("PredictResult").toString());
configIni.endGroup();//壽敕郪
}
void LandslidePredict::WriteConfigPaths(QString strPath)
{
QSettings configIni(strPath, QSettings::IniFormat);
configIni.setIniCodec("utf-8");
//湖羲梓枙峈ㄩ[SldPredict] 腔郪
configIni.beginGroup("SldPredict");
//載陔怀⻌DOM繚噤
QString temp = ui.lineInDataset->text();
if (temp != "")
configIni.setValue("SrcDom", temp);
//載陔怀堤賦彆繚噤
temp = ui.linePreResult->text();
if (temp != "")
configIni.setValue("PredictResult", temp);
configIni.endGroup();//壽敕郪
}
void LandslidePredict::openResultData(QStringList string_list)
{
if (string_list.isEmpty())
return;
QgsRasterLayer* rastLayer;
QgsVectorLayer* vecLayer;
for each (QString layerPath in string_list)
{
QFileInfo fileInfo(layerPath);
QString layerBaseName = fileInfo.baseName(); // 芞脯靡備
if ("tif" == fileInfo.suffix() || "tiff" == fileInfo.suffix())
{
rastLayer = new QgsRasterLayer(fileInfo.filePath(), layerPath, "gdal");
if (!rastLayer)
return;
QgsMapLayer* mapLayer = rastLayer;
QgsRectangle myRectangle;
rastLayer->setContrastEnhancement(QgsContrastEnhancement::StretchToMinimumMaximum
, QgsRasterMinMaxOrigin::StdDev, myRectangle);
QList<QgsMapLayer*> mapLayers;
mapLayers << mapLayer;
QgsProject::instance()->addMapLayers(mapLayers);
//zoomToSelectedLayer(mapLayer);
}
else if ("shp" == fileInfo.suffix())
{
vecLayer = new QgsVectorLayer(fileInfo.filePath(), layerPath);
if (!vecLayer)
return;
QgsMapLayer* mapLayer = vecLayer;
QList<QgsMapLayer*> mapLayers;
mapLayers << mapLayer;
QgsProject::instance()->addMapLayers(mapLayers);
}
}
}
void LandslidePredict::readAndStart()
{
QString dirModel = ui.lineInModel->text();
QString dirDataset = ui.lineInDataset->text();
QString dirPRE = ui.linePreResult->text();
ui.progressBar->setValue(0);
if (dirModel == "" || dirDataset == "" || dirPRE == "")
{
QMessageBox mess(QMessageBox::NoIcon, QString::fromLocal8Bit("渣昫"), QString::fromLocal8Bit("ワ潰脤怀⻌怀堤恅璃麼繚噤"));
mess.setWindowFlags(Qt::Drawer);
int result = mess.exec();
return;
}
if (mWorkThread == nullptr)
{
qDebug() << "--startThread";
startWorkThread();
}
ui.label_progress->setText(QString::fromLocal8Bit("啎聆輛僅:"));
emit start(dirModel, dirDataset, dirPRE);
}
void LandslidePredict::pbCancel()
{
qDebug() << "--pbtCancel";
delete myWidget;//覃お&QDialog::destroyed
}
void LandslidePredict::chooseInModel()
{
QString dirModel = QFileDialog::getOpenFileName(ui.pbtInModel, QString::fromLocal8Bit("恁寁耀倰恅璃"), "", "*.pth");
if (dirModel != "")
ui.lineInModel->setText(dirModel);
}
void LandslidePredict::chooseInDataset()
{
QString dirInDataset = QFileDialog::getExistingDirectory(ui.pbtInDataset, QString::fromLocal8Bit("恁寁怀⻌啎聆杅擂繚噤"), "");
if (dirInDataset != "")
ui.lineInDataset->setText(dirInDataset);
}
void LandslidePredict::chooseResultPath()
{
QString dirPre = QFileDialog::getExistingDirectory(ui.pbtPreResult, QString::fromLocal8Bit("恁寁啎聆賦彆怀堤恅璃繚噤"), "");
if (dirPre != "")
ui.linePreResult->setText(dirPre);
}
//啎聆賦旰ㄛ蛌妐講
void LandslidePredict::finished()
{
QMessageBox mess(QMessageBox::NoIcon,
QString::fromLocal8Bit("賑亠妎梗賦旰"),
QString::fromLocal8Bit("蔚勤⺼狟繚噤笢賦彆輛俴蛌妐講揭燴:\n") + ui.linePreResult->text(),
QMessageBox::Ok, NULL);
mess.setWindowFlags(Qt::Drawer);
mess.setButtonText(QMessageBox::Ok, QString::fromLocal8Bit("<EFBFBD>"));
int result = mess.exec();
switch (result)
{
case QMessageBox::Ok:
emit startTiffToShp(ui.linePreResult->text(), ui.lineInDataset->text());
ui.label_progress->setText(QString::fromLocal8Bit("蛌妐講輛僅:"));
ui.progressBar->setValue(0);
break;
default:
break;
}
}
void WorkObject::runPredictWork(QString inModel, QString inDataset, QString outPre)
{
QDir pluginsDir = QDir(qApp->applicationDirPath());
if (!pluginsDir.cd("models\\envs"))
{
qDebug() << "no folder models\\envs";
return;
}
QString exeDirName = pluginsDir.absoluteFilePath("predict_3c_landslide.exe");
QString strModel = " --model_path " + inModel;
QString strData = " --dom_path " + inDataset + "/";
QString strPre = " --pre_path " + outPre + "/";
QString ss = exeDirName + strModel + strData + strPre;
qDebug() << ss;
QProcess* pProces = new QProcess(this);
connect(pProces, SIGNAL(readyReadStandardOutput()), this, SLOT(on_read()));
pProces->start(ss);
}
void WorkObject::on_read()
{
mProcess = (QProcess*)sender();
QString output = QString::fromLocal8Bit(mProcess->readAllStandardOutput());
if (output.toFloat() > 0)
{
qDebug() << "exe out:" << output.toFloat();
emit progress(output.toFloat());
if (output.toFloat() == 100)
emit preFinished();
}
else
qDebug() << "Unresolved exe out:" << output;
}
void WorkObject::on_cancel()
{
if (mProcess == nullptr)
{
qDebug() << "--mProces null";
}
else
{
QString KillStr = "taskkill /f /im predict_3c_landslide.exe";
mProcess->startDetached(KillStr);
qDebug() << "--kill Proces";
}
}
void WorkObject::runFormatConvert(QString pre, QString dataset)
{
QDir dir(pre);
QStringList nameFilters;
nameFilters << "*.tif" << "*.tiff";
QStringList pre_tiff_files = dir.entryList(nameFilters, QDir::Files | QDir::Readable, QDir::Name);
int list_len = pre_tiff_files.size();
for (int i = 0; i < list_len; i++)
{
emit progress(float(i) / float(list_len) * 95);
qDebug() << "TiffToShp progress:" << float(i) / float(list_len) * 100;
QString file_path = pre + "\\" + pre_tiff_files[i];
QString dsm_path = dataset + "\\" + pre_tiff_files[i];
string path_preTiff = file_path.toStdString();
string pathPureName = path_preTiff.substr(0, path_preTiff.rfind("."));
string shp_path = pathPureName + ".shp";
//覃お掑跡蛌妐講
img2shp cc;
QtGDALProcessBar* gb = new QtGDALProcessBar();
bool returnval = cc.ImagePolygonize(path_preTiff.c_str(), shp_path.c_str(), "ESRI Shapefile", 1, gb, gb);
if (returnval == true)
{
QStringList list;
list << dsm_path << QString::fromStdString(shp_path);
emit addShpDataToMap(list);
}
else
qDebug() << "ImagePolygonize fail";
}
emit progress(100);
}