49 Commits

Author SHA1 Message Date
392bc98ebf add,计划采集21,上海农科院3D植物表型:
1、实现3种深度计算算法;
2026-08-19 17:37:08 +08:00
0866b9cd56 add,计划采集20,上海农科院3D植物表型:
1、新增任务类型AutoFocus:执行自动调焦过程;
2026-08-18 14:36:41 +08:00
33e34aa125 add,计划采集19,上海农科院3D植物表型:
1、新增任务类型LiftingPlatform:基于深度相机探测的植被深度,调整升降台的高度;
2026-08-12 15:17:17 +08:00
abdb27b228 add,计划采集18,上海农科院3D植物表型:
1、任务类型ObtainingDepthInformation兼容功能:获取植被和升降台的平均深度信息并写入文件:3DPlantPhenotypeScenario\plant_depth_values.txt和3DPlantPhenotypeScenario\LiftingPlatform_depth_values.txt
2026-08-11 17:27:18 +08:00
64cdc7591d add,计划采集17,上海农科院3D植物表型:
添加任务类型:获取目标区域的平均深度信息
2026-08-07 16:37:13 +08:00
f00fc6fdea 输出相机连接时的报错,方便排查; 2026-07-31 17:29:08 +08:00
10beb03843 修复:
由于兼容贡嘎山采集导致的一轴模式的采集逻辑bug
2026-07-22 18:29:20 +08:00
64bc8a9d27 优化自动调焦马达控制和界面 2026-07-22 18:27:34 +08:00
6b63d28d2c add,山地所贡嘎山7:
优化
2026-07-22 10:31:12 +08:00
3feefe45c1 fix,自动调焦:
1、优化界面对2版自动调焦的兼容,优化界面排版;
2、修复没有关闭自动调焦时,关闭调焦窗口软件崩溃的问题;

add,山地所贡嘎山6:
优化
2026-07-17 14:48:20 +08:00
245fc7f4ef fix
自动调焦bug修复:自动调焦完成后,移动到最佳位置;
2026-07-16 16:09:23 +08:00
a49f416551 add,山地所贡嘎山5,初步实现:
1、监听tcp消息,收到位置后触发pica L和is11采集。
2、releases可编译;
2026-07-16 16:07:48 +08:00
39578dc9fe add,山地所贡嘎山4:
添加触发界面
2026-07-10 13:20:07 +08:00
e326dcb20c add:
山地所贡嘎山3:
2026-07-08 10:54:22 +08:00
7ded94c2a4 add:
山地所贡嘎山2:(1)右下角添加控制is11的界面(2)添加轮播看板显示is11的光谱;
2026-07-06 15:10:28 +08:00
cb5a74f576 add:
山地所贡嘎山,部分完成:(1)右下角添加控制is11的界面(2)添加is11(鉴知)控制库
2026-07-01 23:16:14 +08:00
4a31cc0f7f add,计划采集17:
1、2轴控制:采集完成后回到原点;
2、将拉伸放入单独线程,防止主界面卡顿;
3、美化定时采集窗口;
4、优化taskExecutor;
2026-06-30 09:52:52 +08:00
55609b7b3b add,计划采集16:
解决切换相机时的图片不切换问题
解决设置高光谱相机帧率和积分时间失效问题
拷贝航线路径文件到数据文件夹
单反弹窗报错:添加描述
图像控制添加2%拉伸
2026-06-18 10:13:50 +08:00
5372a7806c add,计划采集15:
优化定时采集:界面和模型
2026-06-18 10:09:38 +08:00
59abab3f5d add,计划采集14:
修改节点名
2026-06-17 11:24:24 +08:00
fc3853c3ca add,计划采集13:
优化逻辑
2026-06-16 15:31:06 +08:00
d9f1ed922b add,计划采集12:
在界面中显示任务和其子任务,并实时更新它们的状态;
2026-06-16 13:25:43 +08:00
8329c00165 add,计划采集11:
1、完善定时采集流程信息统计:时间;
2、添加状态:跳过;
2026-06-12 10:37:54 +08:00
f69edcf2c9 add,计划采集10:
解决偶发单反唤起失败问题;

任务文件要求:
1、高光谱必须在前面,没有顺序要求,因为在执行高光谱任务前会预热卤素灯,所有高光谱任务完成后才关闭卤素灯;
2、单反/深度必须在后面,没有顺序要求;
3、必须要有高光谱任务:单反存在唤醒程序和一定反应时间,所以必须依赖前一个任务进行唤醒;
 (1)当单反已经是唤醒状态时,重新上电(先下电后上电)后可马上重新唤醒单反:单反适配器剩余电量马上耗尽,所以才能马上重新唤醒单反;
 (2)当单反在上电的状态下,从唤醒状态自动进入休眠状态时,重新下电后需要等待2分15秒(135秒)后,再重新上电才能唤醒单反:等待135秒的目的是将适配器中电容的剩余电量耗尽;
2026-06-11 15:27:02 +08:00
509f4b0767 add,计划采集9:
基本计划采集功能:采集流程电源通断控制ok
2026-06-10 18:10:47 +08:00
4a62d9a007 add,计划采集8:
实现部分计划采集功能:电源通断控制
2026-06-09 11:08:02 +08:00
467bebe9dd add,计划采集7:
实现部分计划采集功能:定时任务可完整执行
2026-06-05 11:36:38 +08:00
41a1a938b9 add,计划采集6:
实现部分计划采集功能:定时任务可控制单反
2026-06-04 18:01:22 +08:00
3607913f13 add,计划采集5:
实现部分计划采集功能:
2026-06-04 16:41:51 +08:00
a8760652bd add,计划采集3:
实现部分计划采集功能
2026-06-03 15:04:03 +08:00
3521a7f225 add,计划采集2:
添加计划任务的数据结构,并实现读写数据结构
2026-06-02 18:00:01 +08:00
6111634eff add,计划采集1:
添加窗口
2026-06-02 14:38:56 +08:00
4d42314a84 修改:
分离TwoMotionCaptureCoordinator和ImagerOperationBase
2026-06-01 17:10:37 +08:00
6456232114 add,单反相机
1、分离功能:单反相机的实时视频流和拍照;
2、将视频流和拍照功能状态反馈到界面上,并做简单控制;
2026-05-28 13:51:15 +08:00
525b39851a 配置release 2026-05-28 10:49:15 +08:00
5f965f0d8e fix
兼容2种帧数显示逻辑:(1)采集时的实时帧数(2)打开影像时的帧数;
2026-05-28 09:27:25 +08:00
3568495aa9 add:
深度相机:改变数据保存路径;
2026-05-27 22:58:41 +08:00
410da482bc 采集过程中禁用图层树的选择功能 2026-05-27 22:37:54 +08:00
43acd5ba01 fix:
1、采集时,创建RasterImageLayer时,dataprovider延迟初始化;
2、采集时,不通过渲染器渲染;
2026-05-27 17:42:14 +08:00
5dc589aee0 add,单反相机2:
1、实现3s拍照;
2、设置照片保存路径;
3、轮播看板:显示单反实时视频流;
2026-05-27 16:03:16 +08:00
e8ae6aa3b9 add
单反相机:实现1s拍照,并将照片传回控制电脑
2026-05-26 14:54:50 +08:00
304a1aa28b add
添加场景:3D植物表型,只涉及了部分界面
2026-05-26 14:04:21 +08:00
b2ed6e9c73 add
1、修改渲染参数:拉伸最大值;
2、toc添加数据管理功能:同步渲染参数到右下角“图像控制”面板;
2026-05-25 13:48:31 +08:00
dcce0a6665 toc添加数据管理功能 2026-05-22 16:21:41 +08:00
eda0a01098 add
1、添加layerTree节点类型:image,然后修改LayerTreeLayer,继承LayerTreeGroup。
2026-05-11 11:13:21 +08:00
e43d60e264 add:
1、增加显微镜场景:添加显微镜3D模型;
2、设置界面添加确认按钮;

fix:
1、相机看板:(1)帧率*积分时间=999,防止nir崩溃(2)记录帧率和积分时间,下次打开软件后恢复;(3)只能拖动slider改变值,不能点击slider改变值;
2、加入判断,不能多次打开同一个影像;
3、图像控制看板:只能拖动slider改变值,不能点击slider改变值;
2026-04-16 16:43:28 +08:00
24d34f39be 添加单反相机控制看板 2026-04-14 16:57:11 +08:00
d326dabff7 add,深度相机:
1、采集惯导数据并写入文件;
2、轮播看板添加深度图像;
3、植物表型场景控制深度相机看板;

fix:
优化调焦时,图像像素的填充方式;
2026-04-14 13:14:55 +08:00
5009832b3a add
1、采集深度、彩色、rgb点云,并存储到文件;
2、界面操作逻辑控制,防止用户错误操作;
2026-04-09 16:29:12 +08:00
109 changed files with 13497 additions and 1128 deletions

2
.gitignore vendored
View File

@ -8,6 +8,8 @@ HPPA - 副本.ui
icon
ignore_*
resources
*.bkp
.qwen
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

View File

@ -12,6 +12,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vincecontrol", "vincecontro
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "IrisMultiMotorController", "IrisMultiMotorController\IrisMultiMotorController\IrisMultiMotorController.vcxproj", "{2E792AA6-1BCB-4CDA-BE01-4D455EC5C473}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "JinspSpectralmeterControl", "JinspSpectralmeterControl\JinspSpectralmeterControl.vcxproj", "{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@ -44,6 +46,14 @@ Global
{2E792AA6-1BCB-4CDA-BE01-4D455EC5C473}.Release|x64.Build.0 = Release|x64
{2E792AA6-1BCB-4CDA-BE01-4D455EC5C473}.Release|x86.ActiveCfg = Release|x64
{2E792AA6-1BCB-4CDA-BE01-4D455EC5C473}.Release|x86.Build.0 = Release|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Debug|x64.ActiveCfg = Debug|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Debug|x64.Build.0 = Debug|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Debug|x86.ActiveCfg = Debug|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Debug|x86.Build.0 = Debug|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Release|x64.ActiveCfg = Release|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Release|x64.Build.0 = Release|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Release|x86.ActiveCfg = Release|x64
{06B5BB62-F5F1-4F59-8F5B-CC50B6F168CB}.Release|x86.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -1,7 +1,16 @@
#include "AppSettings.h"
#include <QCoreApplication>
const QString AppSettings::kDefaultDataFolder = QStringLiteral("C:\\HPPA_image");
const QString AppSettings::kDefaultFileName = QStringLiteral("test_image");
const int AppSettings::kDefaultFrameRate = 20;
const int AppSettings::kDefaultIntegrationTime = 1;
const int AppSettings::kDefaultGain = 0;
const QString AppSettings::kDefaultSLRDataFolder = QString();
const QString AppSettings::kDefaultDepthCameraDataFolder = QString();
const double AppSettings::kDefaultScanSpeed = 1.0;
const double AppSettings::kDefaultReturnSpeed = 5.0;
const int AppSettings::kDefaultGonggaShanRecordPort = 666;
AppSettings::AppSettings()
: m_settings(QSettings::IniFormat, QSettings::UserScope,
@ -29,7 +38,113 @@ QString AppSettings::fileName() const
{
return m_settings.value("General/FileName", kDefaultFileName).toString();
}
void AppSettings::setFileName(const QString& path)
{
m_settings.setValue("General/FileName", path);
}
int AppSettings::frameRate() const
{
return m_settings.value("CameraParams/FrameRate", kDefaultFrameRate).toInt();
}
void AppSettings::setFrameRate(int value)
{
m_settings.setValue("CameraParams/FrameRate", value);
}
int AppSettings::integrationTime() const
{
return m_settings.value("CameraParams/IntegrationTime", kDefaultIntegrationTime).toInt();
}
void AppSettings::setIntegrationTime(int value)
{
m_settings.setValue("CameraParams/IntegrationTime", value);
}
int AppSettings::gain() const
{
return m_settings.value("CameraParams/Gain", kDefaultGain).toInt();
}
void AppSettings::setGain(int value)
{
m_settings.setValue("CameraParams/Gain", value);
}
QString AppSettings::slrDataFolder() const
{
QString path = m_settings.value("General/SLRDataFolder").toString();
if (path.isEmpty())
{
return QCoreApplication::applicationDirPath() + "/CapturedImages/";
}
return path;
}
void AppSettings::setSlrDataFolder(const QString& path)
{
m_settings.setValue("General/SLRDataFolder", path);
}
QString AppSettings::depthCameraDataFolder() const
{
QString path = m_settings.value("General/DepthCameraDataFolder").toString();
if (path.isEmpty())
{
return QCoreApplication::applicationDirPath() + "/CapturedDepthImages/";
}
return path;
}
void AppSettings::setDepthCameraDataFolder(const QString& path)
{
m_settings.setValue("General/DepthCameraDataFolder", path);
}
QString AppSettings::FiberImagerDataFolder() const
{
QString path = m_settings.value("General/FiberImagerDataFolder").toString();
if (path.isEmpty())
{
return QCoreApplication::applicationDirPath() + "/CapturedFiberImagerData/";
}
return path;
}
void AppSettings::setFiberImagerDataFolder(const QString& path)
{
m_settings.setValue("General/FiberImagerDataFolder", path);
}
double AppSettings::scanSpeed() const
{
return m_settings.value("OneMotorControl/ScanSpeed", kDefaultScanSpeed).toDouble();
}
void AppSettings::setScanSpeed(double value)
{
m_settings.setValue("OneMotorControl/ScanSpeed", value);
}
double AppSettings::returnSpeed() const
{
return m_settings.value("OneMotorControl/ReturnSpeed", kDefaultReturnSpeed).toDouble();
}
void AppSettings::setReturnSpeed(double value)
{
m_settings.setValue("OneMotorControl/ReturnSpeed", value);
}
int AppSettings::gonggaShanRecordPort() const
{
return m_settings.value("GonggaShanRecordCtl/Port", kDefaultGonggaShanRecordPort).toInt();
}
void AppSettings::setGonggaShanRecordPort(int value)
{
m_settings.setValue("GonggaShanRecordCtl/Port", value);
}

View File

@ -14,6 +14,41 @@ public:
QString fileName() const;
void setFileName(const QString& path);
// 帧率
int frameRate() const;
void setFrameRate(int value);
// 积分时间
int integrationTime() const;
void setIntegrationTime(int value);
// 增益
int gain() const;
void setGain(int value);
// 单反相机数据保存路径
QString slrDataFolder() const;
void setSlrDataFolder(const QString& path);
// 深度相机数据保存路径
QString depthCameraDataFolder() const;
void setDepthCameraDataFolder(const QString& path);
QString FiberImagerDataFolder() const;
void setFiberImagerDataFolder(const QString& path);
// 扫描速度
double scanSpeed() const;
void setScanSpeed(double value);
// 返回速度
double returnSpeed() const;
void setReturnSpeed(double value);
// 贡嘎山记录端口
int gonggaShanRecordPort() const;
void setGonggaShanRecordPort(int value);
// 在此处添加更多参数的 getter/setter ...
private:
@ -26,4 +61,12 @@ private:
// 默认值
static const QString kDefaultDataFolder;
static const QString kDefaultFileName;
static const int kDefaultFrameRate;
static const int kDefaultIntegrationTime;
static const int kDefaultGain;
static const QString kDefaultSLRDataFolder;
static const QString kDefaultDepthCameraDataFolder;
static const double kDefaultScanSpeed;
static const double kDefaultReturnSpeed;
static const int kDefaultGonggaShanRecordPort;
};

View File

@ -2,12 +2,11 @@
TwoMotionCaptureCoordinator::TwoMotionCaptureCoordinator(
IrisMultiMotorController* motorCtrl,
ImagerOperationBase* cameraCtrl,
QObject* parent)
: QObject(parent)
, m_motorCtrl(motorCtrl)
, m_cameraCtrl(cameraCtrl)
, m_isRunning(false)
, m_isValidCapturing(false)
{
//这些信号槽是按照逻辑顺序的
connect(this, SIGNAL(moveTo(int, double, double, int)),
@ -20,35 +19,6 @@ TwoMotionCaptureCoordinator::TwoMotionCaptureCoordinator(
this, &TwoMotionCaptureCoordinator::handlePositionReached);
//connect(m_motorCtrl, &IrisMultiMotorController::moveFailed,
// this, &TwoMotionCaptureCoordinator::handleError);
connect(this, &TwoMotionCaptureCoordinator::startRecordHSISignal,
m_cameraCtrl, &ImagerOperationBase::start_record);
connect(this, &TwoMotionCaptureCoordinator::stopRecordHSISignal,
m_cameraCtrl, &ImagerOperationBase::stop_record);
connect(m_cameraCtrl, &ImagerOperationBase::RecordFinishedSignal_WhenFrameNumberMeet,
this, &TwoMotionCaptureCoordinator::handleCaptureCompleteWhenFrameNumberMeet);
//connect(m_cameraCtrl, &ImagerOperationBase::RecordFinishedSignal_WhenFrameNumberNotMeet,
// this, &TwoMotionCaptureCoordinator::handleCaptureCompleteWhenFrameNumberNotMeet);
//connect(m_cameraCtrl, &ImagerOperationBase::captureFailed,
// this, &TwoMotionCaptureCoordinator::handleError);
}
TwoMotionCaptureCoordinator::TwoMotionCaptureCoordinator(
IrisMultiMotorController* motorCtrl,
QObject* parent)
: QObject(parent)
, m_motorCtrl(motorCtrl)
, m_isRunning(false)
{
connect(this, SIGNAL(moveTo(int, double, double, int)),
m_motorCtrl, SLOT(moveTo(int, double, double, int)));
connect(this, SIGNAL(moveTo(const std::vector<double>, const std::vector<double>, int)),
m_motorCtrl, SLOT(moveTo(const std::vector<double>, const std::vector<double>, int)));
connect(m_motorCtrl, &IrisMultiMotorController::motorStopSignal,
this, &TwoMotionCaptureCoordinator::handlePositionReached);
//connect(m_motorCtrl, &IrisMultiMotorController::moveFailed,
// this, &TwoMotionCaptureCoordinator::handleError);
}
TwoMotionCaptureCoordinator::~TwoMotionCaptureCoordinator()
@ -98,11 +68,7 @@ void TwoMotionCaptureCoordinator::stop()
savePathLinesToCsv();
emit finishRecordLineNumSignal(m_numCurrentPathLine);
//emit stopRecordHSISignal(m_numCurrentPathLine);
if (m_cameraCtrl != nullptr)
{
m_cameraCtrl->stop_record();
}
emit stopRecordHSISignal(m_numCurrentPathLine);
move2LocBeforeStart();
@ -121,6 +87,7 @@ void TwoMotionCaptureCoordinator::getLocBeforeStart()
QMetaObject::Connection conn = QObject::connect(m_motorCtrl, &IrisMultiMotorController::locationSignal,
[&](std::vector<double> pos) {
m_locBeforeStart = pos;
std::cout << "start pos: "<< pos[0] <<", " << pos[1] << std::endl;
received = true;
loop.quit();
});
@ -130,6 +97,11 @@ void TwoMotionCaptureCoordinator::getLocBeforeStart()
loop.exec();
std::vector<double> pos;
pos.push_back(0);
pos.push_back(0);
m_locBeforeStart = pos;
disconnect(conn);
}
@ -148,7 +120,7 @@ void TwoMotionCaptureCoordinator::move2LocBeforeStart()
speed.push_back(tmp.speedTargetYPosition);
emit moveTo(m_locBeforeStart, speed, 1000);
m_isRunning = false;
m_isValidCapturing = false;
m_isMoving2XMin = false;
m_isMoving2XMax = false;
@ -230,12 +202,12 @@ void TwoMotionCaptureCoordinator::handlePositionReached(int motorID, double pos)
//QMutexLocker locker(&m_dataMutex);
PathLine &tmp = m_pathLines[m_numCurrentPathLine];
if (motorID == 1)//y马达
{
if (m_isMoving2YTargeLoc)
{
PathLine& tmp = m_pathLines[m_numCurrentPathLine];
double threshold = getThre(tmp.targetYPosition, pos);
if (threshold > 5)
@ -265,6 +237,7 @@ void TwoMotionCaptureCoordinator::handlePositionReached(int motorID, double pos)
if (m_isMoving2YStartLoc)
{
m_isMoving2YStartLoc = false;
isBack2Origin();
return;
}
@ -273,6 +246,8 @@ void TwoMotionCaptureCoordinator::handlePositionReached(int motorID, double pos)
{
if (m_isMoving2XMin)
{
PathLine& tmp = m_pathLines[m_numCurrentPathLine];
double threshold = getThre(tmp.targetXMinPosition, pos);
if (threshold > 5)
@ -301,6 +276,8 @@ void TwoMotionCaptureCoordinator::handlePositionReached(int motorID, double pos)
if (m_isMoving2XMax)
{
PathLine& tmp = m_pathLines[m_numCurrentPathLine];
double threshold = getThre(tmp.targetXMaxPosition, pos);
if (threshold > 5 && !m_isImagerFrameNumberMeet)//马达没到准确位置 && 【非】光谱仪因帧数限制主动停止采集
@ -324,11 +301,7 @@ void TwoMotionCaptureCoordinator::handlePositionReached(int motorID, double pos)
//停止采集高光谱数据
emit finishRecordLineNumSignal(m_numCurrentPathLine);
//emit stopRecordHSISignal(m_numCurrentPathLine);
if (m_cameraCtrl!=nullptr)
{
m_cameraCtrl->stop_record();
}
emit stopRecordHSISignal(m_numCurrentPathLine);
m_isMoving2XMax = false;
m_isImagerFrameNumberMeet = false;
@ -341,6 +314,7 @@ void TwoMotionCaptureCoordinator::handlePositionReached(int motorID, double pos)
if (m_isMoving2XStartLoc)
{
m_isMoving2XStartLoc = false;
isBack2Origin();
return;
}
@ -380,9 +354,25 @@ void TwoMotionCaptureCoordinator::startRecordHsi()
emit moveTo(0, tmp.targetXMaxPosition, tmp.speedTargetXMaxPosition, 1000);
emit startRecordHSISignal(m_numCurrentPathLine);
emit startRecordLineNumSignal(m_numCurrentPathLine);
}
}
void TwoMotionCaptureCoordinator::isBack2Origin()
{
if (!m_isRunning) return;
//QMutexLocker locker(&m_dataMutex);
if (!m_isMoving2XStartLoc && !m_isMoving2YStartLoc)
{
m_isRunning = false;
emit back2OriginSignal();
}
}
void TwoMotionCaptureCoordinator::handleCaptureCompleteWhenFrameNumberMeet()
{
m_isImagerFrameNumberMeet = true;
@ -426,7 +416,8 @@ void TwoMotionCaptureCoordinator::processNextPathLine()
}
std::cout << "\nNew path line: " << m_numCurrentPathLine << std::endl;
emit startRecordLineNumSignal(m_numCurrentPathLine);
emit gotoRecordLineNumSignal(m_numCurrentPathLine);
m_isValidCapturing = true;
PathLine &tmp = m_pathLines[m_numCurrentPathLine];
tmp.timestamp1 = QDateTime::currentDateTime();
@ -476,7 +467,7 @@ OneMotionCaptureCoordinator::~OneMotionCaptureCoordinator()
this, &OneMotionCaptureCoordinator::handleMotorStoped);
}
void OneMotionCaptureCoordinator::startStepMotion(OneMotionCapturePathLine pathLine)
void OneMotionCaptureCoordinator::startStepMotion(OneMotionCapturePathLine pathLine)//这个函数为啥被调用了2次?
{
QMutexLocker locker(&m_dataMutex);
@ -508,11 +499,13 @@ void OneMotionCaptureCoordinator::stopStepMotion()
}
emit stopMotorSignal(0);
m_isHypercamStopRecord = true;
}
void OneMotionCaptureCoordinator::handleCaptureCompleteWhenFrameNumberMeet()
{
emit stopMotorSignal(0);
m_isHypercamStopRecord = true;
}
void OneMotionCaptureCoordinator::getLocBeforeStart()
@ -537,6 +530,10 @@ void OneMotionCaptureCoordinator::getLocBeforeStart()
loop.exec();
disconnect(conn);
std::vector<double> pos;
pos.push_back(0);
m_locBeforeStart = pos;
}
void OneMotionCaptureCoordinator::move2LocBeforeStart()
@ -572,25 +569,32 @@ bool OneMotionCaptureCoordinator::saveToCsv(const QString& filename)
void OneMotionCaptureCoordinator::handleMotorStoped(int motorID, double pos)
{
if (!m_isRunning) return;
QMutexLocker locker(&m_dataMutex);
// 记录位置信息
m_pathLine.stopPosition = pos;
m_pathLine.timestamp2 = QDateTime::currentDateTime();
//光谱仪停止采集,马达回到初始位置
emit stopRecordHSISignal();
if (m_cameraCtrl != nullptr)
if (m_isHypercamStopRecord == true)
{
m_cameraCtrl->stop_record();
}
move2LocBeforeStart();
m_isHypercamStopRecord = false;
// emit sequenceComplete last: the slot connected to it may delete this object,
// so no member access is allowed after this point.
emit sequenceComplete(0);
// 记录位置信息
m_pathLine.stopPosition = pos;
m_pathLine.timestamp2 = QDateTime::currentDateTime();
//光谱仪停止采集,马达回到初始位置
emit stopRecordHSISignal();
if (m_cameraCtrl != nullptr)
{
m_cameraCtrl->stop_record();
}
move2LocBeforeStart();
emit sequenceComplete_cam_stop_before_motorback(0);
}
else
{
// emit sequenceComplete last: the slot connected to it may delete this object,
// so no member access is allowed after this point.
emit sequenceComplete(0);
}
}
void OneMotionCaptureCoordinator::handleCaptureComplete(double index)
@ -720,3 +724,251 @@ void DarkAndWhiteCaptureCoordinator::handleCaptureComplete(double index)
{
QMutexLocker locker(&m_dataMutex);
}
TwoMotor1PosCoordinator::TwoMotor1PosCoordinator(
IrisMultiMotorController* motorCtrl,
QObject* parent)
: QObject(parent)
, m_motorCtrl(motorCtrl)
, m_isMoving2Target(false)
, m_isMoving2Origin(false)
, m_targetX(0)
, m_targetY(0)
, m_speedX(0)
, m_speedY(0)
, m_actualX(0)
, m_actualY(0)
, m_retryTimesX(0)
, m_retryTimesY(0)
, m_xReached(false)
, m_yReached(false)
{
//因为IrisMultiMotorController::moveTo有多个重载版本,所以使用信号槽连接时需要使用SIGNAL和SLOT宏来指定参数类型,避免编译器无法推断出正确的函数签名。
//connect(this, &TwoMotor1PosCoordinator::moveTo, m_motorCtrl, &IrisMultiMotorController::moveTo);//这行代码会报错,因为moveTo有多个重载版本,编译器无法推断出正确的函数签名。
connect(this, SIGNAL(moveTo(int, double, double, int)), m_motorCtrl, SLOT(moveTo(int, double, double, int)));
connect(this, SIGNAL(moveTo(const std::vector<double>, const std::vector<double>, int)), m_motorCtrl, SLOT(moveTo(const std::vector<double>, const std::vector<double>, int)));
connect(this, &TwoMotor1PosCoordinator::stopMotorSignal, m_motorCtrl, &IrisMultiMotorController::stop);
connect(m_motorCtrl, &IrisMultiMotorController::motorStopSignal, this, &TwoMotor1PosCoordinator::handlePositionReached);
}
TwoMotor1PosCoordinator::~TwoMotor1PosCoordinator()
{
}
void TwoMotor1PosCoordinator::moveToTarget(double xTarget, double yTarget, double xSpeed, double ySpeed)
{
m_isMoving2Target = true;
m_isMoving2Origin = false;
moveToTargetPrivate(xTarget, yTarget, xSpeed, ySpeed);
}
void TwoMotor1PosCoordinator::back2origin()
{
m_isMoving2Target = false;
m_isMoving2Origin = true;
moveToTargetPrivate(0, 0, m_speedX, m_speedY);
}
void TwoMotor1PosCoordinator::moveToTargetPrivate(double xTarget, double yTarget, double xSpeed, double ySpeed)
{
m_targetX = xTarget;
m_targetY = yTarget;
m_speedX = xSpeed;
m_speedY = ySpeed;
m_xReached = false;
m_yReached = false;
m_retryTimesX = 0;
m_retryTimesY = 0;
std::vector<double> loc = { m_targetX, m_targetY };
std::vector<double> speed = { m_speedX, m_speedY };
std::cout << "TwoMotor1PosCoordinator: moving to (" << m_targetX << ", " << m_targetY << ")" << std::endl;
emit moveTo(loc, speed, 1000);
}
void TwoMotor1PosCoordinator::handlePositionReached(int motorID, double pos)
{
if (!m_isMoving2Target && !m_isMoving2Origin)
{
return;
}
double errorRateThreshold = 5;
if (motorID == 0)
{
m_actualX = pos;
double errorRate = getErrorRate(m_targetX, m_actualX);
if (errorRate > errorRateThreshold && m_retryTimesX < m_retryLimit)
{
m_retryTimesX++;
std::cout << "X motor retry " << m_retryTimesX << ", target: " << m_targetX << ", actual: " << m_actualX << std::endl;
emit moveTo(0, m_targetX, m_speedX, 1000);
return;
}
m_retryTimesX = 0;
m_xReached = true;
std::cout << "X motor reached: " << m_actualX << std::endl;
}
else if (motorID == 1)
{
m_actualY = pos;
double errorRate = getErrorRate(m_targetY, m_actualY);
if (errorRate > errorRateThreshold && m_retryTimesY < m_retryLimit)
{
m_retryTimesY++;
std::cout << "Y motor retry " << m_retryTimesY << ", target: " << m_targetY << ", actual: " << m_actualY << std::endl;
emit moveTo(1, m_targetY, m_speedY, 1000);
return;
}
m_retryTimesY = 0;
m_yReached = true;
std::cout << "Y motor reached: " << m_actualY << std::endl;
}
if (checkArrival())
{
std::cout << "TwoMotor1PosCoordinator: Arrived at (" << m_actualX << ", " << m_actualY << ")" << std::endl;
if (m_isMoving2Origin)
{
m_isMoving2Origin = false;
emit back2OriginSignal();
}
if (m_isMoving2Target)
{
m_isMoving2Target = false;
emit ArrivalSignal(m_actualX, m_actualY);
}
}
}
double TwoMotor1PosCoordinator::getErrorRate(double targetLoc, double actualLoc)
{
double targetLocTmp;
if (targetLoc == 0)
{
targetLocTmp = 0.001;
}
else
{
targetLocTmp = targetLoc;
}
double errorRate = abs(targetLoc - actualLoc) / targetLocTmp * 100;
return errorRate;
}
bool TwoMotor1PosCoordinator::checkArrival()
{
return m_xReached && m_yReached;
}
//---------------------------------------------------------------------------------------------------------------------------------------------
OneMotionCoordinator::OneMotionCoordinator(IrisMultiMotorController* motorCtrl, QObject* parent)
: QObject(parent)
, m_motorCtrl(motorCtrl)
, m_targetPosition(0)
, m_speed(0)
, m_actualPosition(0)
, m_isMoving(false)
, m_retryTimes(0)
, m_reached(false)
{
connect(this, SIGNAL(moveTo(int, double, double, int)), m_motorCtrl, SLOT(moveTo(int, double, double, int)));
connect(m_motorCtrl, &IrisMultiMotorController::motorStopSignal, this, &OneMotionCoordinator::handlePositionReached);
}
OneMotionCoordinator::~OneMotionCoordinator()
{
}
void OneMotionCoordinator::moveToTarget(double position, double speed)
{
QMutexLocker locker(&m_dataMutex);
m_targetPosition = position;
m_speed = speed;
m_retryTimes = 0;
m_reached = false;
m_isMoving = true;
qDebug() << "OneMotionCoordinator: moving to" << position;
emit moveTo(0, position, speed, 1000);
}
void OneMotionCoordinator::handlePositionReached(int motorID, double position)
{
if (!m_isMoving || motorID != 0)
{
return;
}
QMutexLocker locker(&m_dataMutex);
m_actualPosition = position;
double errorRate = getErrorRate(m_targetPosition, m_actualPosition);
if (errorRate > 5 && m_retryTimes < m_retryLimit)
{
m_retryTimes++;
qDebug() << "OneMotionCoordinator: retry" << m_retryTimes << ", target:" << m_targetPosition << ", actual:" << m_actualPosition;
emit moveTo(0, m_targetPosition, m_speed, 1000);
return;
}
m_retryTimes = 0;
m_reached = true;
m_isMoving = false;
qDebug() << "OneMotionCoordinator: Arrived at" << m_actualPosition;
emit sequenceComplete(0);
emit ArrivalSignal(m_actualPosition);
}
double OneMotionCoordinator::getErrorRate(double targetLoc, double actualLoc)
{
double targetLocTmp;
if (targetLoc == 0)
{
targetLocTmp = 0.001;
}
else
{
targetLocTmp = targetLoc;
}
double errorRate = abs(targetLoc - actualLoc) / targetLocTmp * 100;
return errorRate;
}

View File

@ -38,9 +38,6 @@ class TwoMotionCaptureCoordinator : public QObject
{
Q_OBJECT
public:
TwoMotionCaptureCoordinator(IrisMultiMotorController* motorCtrl,
ImagerOperationBase* cameraCtrl,
QObject* parent = nullptr);
TwoMotionCaptureCoordinator(IrisMultiMotorController* motorCtrl,
QObject* parent = nullptr);
~TwoMotionCaptureCoordinator();
@ -49,6 +46,8 @@ public:
signals:
void sequenceComplete(int);//0:所有采集线正常运行完成,1:用户主动取消采集
void back2OriginSignal();
void gotoRecordLineNumSignal(int lineNum);
void startRecordLineNumSignal(int lineNum);
void finishRecordLineNumSignal(int lineNum);
@ -62,13 +61,15 @@ signals:
void recordState(bool state);
public slots:
void handleCaptureCompleteWhenFrameNumberMeet();
private slots:
void start(QVector<PathLine> pathLines);
void stop();
void getRecordState();
void handlePositionReached(int motorID, double pos);
void handleCaptureCompleteWhenFrameNumberMeet();
void handleError(const QString& error);
void move2LocBeforeStart();
@ -76,6 +77,7 @@ private slots:
private:
void processNextPathLine();
void startRecordHsi();
void isBack2Origin();
void getLocBeforeStart();
double getThre(double targetLoc, double actualLoc);
@ -88,6 +90,7 @@ private:
mutable QMutex m_dataMutex;
bool m_isRunning;
bool m_isValidCapturing;
bool m_isMoving2YTargeLoc;
bool m_isMoving2XMin;
bool m_isMoving2XMax;
@ -141,6 +144,7 @@ public slots:
void handleCaptureCompleteWhenFrameNumberMeet();
signals:
void sequenceComplete_cam_stop_before_motorback(int);
void sequenceComplete(int);
void errorOccurred(const QString& error);
void moveTo(int, double, double, int);
@ -162,6 +166,7 @@ private:
mutable QMutex m_dataMutex;
bool m_isRunning;
bool m_isHypercamStopRecord = false;
std::vector<double> m_locBeforeStart;
void getLocBeforeStart();
@ -208,3 +213,90 @@ private:
void getLocBeforeStart();
void move2LocBeforeStart();
};
class TwoMotor1PosCoordinator : public QObject
{
Q_OBJECT
public:
TwoMotor1PosCoordinator(IrisMultiMotorController* motorCtrl,
QObject* parent = nullptr);
~TwoMotor1PosCoordinator();
public slots:
void moveToTarget(double xTarget, double yTarget, double xSpeed, double ySpeed);
void back2origin();
signals:
void ArrivalSignal(double xPos, double yPos);
void back2OriginSignal();
void errorOccurred(const QString& error);
void moveTo(int, double, double, int);
void moveTo(const std::vector<double>, const std::vector<double>, int);
void stopMotorSignal(int axis);
private slots:
void handlePositionReached(int motorID, double pos);
private:
void moveToTargetPrivate(double xTarget, double yTarget, double xSpeed, double ySpeed);
double getErrorRate(double targetLoc, double actualLoc);
bool checkArrival();
void move2Origin();
IrisMultiMotorController* m_motorCtrl;
mutable QMutex m_dataMutex;
bool m_isMoving2Target;
bool m_isMoving2Origin;
double m_targetX;
double m_targetY;
double m_speedX;
double m_speedY;
double m_actualX;
double m_actualY;
int m_retryLimit = 3;
int m_retryTimesX;
int m_retryTimesY;
bool m_xReached;
bool m_yReached;
};
class OneMotionCoordinator : public QObject
{
Q_OBJECT
public:
OneMotionCoordinator(IrisMultiMotorController* motorCtrl, QObject* parent = nullptr);
~OneMotionCoordinator();
public slots:
void moveToTarget(double position, double speed);
signals:
void sequenceComplete(int status);
void ArrivalSignal(double position);
void moveTo(int, double, double, int);
private slots:
void handlePositionReached(int motorID, double position);
private:
bool checkArrival();
double getErrorRate(double targetLoc, double actualLoc);
IrisMultiMotorController* m_motorCtrl;
mutable QMutex m_dataMutex;
double m_targetPosition;
double m_speed;
double m_actualPosition;
bool m_isMoving;
int m_retryLimit = 3;
int m_retryTimes;
bool m_reached;
};

View File

@ -0,0 +1,14 @@
#include "CommunicationInterfaceBase.h"
using namespace MotorParams;
CommunicationInterfaceBase::CommunicationInterfaceBase(QObject* parent)
:QObject(parent)
{
}
CommunicationInterfaceBase::~CommunicationInterfaceBase()
{
}

View File

@ -0,0 +1,36 @@
#pragma once
#include <QObject>
#include <QString>
#include "motorParams.h"
namespace MotorParams {
struct TCPConnectionParams
{
QString serverIP;
int port;
};
class CommunicationInterfaceBase :public QObject
{
Q_OBJECT
public:
CommunicationInterfaceBase(QObject* parent = nullptr);
~CommunicationInterfaceBase();
virtual bool connect2Motor() = 0;
//virtual void disconnect() = 0;
//virtual bool isConnected() const = 0;
virtual int sendCommand(const QString command) = 0;
//virtual void sendCommandAsync(const QString& command) = 0;
virtual int recvData(QByteArray& dataRecv) = 0;
signals:
void dataReceived(const QByteArray& data);
void connected(); // <20><><EFBFBD>ܴ<EFBFBD><DCB4>ڻ<EFBFBD><DABB><EFBFBD>TCP<43><50><EFBFBD><EFBFBD><EFBFBD>ᷢ<EFBFBD><E1B7A2><EFBFBD><EFBFBD><EFBFBD>ź<EFBFBD>
void disconnected();
void errorOccurred(QString msg);
};
} // namespace MotorParams

View File

@ -0,0 +1,122 @@
#include "CommunicationViaTCP.h"
using namespace MotorParams;
CommunicationViaTCP::CommunicationViaTCP(MotorParams::TCPConnectionParams connectionParams, QObject* parent)
:MotorParams::CommunicationInterfaceBase(parent)
{
m_bConnected = false;
m_tcpServer = new QTcpServer(this);
connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
m_tcpServer->listen(QHostAddress::Any, connectionParams.port);
}
CommunicationViaTCP::~CommunicationViaTCP()
{
m_tcpServer->close();
delete m_tcpServer;
//这两行代码要报错,为啥呢?????????????????
//m_tcpSocket->disconnectFromHost();
//delete m_tcpSocket;
}
bool CommunicationViaTCP::connect2Motor()
{
return true;
}
void CommunicationViaTCP::onNewConnection()
{
m_bConnected = true;
m_tcpSocket = m_tcpServer->nextPendingConnection();
connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(onTcpSocketDisconnected()));
connect(m_tcpSocket, &QTcpSocket::readyRead, this, &CommunicationViaTCP::receiveData);
emit connected();
}
bool CommunicationViaTCP::isConnected() const
{
return m_bConnected;
}
//从拔掉客户端的电源(客户端m_tcpSocket断开连接)到这个函数被调用有延迟,所以这个函数调用也有延迟,导致拔掉电源后的一小段时间函数isConnected()还是返回true
void CommunicationViaTCP::onTcpSocketDisconnected()
{
int a = 1;
m_bConnected = false;
m_tcpSocket->deleteLater();
}
void CommunicationViaTCP::receiveData()
{
if (!isConnected())
{
qWarning() << "receiveData: No client connected";
return;
}
QByteArray data = m_tcpSocket->readAll();
if (data.isEmpty())
{
return;
}
bool ok;
int position = QString::fromUtf8(data).toInt(&ok);
if (ok)
{
qDebug() << "Received position:" << position;
emit positionReceived(position);
} else
{
qWarning() << "Failed to parse position data:" << data;
}
}
int CommunicationViaTCP::sendCommand(const QString cmd)
{
if (!isConnected()) {
QString error = "No client connected";
emit commandSendResult(-1, error);
qWarning() << error << "command:" << cmd;
return -1;
}
qint64 bytesWritten = m_tcpSocket->write(cmd.toUtf8().data());
m_tcpSocket->waitForBytesWritten(50);
return bytesWritten;
}
int CommunicationViaTCP::recvData(QByteArray& dataRecv)
{
if (!isConnected()) {
QString error = "No client connected";
return -1;
}
dataRecv.clear();
QByteArray temp;
temp = m_tcpSocket->readAll();
dataRecv.append(temp);
int counter = 0;
while (dataRecv.size() < 21)
{
counter++;
m_tcpSocket->waitForReadyRead(100);
temp = m_tcpSocket->readAll();
dataRecv.append(temp);
if (counter >= 5)
break;
}
//qDebug() << "Hex:" << dataRecv.toHex();
return dataRecv.size();
}

View File

@ -0,0 +1,47 @@
#pragma once
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
#include "CommunicationInterfaceBase.h"
namespace MotorParams {
class CommunicationViaTCP :
public CommunicationInterfaceBase
{
Q_OBJECT
public:
CommunicationViaTCP(TCPConnectionParams connectionParams, QObject* parent = nullptr);
~CommunicationViaTCP();
//继承基类
bool connect2Motor();
//void disconnect();
//bool isConnected() const;
int sendCommand(const QString cmd);
//void sendCommandAsync(const QString& command);
int recvData(QByteArray& dataRecv);
private:
QTcpServer* m_tcpServer;
QTcpSocket* m_tcpSocket;
int m_iCommunicationProtocol;
bool m_bConnected;
bool isConnected() const;
public Q_SLOTS:
void onNewConnection();
void receiveData();
void onTcpSocketDisconnected();
signals:
void commandSendResult(int bytesWritten, const QString& error = QString());
void positionReceived(int position);
};
}

View File

@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>416</width>
<height>219</height>
<width>857</width>
<height>477</height>
</rect>
</property>
<property name="sizePolicy">
@ -83,19 +83,6 @@ QPushButton:pressed
</property>
</spacer>
</item>
<item row="1" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>135</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="1">
@ -126,7 +113,20 @@ QPushButton:pressed
</item>
</layout>
</item>
<item row="1" column="2">
<item row="2" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>135</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="2">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
@ -139,7 +139,52 @@ QPushButton:pressed
</property>
</spacer>
</item>
<item row="2" column="1">
<item row="3" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="styleSheet">
<string notr="true">QLabel {
color: rgb(255, 255, 255);
}</string>
</property>
<property name="text">
<string>数据路径</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="dataFolderLineEdit">
<property name="styleSheet">
<string notr="true">QLineEdit {
background-color: #142D7F;
color: #e6eeff;
border: 1px solid #2f6bff;
border-radius: 6px;
padding: 4px 8px;
min-width: 70px;
min-height: 20px;
font-size: 13px;
}</string>
</property>
<property name="text">
<string>./CapturedImages</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="dataFolderBtn">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="4" column="1">
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>

View File

@ -1,24 +1,635 @@
#include "DepthCameraWindow.h"
#include "DepthCameraWindow.h"
DepthCameraWindow::DepthCameraWindow(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
m_DepthCameraThread = new QThread();
m_DepthCameraOperation = new DepthCameraOperation();
m_DepthCameraOperation->moveToThread(m_DepthCameraThread);
m_DepthCameraThread->start();
connect(ui.openDepthCamera_btn, &QPushButton::clicked, this, &DepthCameraWindow::openDepthCamera);
connect(ui.closeDepthCamera_btn, &QPushButton::clicked, this, &DepthCameraWindow::closeDepthCamera);
connect(this, &DepthCameraWindow::openDepthCameraSignal, m_DepthCameraOperation, &DepthCameraOperation::OpenDepthCamera);
connect(this, &DepthCameraWindow::OpenDepthCamera_getDepthValueSignal, m_DepthCameraOperation, &DepthCameraOperation::OpenDepthCamera_getDepthValue);
connect(m_DepthCameraOperation, &DepthCameraOperation::CamOpenedSignal, this, &DepthCameraWindow::onCamOpened);
connect(m_DepthCameraOperation, &DepthCameraOperation::CamClosedSignal, this, &DepthCameraWindow::onCamClosed);
connect(m_DepthCameraOperation, &DepthCameraOperation::PlotSignal, this, &DepthCameraWindow::PlotDepthImageSignal);
connect(m_DepthCameraOperation, &DepthCameraOperation::CamClosedSignal, this, &DepthCameraWindow::DepthCamClosedSignal);
connect(this->ui.dataFolderBtn, SIGNAL(clicked()), this, SLOT(onSelectDataFolder()));
// 初始化数据保存路径显示(从 AppSettings 恢复或使用默认)
ui.dataFolderLineEdit->setText(AppSettings::instance().depthCameraDataFolder());
}
DepthCameraWindow::~DepthCameraWindow()
{
m_DepthCameraThread->quit();
m_DepthCameraThread->wait();
delete m_DepthCameraOperation;
m_DepthCameraOperation = nullptr;
}
void DepthCameraWindow::onSelectDataFolder()
{
QString dir = QFileDialog::getExistingDirectory(this,
QString::fromLocal8Bit("选择数据保存路径"),
ui.dataFolderLineEdit->text());
setDataFolder(dir);
}
void DepthCameraWindow::setDataFolder(QString dir)
{
if (!dir.isEmpty())
{
ui.dataFolderLineEdit->setText(dir);
AppSettings::instance().setDepthCameraDataFolder(dir);
}
}
void DepthCameraWindow::setCaptureInterval(int captureIntervalSeconds)
{
m_DepthCameraOperation->setCaptureInterval(captureIntervalSeconds);
}
void DepthCameraWindow::openDepthCamera()
{
if (!m_DepthCameraOperation->getRecordStatus())
{
emit openDepthCameraSignal();
}
}
void DepthCameraWindow::OpenDepthCamera_getDepthValue()
{
if (!m_DepthCameraOperation->getRecordStatus())
{
emit OpenDepthCamera_getDepthValueSignal();
}
}
void DepthCameraWindow::onCamOpened()
{
ui.openDepthCamera_btn->setEnabled(false);
ui.closeDepthCamera_btn->setEnabled(true);
ui.openDepthCamera_btn->setText(QString::fromLocal8Bit("已打开"));
}
void DepthCameraWindow::closeDepthCamera()
{
m_DepthCameraOperation->CloseDepthCamera();
}
void DepthCameraWindow::onCamClosed()
{
ui.openDepthCamera_btn->setEnabled(true);
ui.closeDepthCamera_btn->setEnabled(false);
ui.openDepthCamera_btn->setText(QString::fromLocal8Bit("打 开"));
}
//-------------------------------------------------------------------------------------------------------------------------------
DepthCameraOperation::DepthCameraOperation()
{
m_pipe = nullptr;
m_func = nullptr;
record = false;
m_captureIntervalMilliseconds = 3000;
}
DepthCameraOperation::~DepthCameraOperation()
{
if (m_pipe)
{
m_pipe->stop();
delete m_pipe;
m_pipe = nullptr;
}
}
void DepthCameraOperation::setCaptureInterval(int captureIntervalSeconds)
{
m_captureIntervalMilliseconds = captureIntervalSeconds * 1000;
}
void DepthCameraOperation::OpenDepthCamera()
{
if (m_pipe)
{
return;
}
m_pipe = new ob::Pipeline();
std::shared_ptr<ob::Config> config = std::make_shared<ob::Config>();
// Get device from pipeline.
auto device = m_pipe->getDevice();
auto devInfo = device->getDeviceInfo();
auto pid = devInfo->getPid();
auto vid = devInfo->getVid();
//// Get sensorList from device.
//auto sensorList = device->getSensorList();
//for (uint32_t index = 0; index < sensorList->getCount(); index++) {
// // Query all supported infrared sensor type and enable the infrared stream.
// // For dual infrared device, enable the left and right infrared streams.
// // For single infrared device, enable the infrared stream.
// OBSensorType sensorType = sensorList->getSensorType(index);
// std::cout << "Supported Sensor type: " << sensorType << std::endl;
// // Enable the stream for the sensor type.
// config->enableStream(sensorType);
//}
config->enableVideoStream(OB_STREAM_DEPTH, 640, 480, 15, OB_FORMAT_Y16);
config->enableVideoStream(OB_STREAM_COLOR, 640, 480, 15, OB_FORMAT_YUYV);
config->enableAccelStream();
config->enableGyroStream();
config->setFrameAggregateOutputMode(OB_FRAME_AGGREGATE_OUTPUT_ALL_TYPE_FRAME_REQUIRE);
config->setAlignMode(ALIGN_D2C_HW_MODE);
m_pipe->enableFrameSync();
// Create a format converter filter.
auto formatConverter = std::make_shared<ob::FormatConvertFilter>();
m_pipe->start(config);
// Drop several frames
for (int i = 0; i < 15; ++i) {
auto lost = m_pipe->waitForFrameset(m_captureIntervalMilliseconds);
}
auto pointCloud = std::make_shared<ob::PointCloudFilter>();
int frameIndex = 0;
record = true;
QString fileNamePrefix = AppSettings::instance().depthCameraDataFolder() + QDir::separator() + "Gemini336L";
QString imuFilePath = fileNamePrefix + "_IMU.txt";
std::ofstream imuFile(imuFilePath.toStdString(), std::ios::out | std::ios::trunc);
while (record)
{
if(frameIndex==0)
{
emit CamOpenedSignal();
std::cout << "Start recording..." << std::endl;
}
auto frameSet = m_pipe->waitForFrameset(m_captureIntervalMilliseconds);
if (frameSet == nullptr)
{
std::cout << "No frames received in 100ms..." << std::endl;
continue;
}
std::cout << "DepthCamera frameIndex:"<< frameIndex << std::endl;
// 彩色和深度图像
auto depthFrame = frameSet->getFrame(OB_FRAME_DEPTH)->as<ob::DepthFrame>();
auto colorFrame = frameSet->getFrame(OB_FRAME_COLOR)->as<ob::ColorFrame>();
// Convert the color frame to RGB format.
if (colorFrame->format() != OB_FORMAT_RGB) {
if (colorFrame->format() == OB_FORMAT_MJPG) {
formatConverter->setFormatConvertType(FORMAT_MJPG_TO_RGB);
}
else if (colorFrame->format() == OB_FORMAT_UYVY) {
formatConverter->setFormatConvertType(FORMAT_UYVY_TO_RGB);
}
else if (colorFrame->format() == OB_FORMAT_YUYV) {
formatConverter->setFormatConvertType(FORMAT_YUYV_TO_RGB);
}
else {
std::cout << "Color format is not support!" << std::endl;
continue;
}
colorFrame = formatConverter->process(colorFrame)->as<ob::ColorFrame>();
}
// Processed the color frames to BGR format, use OpenCV to save to disk.
formatConverter->setFormatConvertType(FORMAT_RGB_TO_BGR);
colorFrame = formatConverter->process(colorFrame)->as<ob::ColorFrame>();
saveDepthFrame(depthFrame, frameIndex, fileNamePrefix.toStdString());
saveColorFrame(colorFrame, frameIndex, fileNamePrefix.toStdString());
cv::Mat colorMat(colorFrame->height(), colorFrame->width(), CV_8UC3, colorFrame->data());
cv::Mat rgbMat;
cv::cvtColor(colorMat, rgbMat, cv::COLOR_BGR2RGB);
m_colorImage = QImage(rgbMat.data, rgbMat.cols, rgbMat.rows, static_cast<int>(rgbMat.step), QImage::Format_RGB888).copy();
cv::Mat depthMat(depthFrame->height(), depthFrame->width(), CV_16UC1, depthFrame->data());
cv::Mat depthMat8U;
depthMat.convertTo(depthMat8U, CV_8UC1, 255.0 / 4096.0);
cv::Mat depthColorMap;
cv::applyColorMap(depthMat8U, depthColorMap, cv::COLORMAP_JET);
cv::Mat depthRgbMat;
cv::cvtColor(depthColorMap, depthRgbMat, cv::COLOR_BGR2RGB);
m_depthImage = QImage(depthRgbMat.data, depthRgbMat.cols, depthRgbMat.rows, static_cast<int>(depthRgbMat.step), QImage::Format_RGB888).copy();
//m_depthImage = QImage(depthMat.data, depthMat.cols, depthMat.rows, static_cast<int>(depthMat.step), QImage::Format_Grayscale16).copy();
emit PlotSignal();
//点云
pointCloud->setCreatePointFormat(OB_FORMAT_RGB_POINT);
std::shared_ptr<ob::Frame> frame = pointCloud->process(frameSet);
QString plyPath = fileNamePrefix + "_PointCloud_"+ QString::number(frameIndex) + ".ply";
ob::PointCloudHelper::savePointcloudToPly(plyPath.toStdString().c_str(), frame, false, false, 50);
//惯导数据
auto accelFrameRaw = frameSet->getFrame(OB_FRAME_ACCEL);
auto accelFrame = accelFrameRaw->as<ob::AccelFrame>();
auto accelIndex = accelFrame->getIndex();
auto accelTimeStampUs = accelFrame->getTimeStampUs();
auto accelTemperature = accelFrame->getTemperature();
auto accelType = accelFrame->getType();
//if (frameIndex % 50 == 0)
//{ // print information every 50 frames.
// auto accelValue = accelFrame->getValue();
// printImuValue(accelValue, accelIndex, accelTimeStampUs, accelTemperature, accelType, "m/s^2");
//}
//auto accelValue = accelFrame->getValue();
//printImuValue(accelValue, accelIndex, accelTimeStampUs, accelTemperature, accelType, "m/s^2");
auto gyroFrameRaw = frameSet->getFrame(OB_FRAME_GYRO);
auto gyroFrame = gyroFrameRaw->as<ob::GyroFrame>();
auto gyroIndex = gyroFrame->getIndex();
auto gyroTimeStampUs = gyroFrame->getTimeStampUs();
auto gyroTemperature = gyroFrame->getTemperature();
auto gyroType = gyroFrame->getType();
//if (frameIndex % 50 == 0) { // print information every 50 frames.
// auto gyroValue = gyroFrame->getValue();
// printImuValue(gyroValue, gyroIndex, gyroTimeStampUs, gyroTemperature, gyroType, "rad/s");
//}
//auto gyroValue = gyroFrame->getValue();
//printImuValue(gyroValue, gyroIndex, gyroTimeStampUs, gyroTemperature, gyroType, "rad/s");
saveImuData(imuFile, accelFrame, gyroFrame);
frameIndex++;
}
imuFile.close();
m_pipe->stop();
delete m_pipe;
m_pipe = nullptr;
}
void DepthCameraOperation::OpenDepthCamera_getDepthValue()
{
if (m_pipe)
{
return;
}
m_pipe = new ob::Pipeline();
std::shared_ptr<ob::Config> config = std::make_shared<ob::Config>();
// Get device from pipeline.
auto device = m_pipe->getDevice();
auto devInfo = device->getDeviceInfo();
auto pid = devInfo->getPid();
auto vid = devInfo->getVid();
config->enableVideoStream(OB_STREAM_DEPTH, 640, 480, 15, OB_FORMAT_Y16);
config->enableVideoStream(OB_STREAM_COLOR, 640, 480, 15, OB_FORMAT_YUYV);
config->setFrameAggregateOutputMode(OB_FRAME_AGGREGATE_OUTPUT_ALL_TYPE_FRAME_REQUIRE);
m_pipe->enableFrameSync();
// Create a format converter filter.
auto formatConverter = std::make_shared<ob::FormatConvertFilter>();
m_pipe->start(config);
// Drop several frames
for (int i = 0; i < 15; ++i) {
auto lost = m_pipe->waitForFrameset(m_captureIntervalMilliseconds);
}
auto pointCloud = std::make_shared<ob::PointCloudFilter>();
int frameIndex = 0;
record = true;
QString fileNamePrefix = AppSettings::instance().depthCameraDataFolder() + QDir::separator() + "Gemini336L";
// 增量平均所需的变量
cv::Mat avgRgbMat, avgDepthMat;
int avgFrameCount = 0;
for (size_t i = 0; i < m_averageNumberOfTimes; i++)
{
if(frameIndex==0)
{
emit CamOpenedSignal();
std::cout << "Start recording..." << std::endl;
}
auto frameSet = m_pipe->waitForFrameset(m_captureIntervalMilliseconds);
if (frameSet == nullptr)
{
std::cout << "No frames received in 100ms..." << std::endl;
continue;
}
std::cout << "DepthCamera frameIndex:"<< frameIndex << std::endl;
// 彩色和深度图像
auto depthFrame = frameSet->getFrame(OB_FRAME_DEPTH)->as<ob::DepthFrame>();
auto colorFrame = frameSet->getFrame(OB_FRAME_COLOR)->as<ob::ColorFrame>();
// Convert the color frame to RGB format.
if (colorFrame->format() != OB_FORMAT_RGB) {
if (colorFrame->format() == OB_FORMAT_MJPG) {
formatConverter->setFormatConvertType(FORMAT_MJPG_TO_RGB);
}
else if (colorFrame->format() == OB_FORMAT_UYVY) {
formatConverter->setFormatConvertType(FORMAT_UYVY_TO_RGB);
}
else if (colorFrame->format() == OB_FORMAT_YUYV) {
formatConverter->setFormatConvertType(FORMAT_YUYV_TO_RGB);
}
else {
std::cout << "Color format is not support!" << std::endl;
continue;
}
colorFrame = formatConverter->process(colorFrame)->as<ob::ColorFrame>();
}
// Processed the color frames to BGR format, use OpenCV to save to disk.
formatConverter->setFormatConvertType(FORMAT_RGB_TO_BGR);
colorFrame = formatConverter->process(colorFrame)->as<ob::ColorFrame>();
//用于测试:保存深度图像
//saveDepthFrame(depthFrame, frameIndex, fileNamePrefix.toStdString());
//saveColorFrame(colorFrame, frameIndex, fileNamePrefix.toStdString());
cv::Mat colorMat(colorFrame->height(), colorFrame->width(), CV_8UC3, colorFrame->data());
cv::Mat rgbMat;
cv::cvtColor(colorMat, rgbMat, cv::COLOR_BGR2RGB);
//m_colorImage = QImage(rgbMat.data, rgbMat.cols, rgbMat.rows, static_cast<int>(rgbMat.step), QImage::Format_RGB888).copy();
cv::Mat depthMat(depthFrame->height(), depthFrame->width(), CV_16UC1, depthFrame->data());
// 增量平均计算
if (avgFrameCount == 0)
{
avgRgbMat = cv::Mat::zeros(rgbMat.size(), CV_32FC3);
avgDepthMat = cv::Mat::zeros(depthMat.size(), CV_32F);
}
avgFrameCount++;
cv::Mat rgbFloat;
rgbMat.convertTo(rgbFloat, CV_32FC3);
avgRgbMat = avgRgbMat + (rgbFloat - avgRgbMat) / avgFrameCount;
cv::Mat depthMatTmp;
depthMat.convertTo(depthMatTmp, CV_32F);
avgDepthMat = avgDepthMat + (depthMatTmp - avgDepthMat) / avgFrameCount;
cv::Mat depthMat8U;
depthMat.convertTo(depthMat8U, CV_8UC1, 255.0 / 4096.0);
cv::Mat depthColorMap;
cv::applyColorMap(depthMat8U, depthColorMap, cv::COLORMAP_JET);
cv::Mat depthRgbMat;
cv::cvtColor(depthColorMap, depthRgbMat, cv::COLOR_BGR2RGB);
m_depthImage = QImage(depthRgbMat.data, depthRgbMat.cols, depthRgbMat.rows, static_cast<int>(depthRgbMat.step), QImage::Format_RGB888).copy();
//m_depthImage = QImage(depthMat.data, depthMat.cols, depthMat.rows, static_cast<int>(depthMat.step), QImage::Format_Grayscale16).copy();
emit PlotSignal();
frameIndex++;
}
m_pipe->stop();
// 对累积平均后的图像进行处理
double depthValue;
if (avgFrameCount > 0)
{
cv::Mat avgRgbResult, avgDepthResult;
avgRgbMat.convertTo(avgRgbResult, CV_8UC3);
avgDepthMat.convertTo(avgDepthResult, CV_16UC1);
// 保存平均结果图像
std::vector<int> pngParams;
pngParams.push_back(cv::IMWRITE_PNG_COMPRESSION);
pngParams.push_back(0);
pngParams.push_back(cv::IMWRITE_PNG_STRATEGY);
pngParams.push_back(cv::IMWRITE_PNG_STRATEGY_DEFAULT);
cv::imwrite(getTestFilePath("_AvgRGB_").toStdString(), avgRgbResult, pngParams);
cv::imwrite(getTestFilePath("_AvgDepth_").toStdString(), avgDepthResult, pngParams);
// 创建掩膜,排除深度值为0的区域
cv::Mat mask = avgDepthResult != 0;
// 保存掩膜
cv::Mat mask8U;
mask.convertTo(mask8U, CV_8UC1, 255.0);
std::string maskName = fileNamePrefix.toStdString() + "_Mask_" + std::to_string(mask.cols) + "x" + std::to_string(mask.rows) + ".png";
cv::imwrite(maskName, mask8U, pngParams);
if (m_depthAlgorithm == 0)
{
depthValue = processAveragedImages_roiAvg(avgDepthResult, mask);
}
else if (m_depthAlgorithm == 1)
{
depthValue = processAveragedImages_depthRangePercentage(avgDepthResult, mask);
}
else if (m_depthAlgorithm == 2)
{
depthValue = processAveragedImages_segmentation(avgRgbResult, avgDepthResult, mask);
}
}
//计算平均深度值
std::cout << "Depth value: " << depthValue << " m" << std::endl;
emit DepthValueSignal(depthValue);
delete m_pipe;
m_pipe = nullptr;
record = false;
}
double DepthCameraOperation::processAveragedImages_roiAvg(const cv::Mat& avgDepthResult, const cv::Mat& mask)
{
//裁剪边缘区域
int cropRows = static_cast<int>(avgDepthResult.rows * (1 - m_percentageOfEffectiveArea) / 2);
int cropCols = static_cast<int>(avgDepthResult.cols * (1 - m_percentageOfEffectiveArea) / 2);
cv::Rect roi(cropCols, cropRows,
avgDepthResult.cols - 2 * cropCols,
avgDepthResult.rows - 2 * cropRows);
cv::Mat depthRoi = avgDepthResult(roi);
cv::Mat maskRoi = mask(roi);
//计算平均深度值,使用掩膜排除深度值为0的区域
cv::Scalar meanDepth = cv::mean(depthRoi, maskRoi);
double depthValue = meanDepth[0] / 1000.0; // 转换为米
return depthValue;
}
double DepthCameraOperation::processAveragedImages_depthRangePercentage(const cv::Mat& avgDepthResult, const cv::Mat& mask)
{
// 找出最大最小值
double minVal, maxVal;
cv::minMaxLoc(avgDepthResult, &minVal, &maxVal, nullptr, nullptr, mask);
// 检查是否有有效数据
if (minVal == std::numeric_limits<double>::max())
{
std::cout << "Warning: No valid depth pixels found in masked region!" << std::endl;
return 0.0;
}
// 返回最小值乘以m_depthRangePercentage
double depthValue = minVal * m_depthRangePercentage / 1000.0; // 转换为米
return depthValue;
}
double DepthCameraOperation::processAveragedImages_segmentation(const cv::Mat& avgRgbResult, const cv::Mat& avgDepthResult, const cv::Mat& mask)
{
// 转换到 HSV 颜色空间进行植被分割
cv::Mat hsvMat;
cv::cvtColor(avgRgbResult, hsvMat, cv::COLOR_RGB2HSV);
// 分离通道
std::vector<cv::Mat> hsvChannels;
cv::split(hsvMat, hsvChannels);
cv::Mat hue = hsvChannels[0];
cv::Mat sat = hsvChannels[1];
cv::Mat val = hsvChannels[2];
// 定义绿色植被的Hue范围 (OpenCV中Hue范围是0-180,实际绿色约35-90度)
// 扩展范围以覆盖不同光照条件下的绿色
cv::Mat hueMask1 = (hue >= 35) & (hue <= 85);
cv::Mat satMask = sat > 30; // 饱和度阈值,去除灰色区域
cv::Mat valMask = val > 50; // 亮度阈值,去除过暗区域
// 组合条件生成植被掩膜
cv::Mat vmask;
cv::bitwise_and(hueMask1, satMask, vmask);
cv::bitwise_and(vmask, valMask, vmask);
// 结合深度掩膜,计算两个mask的交集
cv::Mat combinedMask;
cv::bitwise_and(mask, vmask, combinedMask);
// 保存 vmask 和 combinedMask 到 exe 所在文件夹的文件夹
cv::Mat vmask8U, combinedMask8U;
vmask.convertTo(vmask8U, CV_8UC1, 255.0);
combinedMask.convertTo(combinedMask8U, CV_8UC1, 255.0);
cv::imwrite(getTestFilePath("vmask").toStdString(), vmask8U);
cv::imwrite(getTestFilePath("combinedMask").toStdString(), combinedMask8U);
// 计算 avgRgbResult 在 combinedMask 区域内的平均深度值
double depthValue = 0.0;
if (cv::countNonZero(combinedMask) > 0) {
cv::Scalar meanDepth = cv::mean(avgDepthResult, combinedMask);
depthValue = meanDepth[0] / 1000.0; // 转换为米
} else {
std::cout << "Warning: No valid pixels in combined mask!" << std::endl;
}
return depthValue;
}
QString DepthCameraOperation::getTestFilePath(const QString& fileName)
{
QString testFolder = QCoreApplication::applicationDirPath() + QDir::separator() + "depthValueTest";
QDir().mkpath(testFolder);
QString timestamp = QString::number(QDateTime::currentMSecsSinceEpoch());
return testFolder + QDir::separator() + fileName + "_" + timestamp + ".png";
}
void DepthCameraOperation::saveDepthFrame(const std::shared_ptr<ob::DepthFrame> depthFrame, const uint32_t frameIndex, std::string fileNamePrefix_)
{
std::vector<int> params;
params.push_back(cv::IMWRITE_PNG_COMPRESSION);
params.push_back(0);
params.push_back(cv::IMWRITE_PNG_STRATEGY);
params.push_back(cv::IMWRITE_PNG_STRATEGY_DEFAULT);
std::string depthName = fileNamePrefix_ + "_Depth_" + std::to_string(depthFrame->width()) + "x" + std::to_string(depthFrame->height()) + "_" + std::to_string(frameIndex) + "_"
+ std::to_string(depthFrame->timeStamp()) + "ms.png";
cv::Mat depthMat(depthFrame->height(), depthFrame->width(), CV_16UC1, depthFrame->data());
cv::imwrite(depthName, depthMat, params);
//std::cout << "Depth saved:" << depthName << std::endl;
}
void DepthCameraOperation::saveColorFrame(const std::shared_ptr<ob::ColorFrame> colorFrame, const uint32_t frameIndex, std::string fileNamePrefix_)
{
std::vector<int> params;
params.push_back(cv::IMWRITE_PNG_COMPRESSION);
params.push_back(0);
params.push_back(cv::IMWRITE_PNG_STRATEGY);
params.push_back(cv::IMWRITE_PNG_STRATEGY_DEFAULT);
std::string colorName = fileNamePrefix_ + "_Color_" + std::to_string(colorFrame->width()) + "x" + std::to_string(colorFrame->height()) + "_" + std::to_string(frameIndex) + "_"
+ std::to_string(colorFrame->timeStamp()) + "ms.png";
cv::Mat depthMat(colorFrame->height(), colorFrame->width(), CV_8UC3, colorFrame->data());
cv::imwrite(colorName, depthMat, params);
//std::cout << "Color saved:" << colorName << std::endl;
}
void DepthCameraOperation::printImuValue(OBFloat3D obFloat3d, uint64_t index, uint64_t timeStampUs, float temperature, OBFrameType type, const std::string& unitStr)
{
std::cout << "frame index: " << index << std::endl;
auto typeStr = ob::TypeHelper::convertOBFrameTypeToString(type);
std::cout << typeStr << " Frame: \n\r{\n\r"
<< " tsp = " << timeStampUs << "\n\r"
<< " temperature = " << temperature << "\n\r"
<< " " << typeStr << ".x = " << obFloat3d.x << unitStr << "\n\r"
<< " " << typeStr << ".y = " << obFloat3d.y << unitStr << "\n\r"
<< " " << typeStr << ".z = " << obFloat3d.z << unitStr << "\n\r"
<< "}\n\r" << std::endl;
}
void DepthCameraOperation::saveImuData(std::ofstream& imuFile, const std::shared_ptr<ob::AccelFrame>& accelFrame, const std::shared_ptr<ob::GyroFrame>& gyroFrame)
{
if (!imuFile.is_open())
return;
auto accelValue = accelFrame->getValue();
auto gyroValue = gyroFrame->getValue();
// position (acceleration): ax, ay, az
// attitude (angular velocity): gx, gy, gz
imuFile << accelFrame->getIndex() << ","
<< accelFrame->getTimeStampUs() << ","
<< accelValue.x << "," << accelValue.y << "," << accelValue.z << ","
<< gyroFrame->getIndex() << ","
<< gyroFrame->getTimeStampUs() << ","
<< gyroValue.x << "," << gyroValue.y << "," << gyroValue.z << "\n";
}
void DepthCameraOperation::OpenDepthCamera_callback()
{
}
void DepthCameraOperation::setCallback(void(*func)())
{
m_func = func;
}
void DepthCameraOperation::CloseDepthCamera()
{
std::cout << "DepthCameraOperation::CloseDepthCamera,关闭深度相机" << std::endl;
record = false;
emit CamClosedSignal();
}

View File

@ -1,11 +1,86 @@
#pragma once
#pragma once
#include <QDialog>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QImage>
#include <QThread>
#include <QDir>
#include <QCoreApplication>
#include <QDateTime>
//#include <QLabel>
#include <QFileDialog>
#include <iostream>
#include "ui_DepthCamera.h"
#include "AppSettings.h"
#include <fstream>
#include <opencv2/opencv.hpp>
#include <libobsensor/ObSensor.hpp>
#include "libobsensor/hpp/Utils.hpp"
typedef void(*func)();
class DepthCameraOperation :public QObject
{
Q_OBJECT
public:
DepthCameraOperation();
~DepthCameraOperation();
QImage m_colorImage;
QImage m_depthImage;
void setCallback(void(*func)());
bool getRecordStatus() const { return record; }
void setCaptureInterval(int captureIntervalSeconds);
void setDepthAlgorithm(int depthAlgorithm) { m_depthAlgorithm = depthAlgorithm; }
void setAverageNumberOfTimes(double averageNumberOfTimes) { m_averageNumberOfTimes = averageNumberOfTimes; }
void setPercentageOfEffectiveArea(double percentageOfEffectiveArea) { m_percentageOfEffectiveArea = percentageOfEffectiveArea; }
void setDepthRangePercentage(double depthRangePercentage) { m_depthRangePercentage = depthRangePercentage; }
private:
ob::Pipeline* m_pipe;
cv::Mat frame;
func m_func;
void saveDepthFrame(const std::shared_ptr<ob::DepthFrame> depthFrame, const uint32_t frameIndex, std::string fileNamePrefix_);
void saveColorFrame(const std::shared_ptr<ob::ColorFrame> colorFrame, const uint32_t frameIndex, std::string fileNamePrefix_);
void printImuValue(OBFloat3D obFloat3d, uint64_t index, uint64_t timeStampUs, float temperature, OBFrameType type, const std::string& unitStr);
void saveImuData(std::ofstream& imuFile, const std::shared_ptr<ob::AccelFrame>& accelFrame, const std::shared_ptr<ob::GyroFrame>& gyroFrame);
bool record;
int m_captureIntervalMilliseconds;
int m_depthAlgorithm;
double m_averageNumberOfTimes;
double m_percentageOfEffectiveArea;
double m_depthRangePercentage;
double processAveragedImages_roiAvg(const cv::Mat& avgDepthResult, const cv::Mat& mask);
double processAveragedImages_depthRangePercentage(const cv::Mat& avgDepthResult, const cv::Mat& mask);
double processAveragedImages_segmentation(const cv::Mat& avgRgbResult, const cv::Mat& avgDepthResult, const cv::Mat& mask);
QString getTestFilePath(const QString& fileName);
public slots:
void OpenDepthCamera();
void OpenDepthCamera_getDepthValue();
void OpenDepthCamera_callback();//不使用信号而使用回调函数来通知界面刷新视频
void CloseDepthCamera();
signals:
void PlotSignal();
void DepthValueSignal(double depthValue);
void CamOpenedSignal();
void CamClosedSignal();
};
class DepthCameraWindow : public QDialog
{
@ -15,13 +90,27 @@ public:
DepthCameraWindow(QWidget* parent = nullptr);
~DepthCameraWindow();
DepthCameraOperation* m_DepthCameraOperation;
void setDataFolder(QString dir);
void setCaptureInterval(int captureIntervalSeconds);
public Q_SLOTS:
void PlotRgbImageSignal();
void CamClosedSignal();
void openDepthCamera();
void OpenDepthCamera_getDepthValue();
void onCamOpened();
void closeDepthCamera();
void onCamClosed();
void onSelectDataFolder();
signals:
void openDepthCameraSignal();
void OpenDepthCamera_getDepthValueSignal();
void PlotDepthImageSignal();
void DepthCamClosedSignal();
private:
Ui::DepthCameraClass ui;
QThread* m_DepthCameraThread;
};

138
HPPA/DepthValueLogger.cpp Normal file
View File

@ -0,0 +1,138 @@
#include "stdafx.h"
#include "DepthValueLogger.h"
#include "AppSettings.h"
#include "fileOperation.h"
#include <QDir>
DepthValueLogger& DepthValueLogger::instance()
{
static DepthValueLogger instance;
return instance;
}
DepthValueLogger::DepthValueLogger()
{
}
DepthValueLogger::~DepthValueLogger()
{
}
QString DepthValueLogger::getLogFilePath(DepthValueType type) const
{
FileOperation* fileOperation = new FileOperation();
QString directory = QString::fromStdString(fileOperation->getDirectoryOfExe());
QString basePath = directory + QDir::separator() + "3DPlantPhenotypeScenario";
switch (type)
{
case DepthValueType::Plant:
return basePath + QDir::separator() + "plant_depth_values.txt";
case DepthValueType::LiftingPlatform:
return basePath + QDir::separator() + "LiftingPlatform_depth_values.txt";
default:
return basePath + QDir::separator() + "plant_depth_values.txt";
}
}
void DepthValueLogger::appendDepthValue(double depthValue, DepthValueType type)
{
QString filePath = getLogFilePath(type);
QFileInfo fileInfo(filePath);
QDir dir = fileInfo.absoluteDir();
if (!dir.exists())
{
dir.mkpath(".");
}
QFile file(filePath);
if (file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
QTextStream out(&file);
QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz");
out << timestamp << "\t" << QString::number(depthValue, 'f', 6) << "\n";
file.close();
emit depthValueLogged(depthValue, type);
}
}
double DepthValueLogger::readLatestDepthValue(DepthValueType type) const
{
QString filePath = getLogFilePath(type);
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return 0.0;
}
double latestValue = 0.0;
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine().trimmed();
if (line.isEmpty())
{
continue;
}
QStringList parts = line.split("\t");
if (parts.size() >= 2)
{
latestValue = parts.last().toDouble();
}
}
file.close();
return latestValue;
}
bool DepthValueLogger::hasValidDepthValue(DepthValueType type) const
{
QString filePath = getLogFilePath(type);
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return false;
}
bool hasValue = false;
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine().trimmed();
if (!line.isEmpty())
{
hasValue = true;
break;
}
}
file.close();
return hasValue;
}
void DepthValueLogger::appendPlantDepthValue(double depthValue)
{
appendDepthValue(depthValue, DepthValueType::Plant);
}
void DepthValueLogger::appendLiftingPlatformDepthValue(double depthValue)
{
appendDepthValue(depthValue, DepthValueType::LiftingPlatform);
}
double DepthValueLogger::readLatestPlantDepthValue() const
{
return readLatestDepthValue(DepthValueType::Plant);
}
double DepthValueLogger::readLatestLiftingPlatformDepthValue() const
{
return readLatestDepthValue(DepthValueType::LiftingPlatform);
}

41
HPPA/DepthValueLogger.h Normal file
View File

@ -0,0 +1,41 @@
#ifndef DEPTH_VALUE_LOGGER_H
#define DEPTH_VALUE_LOGGER_H
#include <QObject>
#include <QString>
enum class DepthValueType
{
Plant,
LiftingPlatform
};
class DepthValueLogger : public QObject
{
Q_OBJECT
public:
static DepthValueLogger& instance();
void appendDepthValue(double depthValue, DepthValueType type);
double readLatestDepthValue(DepthValueType type) const;
bool hasValidDepthValue(DepthValueType type) const;
void appendPlantDepthValue(double depthValue);
void appendLiftingPlatformDepthValue(double depthValue);
double readLatestPlantDepthValue() const;
double readLatestLiftingPlatformDepthValue() const;
signals:
void depthValueLogged(double value, DepthValueType type);
private:
DepthValueLogger();
~DepthValueLogger();
DepthValueLogger(const DepthValueLogger&) = delete;
DepthValueLogger& operator=(const DepthValueLogger&) = delete;
QString getLogFilePath(DepthValueType type) const;
};
#endif

View File

@ -0,0 +1,61 @@
//
// Created by tangchao on 2022/1/11.
//
#ifndef OCEAN_OPTICS_CALIBRATION_CONSOLE_FIBERSPECTROMETEROPERATIONBASE_H
#define OCEAN_OPTICS_CALIBRATION_CONSOLE_FIBERSPECTROMETEROPERATIONBASE_H
#include "ZZ_Types.h"
using namespace ZZ_MISCDEF;
using namespace ZZ_MISCDEF::IRIS::FS;
class FiberSpectrometerOperationBase
{
public:
// FiberSpectrometerOperationBase();
// ~FiberSpectrometerOperationBase();
virtual void connectFiberSpectrometer(QString& sn, QString& pixelCount, QString& wavelengthInfo) = 0;
virtual void disconnectFiberSpectrometer() = 0;
virtual void getDeviceAttribute(DeviceAttribute& deviceAttribute) = 0;
virtual void getDeviceInfo(DeviceInfo& deviceInfo) = 0;
virtual void setExposureTime(int iExposureTimeInMS) = 0;
virtual void getExposureTime(int &iExposureTimeInMS) = 0;
virtual void getDeviceTemperature(float &fTemperature) = 0;
virtual void singleShot(DataFrame &dfData) = 0;
// typedef struct coeffs
// {
// ZZ_U32 coeffsCounter;
// double coeffs[100];
// }coeffsFrame;
virtual void getNonlinearityCoeffs(coeffsFrame &coeffs) = 0;
// ZZ_S32 GetMaxValue(ZZ_S32 * dark, int number) = 0;
DataFrame m_IntegratingSphereData;
DataFrame m_DarkData;
protected:
ZZ_U32 m_MaxValueOfFiberSpectrometer;
private:
public slots:
virtual void recordDark(QString path) = 0;
virtual void recordTarget(int recordTimes, QString path) = 0;
virtual void autoExpose() = 0;
signals:
void sendExposureTimeSignal(int exposureTime);
};
#endif //OCEAN_OPTICS_CALIBRATION_CONSOLE_FIBERSPECTROMETEROPERATIONBASE_H

View File

@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>557</width>
<height>432</height>
<width>582</width>
<height>465</height>
</rect>
</property>
<property name="windowTitle">
@ -154,7 +154,7 @@ QSlider::handle:horizontal:pressed {
border: 1px solid #2f6bff;
}</string>
</property>
<layout class="QGridLayout" name="gridLayout_7">
<layout class="QGridLayout" name="gridLayout_10">
<property name="leftMargin">
<number>0</number>
</property>
@ -168,7 +168,7 @@ QSlider::handle:horizontal:pressed {
<number>0</number>
</property>
<property name="spacing">
<number>10</number>
<number>6</number>
</property>
<item row="0" column="0">
<widget class="QWidget" name="titlebarWidget" native="true">
@ -242,23 +242,11 @@ QSlider::handle:horizontal:pressed {
</item>
<item row="1" column="0">
<widget class="QWidget" name="widget" native="true">
<layout class="QGridLayout" name="gridLayout_2">
<property name="leftMargin">
<number>10</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>10</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<layout class="QGridLayout" name="gridLayout_2" columnstretch="2,3">
<property name="spacing">
<number>10</number>
<number>9</number>
</property>
<item row="0" column="0" rowspan="2">
<item row="0" column="0">
<widget class="QWidget" name="connectFocusModule_widget" native="true">
<property name="styleSheet">
<string notr="true">QWidget #connectFocusModule_widget
@ -274,85 +262,185 @@ QRadioButton
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="leftMargin">
<number>9</number>
<number>0</number>
</property>
<property name="topMargin">
<number>9</number>
<number>0</number>
</property>
<property name="rightMargin">
<number>9</number>
<number>0</number>
</property>
<property name="bottomMargin">
<number>9</number>
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>连接调焦模块</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>线性平台</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="motorPort_comboBox"/>
</item>
<item row="2" column="0">
<widget class="QRadioButton" name="ultrasound_radioButton">
<property name="text">
<string>超声</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QComboBox" name="ultrasoundPort_comboBox">
<property name="enabled">
<bool>false</bool>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QRadioButton" name="is_new_version_radioButton">
<property name="text">
<string>新版</string>
</property>
</widget>
</item>
<item row="3" column="1">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>107</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="4" column="0" colspan="2">
<widget class="QPushButton" name="connectMotor_btn">
<property name="text">
<string>连接线性平台</string>
<property name="spacing">
<number>0</number>
</property>
<item row="0" column="1">
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>连接调焦线性平台</string>
</property>
<layout class="QGridLayout" name="gridLayout_7">
<item row="0" column="0">
<widget class="QRadioButton" name="is_new_version_radioButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>新版</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="autoExclusive">
<bool>false</bool>
</property>
</widget>
</item>
<item row="0" column="1">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="0" colspan="2">
<widget class="QStackedWidget" name="stackedWidget_connetcParm">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="page">
<layout class="QGridLayout" name="gridLayout_12">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
</layout>
</widget>
<widget class="QWidget" name="page_2">
<layout class="QGridLayout" name="gridLayout_13">
<item row="0" column="0">
<widget class="QLabel" name="label_2">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>线性平台</string>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="motorPort_comboBox"/>
</item>
<item row="1" column="0">
<widget class="QRadioButton" name="ultrasound_radioButton">
<property name="text">
<string>超声</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="ultrasoundPort_comboBox">
<property name="enabled">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QPushButton" name="connectMotor_btn">
<property name="text">
<string>连接</string>
</property>
</widget>
</item>
<item row="3" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="1">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_4">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>状态</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="motor_state_label">
<property name="maximumSize">
<size>
<width>8</width>
<height>8</height>
</size>
</property>
<property name="sizeIncrement">
<size>
<width>8</width>
<height>8</height>
</size>
</property>
<property name="styleSheet">
<string notr="true">QLabel#motor_state_label
{
background-color: red;
border-radius: 4px;
}</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
</layout>
@ -368,151 +456,147 @@ QRadioButton
}</string>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="2" column="0">
<widget class="QPushButton" name="moveto_btn">
<property name="text">
<string>移动至</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QPushButton" name="logicZero_btn">
<property name="text">
<string>LogicZero</string>
</property>
</widget>
</item>
<item row="2" column="1" colspan="2">
<widget class="QLineEdit" name="move2_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>10</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QPushButton" name="add_btn">
<property name="text">
<string>+</string>
</property>
</widget>
</item>
<item row="4" column="1" colspan="2">
<widget class="QLineEdit" name="subtractStepSize_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>10</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="updateCurrentLocation_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>34</height>
</size>
</property>
<property name="text">
<string>更新实时位置</string>
</property>
</widget>
</item>
<item row="3" column="1" colspan="2">
<widget class="QLineEdit" name="addStepSize_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>10</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="QPushButton" name="rangeMeasurement_btn">
<property name="text">
<string>量程测量</string>
</property>
</widget>
</item>
<item row="1" column="1" colspan="2">
<widget class="QLineEdit" name="currentLocation_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>null</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QPushButton" name="subtract_btn">
<property name="text">
<string>-</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="max_btn">
<property name="text">
<string>max</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_5">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<item row="0" column="2">
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>调整线性平台</string>
</property>
<layout class="QGridLayout" name="gridLayout_8">
<item row="0" column="0">
<widget class="QPushButton" name="updateCurrentLocation_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>34</height>
</size>
</property>
<property name="text">
<string>更新实时位置</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QPushButton" name="subtract_btn">
<property name="text">
<string>-</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QPushButton" name="add_btn">
<property name="text">
<string>+</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QPushButton" name="logicZero_btn">
<property name="text">
<string>LogicZero</string>
</property>
</widget>
</item>
<item row="1" column="1" colspan="2">
<widget class="QLineEdit" name="move2_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>0</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="3" column="1" colspan="2">
<widget class="QLineEdit" name="subtractStepSize_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>1</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="moveto_btn">
<property name="text">
<string>移动至</string>
</property>
</widget>
</item>
<item row="0" column="1" colspan="2">
<widget class="QLineEdit" name="currentLocation_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>null</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QPushButton" name="max_btn">
<property name="text">
<string>max</string>
</property>
</widget>
</item>
<item row="4" column="2">
<widget class="QPushButton" name="rangeMeasurement_btn">
<property name="text">
<string>量程测量</string>
</property>
</widget>
</item>
<item row="2" column="1" colspan="2">
<widget class="QLineEdit" name="addStepSize_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>1</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
</item>
<item row="1" column="1">
<item row="1" column="0" colspan="2">
<widget class="QWidget" name="controlFocus_widget" native="true">
<property name="styleSheet">
<string notr="true">QWidget #controlFocus_widget
@ -521,53 +605,53 @@ QRadioButton
border-radius: 5px 5px 5px 5px;
}</string>
</property>
<layout class="QGridLayout" name="gridLayout_4">
<item row="0" column="0">
<widget class="QLabel" name="label_4">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
<layout class="QGridLayout" name="gridLayout_4" columnstretch="1,2">
<item row="0" column="1">
<widget class="QGroupBox" name="groupBox_3">
<property name="title">
<string>自动调焦</string>
</property>
<property name="text">
<string>调焦</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_3">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>采样率</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="sample_ratio_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>20</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QProgressBar" name="autoFocusProgress_progressBar">
<property name="styleSheet">
<string notr="true">QProgressBar {
<layout class="QGridLayout" name="gridLayout_9">
<item row="0" column="0">
<widget class="QLabel" name="label_3">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>采样数</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="sample_ratio_lineEdit">
<property name="minimumSize">
<size>
<width>88</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>20</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="autoFocus_btn">
<property name="text">
<string>自动调焦</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QProgressBar" name="autoFocusProgress_progressBar">
<property name="styleSheet">
<string notr="true">QProgressBar {
border: 2px solid #08FACE; /* 边框颜色和宽度 */
border-radius: 8px; /* 圆角 */
background-color: #eee; /* 未完成部分颜色 */
@ -579,37 +663,29 @@ QRadioButton
background-color: #08FACE; /* 渐变色进度块 */
border-radius: 8px; /* 保持和整体圆角一致 */
}</string>
</property>
<property name="value">
<number>24</number>
</property>
</property>
<property name="value">
<number>24</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="autoFocus_btn">
<property name="text">
<string>自动调焦</string>
</property>
</widget>
</item>
<item row="3" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>171</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="1">
<widget class="QPushButton" name="manualFocus_btn">
<property name="text">
<item row="0" column="0">
<widget class="QGroupBox" name="groupBox_4">
<property name="title">
<string>手动调焦</string>
</property>
<layout class="QGridLayout" name="gridLayout_11">
<item row="0" column="0">
<widget class="QPushButton" name="manualFocus_btn">
<property name="text">
<string>手动调焦</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>

99
HPPA/FodisWindow.cpp Normal file
View File

@ -0,0 +1,99 @@
#include "FodisWindow.h"
#include "JinspFiberImagerConfig.h"
FodisWindow::FodisWindow(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
m_FiberImagerThread = new QThread();
m_JinspFiberImagerOperation = new JinspFiberImager(false, JinspFiberImagerConfig::instance().portName().toStdString(), "JINSP");
connect(m_JinspFiberImagerOperation, &JinspFiberImager::spectalCaptured, this, &FodisWindow::spectalCaptured);
connect(m_JinspFiberImagerOperation, &JinspFiberImager::startExposureSignal, this, &FodisWindow::startExposureSignal);
connect(m_JinspFiberImagerOperation, &JinspFiberImager::exposureCompleteSignal, this, &FodisWindow::exposureCompleteSignal);
m_JinspFiberImagerOperation->moveToThread(m_FiberImagerThread);
m_FiberImagerThread->start();
connect(ui.open_btn, &QPushButton::clicked, this, &FodisWindow::openFiberImager);
connect(ui.close_btn, &QPushButton::clicked, this, &FodisWindow::closeFiberImager);
connect(this, &FodisWindow::openFiberImagerSignal, m_JinspFiberImagerOperation, &JinspFiberImager::OpenFiberImagerAndRecord);
//connect(m_JinspFiberImagerOperation, &JinspFiberImager::CamOpenedSignal, this, &FodisWindow::onCamOpened);
//connect(m_JinspFiberImagerOperation, &JinspFiberImager::CamClosedSignal, this, &FodisWindow::onCamClosed);
//connect(m_JinspFiberImagerOperation, &JinspFiberImager::PlotSignal, this, &FodisWindow::PlotSpectralSignal);
//connect(m_JinspFiberImagerOperation, &JinspFiberImager::CamClosedSignal, this, &FodisWindow::FiberImagerClosedSignal);
connect(this->ui.dataFolderBtn, SIGNAL(clicked()), this, SLOT(onSelectDataFolder()));
// 初始化数据保存路径显示(从 AppSettings 恢复或使用默认)
ui.dataFolderLineEdit->setText(AppSettings::instance().depthCameraDataFolder());
setDataFolder(AppSettings::instance().FiberImagerDataFolder());
}
FodisWindow::~FodisWindow()
{
m_FiberImagerThread->quit();
m_FiberImagerThread->wait();
delete m_JinspFiberImagerOperation;
m_JinspFiberImagerOperation = nullptr;
}
void FodisWindow::onSelectDataFolder()
{
QString dir = QFileDialog::getExistingDirectory(this,
QString::fromLocal8Bit("选择数据保存路径"),
ui.dataFolderLineEdit->text());
setDataFolder(dir);
}
void FodisWindow::setDataFolder(QString dir)
{
if (!dir.isEmpty())
{
ui.dataFolderLineEdit->setText(dir);
AppSettings::instance().setFiberImagerDataFolder(dir);
}
}
void FodisWindow::setCaptureInterval(int captureIntervalSeconds)
{
m_JinspFiberImagerOperation->setCaptureInterval(captureIntervalSeconds);
}
void FodisWindow::openFiberImager()
{
openFiberImager_expose_record("pos_null");
}
void FodisWindow::openFiberImager_expose_record(QString posInfo)
{
if (!m_JinspFiberImagerOperation->getRecordStatus())
{
emit openFiberImagerSignal(posInfo);
}
}
void FodisWindow::onCamOpened()
{
ui.open_btn->setEnabled(false);
ui.close_btn->setEnabled(true);
ui.open_btn->setText(QString::fromLocal8Bit("已打开"));
}
void FodisWindow::closeFiberImager()
{
m_JinspFiberImagerOperation->disconnectFiberSpectrometer();
}
void FodisWindow::onCamClosed()
{
ui.open_btn->setEnabled(true);
ui.close_btn->setEnabled(false);
ui.open_btn->setText(QString::fromLocal8Bit("打 开"));
}

56
HPPA/FodisWindow.h Normal file
View File

@ -0,0 +1,56 @@
#pragma once
#include <QDialog>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QImage>
#include <Qthread>
#include <QDir>
//#include <QLabel>
#include <QFileDialog>
#include <iostream>
#include "ui_fodis.h"
#include "AppSettings.h"
#include <fstream>
#include "JinspFiberImager.h"
class FodisWindow : public QDialog
{
Q_OBJECT
public:
FodisWindow(QWidget* parent = nullptr);
~FodisWindow();
void setDataFolder(QString dir);
void setCaptureInterval(int captureIntervalSeconds);
public Q_SLOTS:
void openFiberImager();
void openFiberImager_expose_record(QString posInfo);
void onCamOpened();
void closeFiberImager();
void onCamClosed();
void onSelectDataFolder();
signals:
void openFiberImagerSignal(QString posInfo);
void PlotSpectralSignal();
void FiberImagerClosedSignal();
void spectalCaptured(DeviceAttribute attribute, DataFrame dataFrame);
void startExposureSignal();
void exposureCompleteSignal(int exposureTime);
private:
Ui::FodisWindow ui;
QThread* m_FiberImagerThread;
JinspFiberImager* m_JinspFiberImagerOperation;
};

View File

@ -0,0 +1,146 @@
#include "GonggaShanRecordCtl.h"
GonggashanTaskScheduler::GonggashanTaskScheduler(QObject* parent)
: QObject(parent)
, m_taskState(TaskState::Idle)
{
}
GonggashanTaskScheduler::~GonggashanTaskScheduler()
{
}
bool GonggashanTaskScheduler::isTaskRunning() const
{
return m_taskState == TaskState::Running;
}
void GonggashanTaskScheduler::setTaskRunning(bool running)
{
m_taskState = running ? TaskState::Running : TaskState::Idle;
Q_EMIT taskStateChanged(m_taskState);
}
void GonggaShanRecordCtl::logStatus(const QString& message, bool isHearderBlankLine, bool isTailBlankLine)
{
QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
if (isHearderBlankLine)
{
ui.status_textEdit->append("\n");
}
ui.status_textEdit->append(QString("[%1] %2").arg(timestamp, message));
if (isTailBlankLine)
{
ui.status_textEdit->append("\n");
}
if (m_logStream.device())
{
if (isHearderBlankLine)
{
m_logStream << "\n";
}
m_logStream << "[" << timestamp << "] " << message << "\n";
if (isTailBlankLine)
{
m_logStream << "\n";
}
m_logStream.flush();
m_logFile.flush();
}
}
GonggaShanRecordCtl::GonggaShanRecordCtl(QWidget* parent)
: QDialog(parent)
, m_taskScheduler(new GonggashanTaskScheduler(this))
{
ui.setupUi(this);
AppSettings& settings = AppSettings::instance();
ui.spinbox_Port->setValue(settings.gonggaShanRecordPort());
connect(ui.btnListen, &QPushButton::clicked, this, &GonggaShanRecordCtl::startListen);
connect(ui.btnDisListen, &QPushButton::clicked, this, &GonggaShanRecordCtl::stopListen);
connect(ui.spinbox_Port, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
AppSettings::instance().setGonggaShanRecordPort(value);
});
}
GonggaShanRecordCtl::~GonggaShanRecordCtl()
{
if (m_logFile.isOpen()) {
m_logStream.flush();
m_logFile.close();
}
tcpServer6005->deleteLater();
}
void GonggaShanRecordCtl::startListen()
{
if (m_logFile.isOpen()) {
m_logStream.flush();
m_logFile.close();
}
QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss");
QString logFileName = QString("%1_log.txt").arg(timestamp);
m_logFilePath = AppSettings::instance().dataFolder() + QDir::separator() + logFileName;
m_logFile.setFileName(m_logFilePath);
m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
m_logStream.setDevice(&m_logFile);
logStatus("Start listen....", true, true);
MotorParams::TCPConnectionParams tcpConnectionParams6005;
tcpConnectionParams6005.port = ui.spinbox_Port->text().toInt();
tcpConnectionParams6005.serverIP = "192.168.1.2";//此ip地址没有使用,可以随便填入
tcpServer6005 = new MotorParams::CommunicationViaTCP(tcpConnectionParams6005, this);
connect(tcpServer6005, &MotorParams::CommunicationViaTCP::positionReceived, this, &GonggaShanRecordCtl::startRecord);
}
void GonggaShanRecordCtl::stopListen()
{
logStatus("Stop listen", true, true);
disconnect(tcpServer6005, &MotorParams::CommunicationViaTCP::positionReceived, this, &GonggaShanRecordCtl::startRecord);
tcpServer6005->deleteLater();
}
void GonggaShanRecordCtl::startRecord(int position)
{
if (m_taskScheduler->isTaskRunning())
{
logStatus("Data collection has begun....");
return;
}
QString pos = QString::number(position);
logStatus("Reach pos: " + pos, true);
m_taskScheduler->setTaskRunning(true);
emit startRcordSignal("pos_" + pos);
}
void GonggaShanRecordCtl::onFiberImagerStartExposureSignal()
{
logStatus("FiberImager: start exposure...");
}
void GonggaShanRecordCtl::onFiberImagerExposureCompleteSignal(int exposureTime)
{
logStatus(QString("FiberImager: exposure finished, %1").arg(exposureTime));
logStatus("Start recording...");
}
void GonggaShanRecordCtl::onRcordFinished()
{
m_taskScheduler->setTaskRunning(false);
logStatus("Record Finished.");
}

View File

@ -0,0 +1,76 @@
#pragma once
#include <QDialog>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <vector>
#include <QPointer>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include "ui_gonggashanCtl.h"
#include "CommunicationViaTCP.h"
#include "AppSettings.h"
class GonggashanTaskScheduler : public QObject
{
Q_OBJECT
public:
enum class TaskState
{
Idle,
Running
};
explicit GonggashanTaskScheduler(QObject* parent = nullptr);
~GonggashanTaskScheduler();
bool isTaskRunning() const;
void setTaskRunning(bool running);
Q_SIGNALS:
void taskStateChanged(TaskState state);
private:
TaskState m_taskState;
};
class GonggaShanRecordCtl : public QDialog
{
Q_OBJECT
public:
GonggaShanRecordCtl(QWidget* parent = nullptr);
~GonggaShanRecordCtl();
public Q_SLOTS:
void onFiberImagerStartExposureSignal();
void onRcordFinished();
void onFiberImagerExposureCompleteSignal(int exposureTime);
Q_SIGNALS:
// Emitted when user changes any of the R/G/B wavelength values
void startRcordSignal(QString posInfo);
private Q_SLOTS:
void startListen();
void stopListen();
void startRecord(int position);
private:
void logStatus(const QString& message, bool isHearderBlankLine = false, bool isTailBlankLine = false);
Ui::gongga_control ui;
QPointer<MotorParams::CommunicationViaTCP> tcpServer6005;
GonggashanTaskScheduler* m_taskScheduler;
QString m_logFilePath;
QFile m_logFile;
QTextStream m_logStream;
};

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@
#include <QChart>
#include <QChartView>
#include <QValueAxis>
#include <QPointer>
#include <QFileDialog>
#include <QNetworkRequest>
@ -79,6 +80,18 @@
#include "rgbCameraWindow.h"
#include "DepthCameraWindow.h"
#include "SingleLensReflexCameraWindow.h"
#include "LayerTreeImageNode.h"
#include "TimedDataCollection.h"
#include "PowerControl3D.h"
#include "FodisWindow.h"
#include "GonggaShanRecordCtl.h"
#include <algorithm>
#define PI 3.1415926
@ -186,6 +199,26 @@ private:
QPixmap m_pixmap;
};
class ImageStretchWorker : public QObject
{
Q_OBJECT
public:
explicit ImageStretchWorker(QObject* parent = nullptr);
~ImageStretchWorker();
public slots:
void processImage(const cv::Mat& rgbImage, int fileNumber, const QString& filePath, float ratio = 0.02f);
signals:
void imageReady(int fileNumber, const QString& filePath, QPixmap& pixmap);
void processingError(int fileNumber, const QString& filePath, const QString& error);
private:
cv::Mat CStretch(const cv::Mat& img, float ratio);
cv::Mat CStretchDeal(const cv::Mat& img, uint minnum, uint maxnum);
std::vector<cv::Point2f> CHistogram(const cv::Mat& img);
uint MaxRatio(const std::vector<cv::Point2f>& data, float ratio);
uint MinRatio(const std::vector<cv::Point2f>& data, float ratio);
QImage Mat2QImage(const cv::Mat& cvImg);
};
class HPPA : public QMainWindow
{
Q_OBJECT
@ -271,6 +304,8 @@ private:
MyCarousel* m_carousel;
QLabel* m_cam_label;
QLabel* m_SingleLensReflexCamera_label;
QLabel* m_depthCamera_label;
QPushButton* m_open_rgb_camera_btn;
QPushButton* m_close_rgb_camera_btn;
@ -280,11 +315,17 @@ private:
rgbCameraWindow* m_rgbCameraControlWindow;
ImageControl* m_ic;
DepthCameraWindow* m_depthCameraWindow;
SingleLensReflexCameraWindow* m_singleLensReflexCameraWindow;
adjustTable* m_adt;
PowerControl* m_pc;
PowerControl3D* m_pc3D;
RobotArmControl* m_rac;
OneMotorControl* m_omc;
OneMotorControl_LiftingPlatform* m_omc_LiftingPlatform;
TwoMotorControl* m_tmc;
FodisWindow* m_fodisWindow;
GonggaShanRecordCtl* m_gonggaShanRecordCtl;
QPointer<TimedDataCollection> m_tdc;
View3DModelManager* m_view3DModelManager;
@ -310,6 +351,21 @@ private:
bool showResultMessageBox(QString title, QString msg);
void disconnectImagerAndCleanup();
void initTimedDataCollection();
QThread* m_ImageStretchThread = nullptr;
ImageStretchWorker* m_ImageStretchWorker = nullptr;
// 用于临时显示的未拉伸图像(可选,用于快速预览)
void showQuickPreview(int fileNumber, const QString& filePath, const cv::Mat& rgbImage);
QChart* m_FiberImagerChart;
void showFiberImagerSpectral(DeviceAttribute attribute, DataFrame dataFrame);
void setupGonggashanAutoRecordConnection();
public Q_SLOTS:
void onPlotHyperspectralImageRgbImage(int fileNumber, int frameNumber, QString filePath);
void focusPlotSpectralImg(int state);
@ -351,8 +407,13 @@ public Q_SLOTS:
void OnSendLogToCallClass(QString str);
void onPlotRgbImage();
void onPlotDepthImage();
void onLiveViewImageReady(const QImage& image);
void HPPA::onLiveViewStopped();
void onClearLabel();
void onClearDepthLabel();
void onCopyFinished();
@ -361,13 +422,21 @@ public Q_SLOTS:
void recordFromRobotArm(int fileCounter);
void createOneMotorScenario();
void createGonggaRotatingPlatformScenario();
void createPlantPhenotypeScenario();
void create3DPlantPhenotypeScenario();
void onCreated3DModelPlantPhenotype();
void onCreated3DModelMicroscopicMotion();
void createMicroscopicMotionControlScenario();
void onCreated3DModelOneMotor();
void addLayer(const QString& baseName, const QString& filePath, bool refresh);
void addLayer(const QString& baseName, const QString& filePath, bool refresh, bool isAddImage = true);
void newImage(RasterLayer* ml, RasterImageLayer::RendererType, LayerTreeNode* parent, bool refresh=true);
void onLayerCreatedFromFile(const QString& baseName, const QString& filePath, int fileIndex);
void removeLayerByTreeIndex();
void removeLayerByNode(LayerTreeNode* node);
void showColorImageByTreeIndex();
void removeImageByTreeIndex();
void removeAllLayersInRasterGroup();
void onLayerTreeSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
@ -375,6 +444,21 @@ public Q_SLOTS:
void onMapToolPanTriggered();
void onMapToolSpectralTriggered();
void onTimedDataCollection();
void setTimedDataCollectionHyperCamParm(int camType, double f, double e, QString filePath, QString fileName);
void setTimedDataCollectionCamParm(int camType, int captureIntervalSeconds, QString folder);
void setTimedDataCollectionMotorParm(QString pathLineFilePath);
void onStartTimedDataCollection(int camType);
void onObtainTargetDepthInformation(SubTask subTaskParams);
void onLiftingPlatform(SubTask subTaskParams);
void onAutoFocus_TimedDataCollection(SubTask subTaskParams);
void onStretchedImageReady(int fileNumber, const QString& filePath, QPixmap& pixmap);
void onStretchProcessingError(int fileNumber, const QString& filePath, const QString& error);
void onGonggashanRecord(QString posInfo);
protected:
void closeEvent(QCloseEvent* event) override;

View File

@ -105,6 +105,7 @@ color:white;
<addaction name="action_start_recording"/>
<addaction name="separator"/>
<addaction name="actionOpenDirectory"/>
<addaction name="mActionTimedDataCollection"/>
</widget>
<widget class="QMenu" name="menuhelp">
<property name="title">
@ -132,7 +133,10 @@ color:white;
<string>应用场景</string>
</property>
<addaction name="mActionOneMotorScenario"/>
<addaction name="mActionGonggaRotatingPlatformScenario"/>
<addaction name="mActionPlantPhenotypeScenario"/>
<addaction name="mActionMicroscopicMotionControlScenario"/>
<addaction name="mAction3DPlantPhenotypeScenario"/>
</widget>
<widget class="QMenu" name="menu_4">
<property name="title">
@ -725,6 +729,35 @@ QPushButton:pressed
<string>光谱</string>
</property>
</action>
<action name="mActionMicroscopicMotionControlScenario">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>显微运动控制台</string>
</property>
</action>
<action name="mAction3DPlantPhenotypeScenario">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>3D植物表型</string>
</property>
</action>
<action name="mActionTimedDataCollection">
<property name="text">
<string>定时采集</string>
</property>
</action>
<action name="mActionGonggaRotatingPlatformScenario">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>贡嘎山旋转平台</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<customwidgets>

View File

@ -55,27 +55,28 @@
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<IncludePath>D:\cpp_library\gdal2.2.3_vs2017\include;C:\Program Files\ResononAPI\include;D:\cpp_library\opencv3.4.11\opencv\build\include;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv2;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PCOMM\Include;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PortControl;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL;D:\cpp_project_vs2022\HPPA\HPPA;D:\cpp_library\libconfig-1.7.3\lib;D:\cpp_project_vs2022\HPPA\vincecontrol;D:\cpp_library\vincecontrol_vs2017;C:\XIMEA\API\xiAPI;D:\cpp_project_vs2022\HPPA\IrisMultiMotorController\IrisMultiMotorController;D:\cpp_library\eigen-3.4-rc1;$(IncludePath)</IncludePath>
<LibraryPath>D:\cpp_library\opencv3.4.11\opencv\build\x64\vc15\lib;D:\cpp_library\gdal2.2.3_vs2017\lib;C:\Program Files\ResononAPI\lib64;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\x64\Debug;D:\cpp_library\libconfig-1.7.3\build\x64;D:\cpp_project_vs2022\HPPA\x64\Debug;C:\XIMEA\API\xiAPI;D:\cpp_project_vs2022\HPPA\IrisMultiMotorController\x64\Debug;$(LibraryPath)</LibraryPath>
<IncludePath>D:\cpp_library\gdal2.2.3_vs2017\include;C:\Program Files\ResononAPI\include;D:\cpp_library\opencv3.4.11\opencv\build\include;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv2;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PCOMM\Include;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PortControl;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL;D:\cpp_project_vs2022\HPPA\HPPA;D:\cpp_library\libconfig-1.7.3\lib;D:\cpp_project_vs2022\HPPA\vincecontrol;D:\cpp_library\vincecontrol_vs2017;C:\XIMEA\API\xiAPI;D:\cpp_project_vs2022\HPPA\IrisMultiMotorController\IrisMultiMotorController;D:\cpp_library\eigen-3.4-rc1;C:\Program Files\OrbbecSDK 2.7.6\include;D:\cpp_library\EDSDK132010CD(13.20.10)\Windows\EDSDK_64\Header;D:\cpp_project_vs2022\HPPA\JinspSpectralmeterControl;$(IncludePath)</IncludePath>
<LibraryPath>D:\cpp_library\opencv3.4.11\opencv\build\x64\vc15\lib;D:\cpp_library\gdal2.2.3_vs2017\lib;C:\Program Files\ResononAPI\lib64;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\x64\Debug;D:\cpp_library\libconfig-1.7.3\build\x64;D:\cpp_project_vs2022\HPPA\x64\Debug;C:\XIMEA\API\xiAPI;D:\cpp_project_vs2022\HPPA\IrisMultiMotorController\x64\Debug;C:\Program Files\OrbbecSDK 2.7.6\lib;D:\cpp_library\EDSDK132010CD(13.20.10)\Windows\EDSDK_64\Library;$(LibraryPath)</LibraryPath>
<TargetName>Spectral Insight</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<IncludePath>D:\cpp_library\gdal2.2.3_vs2017\include;C:\Program Files\ResononAPI\include;D:\cpp_library\opencv3.4.11\opencv\build\include;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv2;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PCOMM\Include;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PortControl;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL;D:\cpp_project_vs2022\HPPA\HPPA;D:\cpp_library\libconfig-1.7.3\lib;D:\cpp_project_vs2022\HPPA\vincecontrol;C:\XIMEA\API\xiAPI;D:\cpp_project_vs2022\HPPA\IrisMultiMotorController\IrisMultiMotorController;D:\cpp_library\eigen-3.4-rc1;$(IncludePath)</IncludePath>
<LibraryPath>D:\cpp_library\opencv3.4.11\opencv\build\x64\vc15\lib;D:\cpp_library\vincecontrol_vs2017_release;D:\cpp_library\gdal2.2.3_vs2017\lib;C:\Program Files\ResononAPI\lib64;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\x64\Release;D:\cpp_library\libconfig-1.7.3\build\x64;D:\cpp_project_vs2022\IrisMultiMotorController\x64\Release;C:\XIMEA\API\xiAPI;$(LibraryPath)</LibraryPath>
<IncludePath>D:\cpp_library\gdal2.2.3_vs2017\include;C:\Program Files\ResononAPI\include;D:\cpp_library\opencv3.4.11\opencv\build\include;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv;D:\cpp_library\opencv3.4.11\opencv\build\include\opencv2;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PCOMM\Include;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL\SDKs\PortControl;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\AutoFocus_InspireLinearMotor_DLL;D:\cpp_project_vs2022\HPPA\HPPA;D:\cpp_library\libconfig-1.7.3\lib;D:\cpp_project_vs2022\HPPA\vincecontrol;C:\XIMEA\API\xiAPI;D:\cpp_project_vs2022\HPPA\IrisMultiMotorController\IrisMultiMotorController;D:\cpp_library\eigen-3.4-rc1;C:\Program Files\OrbbecSDK 2.7.6\include;D:\cpp_library\EDSDK132010CD(13.20.10)\Windows\EDSDK_64\Header;D:\cpp_project_vs2022\HPPA\JinspSpectralmeterControl;$(IncludePath)</IncludePath>
<LibraryPath>D:\cpp_library\opencv3.4.11\opencv\build\x64\vc15\lib;D:\cpp_library\vincecontrol_vs2017_release;D:\cpp_library\gdal2.2.3_vs2017\lib;C:\Program Files\ResononAPI\lib64;D:\cpp_project_vs2022\AutoFocus_InspireLinearMotor_DLL\x64\Release;D:\cpp_library\libconfig-1.7.3\build\x64;D:\cpp_project_vs2022\IrisMultiMotorController\x64\Release;C:\XIMEA\API\xiAPI;C:\Program Files\OrbbecSDK 2.7.6\lib;D:\cpp_library\EDSDK132010CD(13.20.10)\Windows\EDSDK_64\Library;$(LibraryPath)</LibraryPath>
<TargetName>Spectral Insight</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>opencv_world3411.lib;opencv_world3411d.lib;gdal_i.lib;resonon-basler.lib;AutoFocus_InspireLinearMotor_DLL.lib;libconfig++d.lib;vincecontrol.lib;resonon-allied.lib;xiapi64.lib;IrisMultiMotorController.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>opencv_world3411.lib;opencv_world3411d.lib;gdal_i.lib;resonon-basler.lib;AutoFocus_InspireLinearMotor_DLL.lib;libconfig++d.lib;vincecontrol.lib;resonon-allied.lib;xiapi64.lib;IrisMultiMotorController.lib;OrbbecSDK.lib;EDSDK.lib;JinspSpectralmeterControl.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>D:\cpp_project_vs2022\HPPA\x64\Debug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
<LanguageStandard>stdcpp14</LanguageStandard>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>opencv_world3411.lib;vincecontrol.lib;gdal_i.lib;resonon-basler.lib;resonon-allied.lib;AutoFocus_InspireLinearMotor_DLL.lib;libconfig++.lib;xiapi64.lib;IrisMultiMotorController.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>opencv_world3411.lib;vincecontrol.lib;gdal_i.lib;resonon-basler.lib;resonon-allied.lib;AutoFocus_InspireLinearMotor_DLL.lib;libconfig++.lib;xiapi64.lib;IrisMultiMotorController.lib;OrbbecSDK.lib;EDSDK.lib;JinspSpectralmeterControl.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>D:\cpp_project_vs2022\HPPA\x64\Release;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
@ -112,18 +113,25 @@
<ClCompile Include="AspectRatioLabel.cpp" />
<ClCompile Include="CaptureCoordinator.cpp" />
<ClCompile Include="Carousel.cpp" />
<ClCompile Include="CommunicationInterfaceBase.cpp" />
<ClCompile Include="CommunicationViaTCP.cpp" />
<ClCompile Include="Corning410Imager.cpp" />
<ClCompile Include="CustomDockWidgetBase.cpp" />
<ClCompile Include="DepthCameraWindow.cpp" />
<ClCompile Include="FileNameLineEdit.cpp" />
<ClCompile Include="FodisWindow.cpp" />
<ClCompile Include="GonggaShanRecordCtl.cpp" />
<ClCompile Include="hppaConfigFile.cpp" />
<ClCompile Include="HyperImagerControl.cpp" />
<ClCompile Include="imageControl.cpp" />
<ClCompile Include="ImagerOperationBase.cpp" />
<ClCompile Include="imager_base.cpp" />
<ClCompile Include="irisximeaimager.cpp" />
<ClCompile Include="JinspFiberImager.cpp" />
<ClCompile Include="JinspFiberImagerConfig.cpp" />
<ClCompile Include="LayerTree.cpp" />
<ClCompile Include="LayerTreeGroupNode.cpp" />
<ClCompile Include="LayerTreeImageNode.cpp" />
<ClCompile Include="LayerTreeLayerNode.cpp" />
<ClCompile Include="LayerTreeModel.cpp" />
<ClCompile Include="LayerTreeNode.cpp" />
@ -137,13 +145,18 @@
<ClCompile Include="MapToolSpectral.cpp" />
<ClCompile Include="MotorWindowBase.cpp" />
<ClCompile Include="OneMotorControl.cpp" />
<ClCompile Include="PathLine.cpp" />
<ClCompile Include="path_tc.cpp" />
<ClCompile Include="PowerControl.cpp" />
<ClCompile Include="PowerControl3D.cpp" />
<ClCompile Include="QDoubleSlider.cpp" />
<ClCompile Include="QMotorDoubleSlider.cpp" />
<ClCompile Include="RasterDataProvider.cpp" />
<ClCompile Include="RasterLayer.cpp" />
<ClCompile Include="RasterRenderer.cpp" />
<ClCompile Include="MultibandRasterRenderer.cpp" />
<ClCompile Include="RasterRendererBase.cpp" />
<ClCompile Include="RasterImageLayer.cpp" />
<ClCompile Include="SinglebandRasterRenderer.cpp" />
<ClCompile Include="recordFrameCounter.cpp" />
<ClCompile Include="resononImager.cpp" />
<ClCompile Include="ResononNirImager.cpp" />
@ -151,11 +164,15 @@
<ClCompile Include="rgbCameraWindow.cpp" />
<ClCompile Include="RobotArmControl.cpp" />
<ClCompile Include="setWindow.cpp" />
<ClCompile Include="SingleLensReflexCameraWindow.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="TabManager.cpp" />
<ClCompile Include="TaskTreeModel.cpp" />
<ClCompile Include="TimedDataCollection.cpp" />
<ClCompile Include="TimedDataCollectionDataStructures.cpp" />
<ClCompile Include="TwoMotorControl.cpp" />
<ClCompile Include="utility_tc.cpp" />
<ClCompile Include="View3D.cpp" />
@ -165,8 +182,11 @@
<QtUic Include="adjustTable.ui" />
<QtUic Include="DepthCamera.ui" />
<QtUic Include="FocusDialog.ui" />
<QtUic Include="fodis.ui" />
<QtUic Include="gonggashanCtl.ui" />
<QtUic Include="HPPA.ui" />
<QtMoc Include="HPPA.h" />
<ClCompile Include="DepthValueLogger.cpp" />
<ClCompile Include="fileOperation.cpp" />
<ClCompile Include="focusWindow.cpp" />
<ClCompile Include="HPPA.cpp" />
@ -182,14 +202,18 @@
<QtUic Include="oneMotorControl.ui" />
<QtUic Include="PathPlan.ui" />
<QtUic Include="PowerControl.ui" />
<QtUic Include="PowerControl3D.ui" />
<QtUic Include="RadianceConversion.ui" />
<QtUic Include="ReflectanceConversion.ui" />
<QtUic Include="rgbCamera.ui" />
<QtUic Include="RobotArmControl.ui" />
<QtUic Include="set.ui" />
<QtUic Include="SingleLensReflexCamera.ui" />
<QtUic Include="TimedDataCollection_ui.ui" />
<QtUic Include="twoMotorControl.ui" />
</ItemGroup>
<ItemGroup>
<QtMoc Include="DepthValueLogger.h" />
<QtMoc Include="fileOperation.h" />
</ItemGroup>
<ItemGroup>
@ -214,6 +238,11 @@
<ClInclude Include="AppSettings.h" />
<QtMoc Include="FileNameLineEdit.h" />
<QtMoc Include="DepthCameraWindow.h" />
<QtMoc Include="CommunicationViaTCP.h" />
<QtMoc Include="CommunicationInterfaceBase.h" />
<QtMoc Include="FodisWindow.h" />
<ClInclude Include="FiberSpectrometerOperationBase.h" />
<QtMoc Include="GonggaShanRecordCtl.h" />
<ClInclude Include="imager_base.h" />
<ClInclude Include="irisximeaimager.h" />
<QtMoc Include="OneMotorControl.h" />
@ -227,6 +256,8 @@
<QtMoc Include="MapLayer.h" />
<QtMoc Include="RasterLayer.h" />
<QtMoc Include="MapLayerStore.h" />
<QtMoc Include="LayerTreeImageNode.h" />
<QtMoc Include="JinspFiberImager.h" />
<ClInclude Include="LayerTreeView.h" />
<QtMoc Include="LayerTreeViewMenuProvider.h" />
<QtMoc Include="MapTool.h" />
@ -234,11 +265,20 @@
<QtMoc Include="MapToolSpectral.h" />
<QtMoc Include="MapTools.h" />
<ClInclude Include="MotorWindowBase.h" />
<QtMoc Include="PowerControl3D.h" />
<ClInclude Include="PathLine.h" />
<ClInclude Include="RasterDataProvider.h" />
<ClInclude Include="RasterRenderer.h" />
<ClInclude Include="MultibandRasterRenderer.h" />
<ClInclude Include="RasterImageLayer.h" />
<ClInclude Include="RasterRendererBase.h" />
<ClInclude Include="SinglebandRasterRenderer.h" />
<QtMoc Include="recordFrameCounter.h" />
<QtMoc Include="setWindow.h" />
<QtMoc Include="rgbCameraWindow.h" />
<QtMoc Include="SingleLensReflexCameraWindow.h" />
<QtMoc Include="TimedDataCollection.h" />
<QtMoc Include="TimedDataCollectionDataStructures.h" />
<QtMoc Include="TaskTreeModel.h" />
<ClInclude Include="utility_tc.h" />
<QtMoc Include="aboutWindow.h" />
<ClInclude Include="hppaConfigFile.h" />

View File

@ -21,6 +21,24 @@
<UniqueIdentifier>{639EADAA-A684-42e4-A9AD-28FC9BCB8F7C}</UniqueIdentifier>
<Extensions>ts</Extensions>
</Filter>
<Filter Include="Header Files\TimedDataCollection">
<UniqueIdentifier>{3777a3c2-8d8a-4414-b6c9-ac20640f7b2e}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\TimedDataCollection">
<UniqueIdentifier>{ea004f0d-34de-4b29-8ce2-57dd8aa01c03}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\LayerTree">
<UniqueIdentifier>{25329ee3-f78c-4dd9-9170-e64ccb4ccd9e}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\LayerTree">
<UniqueIdentifier>{18072152-2a29-4ad8-be97-d097af97eeec}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\hyperImagerCtl">
<UniqueIdentifier>{b3f08410-c140-42db-bcfd-24efba860cfb}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\hyperImagerCtl">
<UniqueIdentifier>{205ec088-0286-42ca-862c-2870928a46f5}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<QtRcc Include="HPPA.qrc">
@ -70,9 +88,6 @@
<ClCompile Include="QMotorDoubleSlider.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="resononImager.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RgbCameraOperation.cpp">
<Filter>Source Files</Filter>
</ClCompile>
@ -88,12 +103,6 @@
<ClCompile Include="path_tc.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ResononNirImager.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ImagerOperationBase.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="utility_tc.cpp">
<Filter>Source Files</Filter>
</ClCompile>
@ -139,42 +148,27 @@
<ClCompile Include="View3DModelManager.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LayerTreeNode.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LayerTreeModel.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LayerTree.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LayerTreeGroupNode.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LayerTreeLayerNode.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="MapLayer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RasterLayer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RasterImageLayer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RasterDataProvider.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RasterRenderer.cpp">
<ClCompile Include="MultibandRasterRenderer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="SinglebandRasterRenderer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="MapLayerStore.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LayerTreeView.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LayerTreeViewMenuProvider.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="imageControl.cpp">
<Filter>Source Files</Filter>
</ClCompile>
@ -217,6 +211,81 @@
<ClCompile Include="DepthCameraWindow.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="SingleLensReflexCameraWindow.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RasterRendererBase.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="CommunicationViaTCP.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="CommunicationInterfaceBase.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="PowerControl3D.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="PathLine.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="FodisWindow.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="JinspFiberImager.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="JinspFiberImagerConfig.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GonggaShanRecordCtl.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="TaskTreeModel.cpp">
<Filter>Source Files\TimedDataCollection</Filter>
</ClCompile>
<ClCompile Include="TimedDataCollection.cpp">
<Filter>Source Files\TimedDataCollection</Filter>
</ClCompile>
<ClCompile Include="TimedDataCollectionDataStructures.cpp">
<Filter>Source Files\TimedDataCollection</Filter>
</ClCompile>
<ClCompile Include="LayerTree.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="LayerTreeGroupNode.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="LayerTreeImageNode.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="LayerTreeLayerNode.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="LayerTreeModel.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="LayerTreeNode.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="LayerTreeView.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="LayerTreeViewMenuProvider.cpp">
<Filter>Source Files\LayerTree</Filter>
</ClCompile>
<ClCompile Include="ImagerOperationBase.cpp">
<Filter>Source Files\hyperImagerCtl</Filter>
</ClCompile>
<ClCompile Include="resononImager.cpp">
<Filter>Source Files\hyperImagerCtl</Filter>
</ClCompile>
<ClCompile Include="ResononNirImager.cpp">
<Filter>Source Files\hyperImagerCtl</Filter>
</ClCompile>
<ClCompile Include="DepthValueLogger.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<QtMoc Include="fileOperation.h">
@ -243,18 +312,12 @@
<QtMoc Include="QMotorDoubleSlider.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="resononImager.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="RgbCameraOperation.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="aboutWindow.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="ImagerOperationBase.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="adjustTable.h">
<Filter>Header Files</Filter>
</QtMoc>
@ -291,21 +354,6 @@
<QtMoc Include="View3DModelManager.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="LayerTreeModel.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="LayerTreeNode.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="LayerTree.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="LayerTreeGroupNode.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="LayerTreeLayerNode.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="MapLayer.h">
<Filter>Header Files</Filter>
</QtMoc>
@ -315,9 +363,6 @@
<QtMoc Include="MapLayerStore.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="LayerTreeViewMenuProvider.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="imageControl.h">
<Filter>Header Files</Filter>
</QtMoc>
@ -354,6 +399,66 @@
<QtMoc Include="DepthCameraWindow.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="SingleLensReflexCameraWindow.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="CommunicationViaTCP.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="CommunicationInterfaceBase.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="PowerControl3D.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="FodisWindow.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="JinspFiberImager.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="GonggaShanRecordCtl.h">
<Filter>Header Files</Filter>
</QtMoc>
<QtMoc Include="TimedDataCollection.h">
<Filter>Header Files\TimedDataCollection</Filter>
</QtMoc>
<QtMoc Include="TaskTreeModel.h">
<Filter>Header Files\TimedDataCollection</Filter>
</QtMoc>
<QtMoc Include="TimedDataCollectionDataStructures.h">
<Filter>Header Files\TimedDataCollection</Filter>
</QtMoc>
<QtMoc Include="LayerTree.h">
<Filter>Header Files\LayerTree</Filter>
</QtMoc>
<QtMoc Include="LayerTreeGroupNode.h">
<Filter>Header Files\LayerTree</Filter>
</QtMoc>
<QtMoc Include="LayerTreeImageNode.h">
<Filter>Header Files\LayerTree</Filter>
</QtMoc>
<QtMoc Include="LayerTreeLayerNode.h">
<Filter>Header Files\LayerTree</Filter>
</QtMoc>
<QtMoc Include="LayerTreeModel.h">
<Filter>Header Files\LayerTree</Filter>
</QtMoc>
<QtMoc Include="LayerTreeNode.h">
<Filter>Header Files\LayerTree</Filter>
</QtMoc>
<QtMoc Include="LayerTreeViewMenuProvider.h">
<Filter>Header Files\LayerTree</Filter>
</QtMoc>
<QtMoc Include="ImagerOperationBase.h">
<Filter>Header Files\hyperImagerCtl</Filter>
</QtMoc>
<QtMoc Include="resononImager.h">
<Filter>Header Files\hyperImagerCtl</Filter>
</QtMoc>
<QtMoc Include="DepthValueLogger.h">
<Filter>Header Files</Filter>
</QtMoc>
</ItemGroup>
<ItemGroup>
<ClInclude Include="imageProcessor.h">
@ -374,9 +479,6 @@
<ClInclude Include="path_tc.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ResononNirImager.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="utility_tc.h">
<Filter>Header Files</Filter>
</ClInclude>
@ -389,10 +491,16 @@
<ClInclude Include="RasterDataProvider.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="RasterRenderer.h">
<ClInclude Include="MultibandRasterRenderer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="LayerTreeView.h">
<ClInclude Include="RasterImageLayer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="RasterRendererBase.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="SinglebandRasterRenderer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="AppSettings.h">
@ -401,6 +509,18 @@
<ClInclude Include="MotorWindowBase.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="PathLine.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="FiberSpectrometerOperationBase.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="LayerTreeView.h">
<Filter>Header Files\LayerTree</Filter>
</ClInclude>
<ClInclude Include="ResononNirImager.h">
<Filter>Header Files\hyperImagerCtl</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<QtUic Include="FocusDialog.ui">
@ -448,6 +568,21 @@
<QtUic Include="DepthCamera.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="SingleLensReflexCamera.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="TimedDataCollection_ui.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="PowerControl3D.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="fodis.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="gonggashanCtl.ui">
<Filter>Form Files</Filter>
</QtUic>
</ItemGroup>
<ItemGroup>
<None Include="cpp.hint" />

View File

@ -83,6 +83,7 @@ void HyperImagerControl::setFrameRate(double frameRate)
ui.FramerateSlider->setValue(frameRate);
updateIntegrationTimeRange(frameRate);
AppSettings::instance().setFrameRate(frameRate);
}
void HyperImagerControl::setIntegrationTime(double integrationTime)
@ -91,12 +92,15 @@ void HyperImagerControl::setIntegrationTime(double integrationTime)
ui.IntegratioinTimeSlider->setValue(integrationTime);
updateFramerateRange(integrationTime);
AppSettings::instance().setIntegrationTime(integrationTime);
}
void HyperImagerControl::setGain(double gain)
{
ui.gain_spinBox->setValue(gain);
ui.GainSlider->setValue(gain);
AppSettings::instance().setGain(gain);
}
void HyperImagerControl::onFramerateSpinBoxEditingFinished()
@ -161,7 +165,7 @@ void HyperImagerControl::onGainSliderReleased()
void HyperImagerControl::updateIntegrationTimeRange(double frameRate)
{
double maxIntegrationTime = 1.0 / frameRate * 1000.0; // 毫秒
double maxIntegrationTime = 1.0 / frameRate * 999.0; // 毫秒
ui.IntegratioinTimeSlider->blockSignals(true);
ui.IntegratioinTimeSlider->setMaximum(maxIntegrationTime);
@ -176,7 +180,7 @@ void HyperImagerControl::updateIntegrationTimeRange(double frameRate)
void HyperImagerControl::updateFramerateRange(double integrationTime)
{
double maxFramerate = 1.0 / (integrationTime / 1000.0); // 积分时间(毫秒)转帧率
double maxFramerate = 1.0 / (integrationTime / 999.0); // 积分时间(毫秒)转帧率
if(maxFramerate > m_frameRateLimit)
{

View File

@ -5,6 +5,7 @@
#include "ui_hyperImagerControl.h"
#include "AspectRatioLabel.h"
#include "AppSettings.h"
class QDoubleSlider;

View File

@ -6,7 +6,7 @@
#include <QPoint>
#include "ImageViewer.h"
#include "RasterLayer.h"
#include "RasterImageLayer.h"
#include "MapTool.h"
@ -264,35 +264,22 @@ qreal Mapcavas::zoomDelta() const
return m_zoomDelta;
}
// new: set associated raster layer
void Mapcavas::setLayers(RasterLayer* layer)
// set associated raster image layer
void Mapcavas::setImageLayer(RasterImageLayer* layer)
{
m_rasterLayer = layer;
m_imageLayer = layer;
}
RasterLayer* Mapcavas::rasterLayer() const
RasterImageLayer* Mapcavas::imageLayer() const
{
return m_rasterLayer;
return m_imageLayer;
}
// new: refresh the map by rendering using the RasterLayer's render method
void Mapcavas::freshmap()
{
if (!m_rasterLayer) return;
if (!m_imageLayer) return;
RasterLayer::RenderParams params = m_rasterLayer->currentRenderParams();
QImage img = m_rasterLayer->render(params);
if (img.isNull()) return;
QPixmap pm = QPixmap::fromImage(img);
SetImage(&pm);
}
void Mapcavas::freshmap(const RasterLayer::RenderParams& params)
{
if (!m_rasterLayer) return;
QImage img = m_rasterLayer->render(params);
QImage img = m_imageLayer->render();
if (img.isNull()) return;
QPixmap pm = QPixmap::fromImage(img);

View File

@ -4,7 +4,8 @@
#include "QGraphicsView"
#include "qlabel.h"
#include <QVector>
#include "RasterLayer.h"
class RasterImageLayer;
class MapTool;
@ -16,7 +17,7 @@ public:
Mapcavas(QWidget* pParent = NULL);
~Mapcavas();
void DisplayFrameNumber(int frameNumber);
@ -47,12 +48,11 @@ public:
void setZoomDelta(qreal delta);
qreal zoomDelta() const;
// new: set raster layer and refresh map
void setLayers(RasterLayer* layer);
// set raster image layer and refresh map
void setImageLayer(RasterImageLayer* layer);
void freshmap();
void freshmap(const RasterLayer::RenderParams& params);
RasterLayer* rasterLayer() const;
RasterImageLayer* imageLayer() const;
// MapTool management
void setMapTool(MapTool* tool);
@ -65,7 +65,7 @@ private:
QGraphicsPixmapItem *m_GraphicsPixmapItemHandle;
QLabel *m_framNumberLabel;//显示实时采集到的帧数
RasterLayer* m_rasterLayer = nullptr; // associated raster layer
RasterImageLayer* m_imageLayer = nullptr; // associated raster image layer
MapTool* m_mapTool = nullptr; // current active map tool
qreal m_translateSpeed; // 平移速度

View File

@ -221,6 +221,16 @@ void ImagerOperationBase::record_white()
void ImagerOperationBase::start_record()
{
QObject* obj = sender();
if (obj)
{
qDebug() << "ImagerOperationBase::start_record, sender name:" << obj->objectName();
}
else
{
qDebug() << "ImagerOperationBase::start_record, sender is null";
}
using namespace std;
//std::cout << "------------------------------------------------------" << std::endl;

348
HPPA/JinspFiberImager.cpp Normal file
View File

@ -0,0 +1,348 @@
//
// Created by 73505 on 2023/5/7.
//
#include <algorithm>
#include "JinspFiberImager.h"
JinspFiberImager::JinspFiberImager(bool bIsUSBMode, std::string ucPortNumber, std::string strDeviceName)
{
m_FiberSpectrometer = NULL;
mUcPortNumber=ucPortNumber;
m_record = false;
m_captureIntervalMilliseconds = 1 * 1000;
qRegisterMetaType<DeviceAttribute>("DeviceAttribute");
qRegisterMetaType<DataFrame>("DataFrame");
}
JinspFiberImager::~JinspFiberImager()
{
}
void JinspFiberImager::connectFiberSpectrometer(QString& SN, QString& pixelCount, QString& wavelengthInfo)
{
using namespace std;
m_FiberSpectrometer = new JinspSpectralmeterControl();
m_FiberSpectrometer->Initialize(false, mUcPortNumber, "OPTOSKY");
DeviceInfo deviceInfo;//
DeviceAttribute deviceAttribute;
m_FiberSpectrometer->GetDeviceInfo(deviceInfo);
m_FiberSpectrometer->GetDeviceAttribute(deviceAttribute);//?????
SN = QString::fromStdString(deviceInfo.strSN);
pixelCount = QString::number(deviceAttribute.iPixels);
wavelengthInfo = QString::number(deviceAttribute.fWaveLengthInNM[0]) + "--" + QString::number(deviceAttribute.fWaveLengthInNM[deviceAttribute.iPixels - 1]);
m_FiberSpectrometer->SetDeviceTemperature(-10);
//设置dn值的最大值(和位深相关)
string qepro = "QEP";//?????????????????????????????????????????????????????????????????????????????????????????
string flame = "FLMS";//?????????????????????????????????????????????????????????????????????????????????????????
if (deviceInfo.strSN.find(qepro) != string::npos)
{
m_MaxValueOfFiberSpectrometer = 200000;
}
else if (deviceInfo.strSN.find(flame) != string::npos)
{
m_MaxValueOfFiberSpectrometer = 65535;
}
else//没有找到匹配的仪器来设置 dn值的最大值
{
m_MaxValueOfFiberSpectrometer = 65535;
}
}
void JinspFiberImager::disconnectFiberSpectrometer()
{
m_record = false;
}
void JinspFiberImager::getDeviceAttribute(DeviceAttribute& deviceAttribute)
{
m_FiberSpectrometer->GetDeviceAttribute(deviceAttribute);
}
void JinspFiberImager::getDeviceInfo(DeviceInfo& deviceInfo)
{
m_FiberSpectrometer->GetDeviceInfo(deviceInfo);
}
void JinspFiberImager::setExposureTime(int iExposureTimeInMS)
{
m_FiberSpectrometer->SetExposureTime(iExposureTimeInMS);
}
void JinspFiberImager::getExposureTime(int &iExposureTimeInMS)
{
m_FiberSpectrometer->GetExposureTime(iExposureTimeInMS);
}
void JinspFiberImager::getDeviceTemperature(float &fTemperature)
{
m_FiberSpectrometer->GetDeviceTemperature(fTemperature);
}
void JinspFiberImager::singleShot(DataFrame &dfData)
{
m_FiberSpectrometer->SingleShot(dfData);
}
void JinspFiberImager::getNonlinearityCoeffs(coeffsFrame &coeffs)
{
printf("This is JinspFiberImager.\n");
}
void JinspFiberImager::recordDark(QString path)
{
//获取设备信息
DeviceAttribute attribute;
DeviceInfo deviceInfo;
getDeviceAttribute(attribute);
getDeviceInfo(deviceInfo);
//采集暗帧
singleShot(m_DarkData);
//输出到csv
QDateTime curDateTime = QDateTime::currentDateTime();
QString currentTime = curDateTime.toString("yyyy_MM_dd_hh_mm_ss");
QString fileName = path + "/" + currentTime + "_" + QString::fromStdString(deviceInfo.strSN) + "_darkSpectral_dn.csv";
std::ofstream outfile(fileName.toStdString().c_str());
for (int i = 0; i < attribute.iPixels; i++)
{
if (i==0)
{
outfile << m_DarkData.usExposureTimeInMS << std::endl;
}
outfile << attribute.fWaveLengthInNM[i] << "," << m_DarkData.lData[i] << std::endl;
}
outfile.close();
}
void JinspFiberImager::recordTarget(int recordTimes, QString path)
{
//获取设备信息
DeviceAttribute attribute;
DeviceInfo deviceInfo;
getDeviceAttribute(attribute);
getDeviceInfo(deviceInfo);
DataFrame integratingSphereData_tmp;
for (int i = 0; i < recordTimes; i++)
{
singleShot(integratingSphereData_tmp);
if (i == 0)//将integratingSphereData_tmp中的曝光时间、温度等信息传给m_IntegratingSphereData
{
m_IntegratingSphereData = integratingSphereData_tmp;
}
else
{
for (int i = 0; i < attribute.iPixels; i++)
{
m_IntegratingSphereData.lData[i] += integratingSphereData_tmp.lData[i];
}
}
}
for (int i = 0; i < attribute.iPixels; i++)
{
m_IntegratingSphereData.lData[i] = m_IntegratingSphereData.lData[i] / recordTimes;
}
//将m_IntegratingSphereData通过信号发送
emit spectalCaptured(attribute, m_IntegratingSphereData);
//输出到csv
QDateTime curDateTime = QDateTime::currentDateTime();
QString currentTime = curDateTime.toString("yyyy_MM_dd_hh_mm_ss");
QString fileName = path + "/" + currentTime + "_" + m_posInfo + "_" + QString::fromStdString(deviceInfo.strSN) + "_integratingSphereSpectral_dn.csv";
std::ofstream outfile(fileName.toStdString().c_str());
for (int i = 0; i < attribute.iPixels; i++)
{
if (i==0)
{
outfile << m_IntegratingSphereData.usExposureTimeInMS << "," << getNanosecondsSinceMidnight() << std::endl;
}
outfile << attribute.fWaveLengthInNM[i] << "," << m_IntegratingSphereData.lData[i] << std::endl;
}
outfile.close();
}
void JinspFiberImager::autoExpose()
{
int allowMaxExposure = 6000;
DeviceAttribute attribute;
getDeviceAttribute(attribute);
const ZZ_U32 maxPixelValue = m_MaxValueOfFiberSpectrometer;
const double targetMinRatio = 0.80;
const double targetMaxRatio = 0.90;
const ZZ_U32 targetMin = maxPixelValue * targetMinRatio;
const ZZ_U32 targetMax = maxPixelValue * targetMaxRatio;
ZZ_U32 thresholdLow = targetMin;
ZZ_U32 thresholdHigh = targetMax;
// 自适应初始曝光时间:先快速探测亮度水平
int exposureTime = 10;
setExposureTime(exposureTime);
DataFrame dataFrame;
singleShot(dataFrame);
ZZ_S32 maxValue = GetMaxValue(dataFrame.lData, attribute.iPixels);
// 探测阶段:快速逼近目标区间
if (maxValue > 0)
{
// 预测达到目标区间所需的曝光时间
ZZ_U32 targetValue = (targetMin + targetMax) / 2;
double predictedRatio = static_cast<double>(targetValue) / maxValue;
// 曝光时间与亮度为对数关系,使用对数预测更准确
double logRatio = log(static_cast<double>(targetValue) / maxValue + 0.001);
int predictedExposure = static_cast<int>(exposureTime * pow(predictedRatio, 0.7));
if (predictedExposure < 1)
predictedExposure = 1;
if (predictedExposure > allowMaxExposure)
predictedExposure = allowMaxExposure;
//predictedExposure = std::clamp(predictedExposure, 1, allowMaxExposure);
exposureTime = predictedExposure;
setExposureTime(exposureTime);
singleShot(dataFrame);
maxValue = GetMaxValue(dataFrame.lData, attribute.iPixels);
}
emit sendExposureTimeSignal(exposureTime);
// 二分查找阶段:在目标区间内精确查找
int lowExposure = 1;
int highExposure = allowMaxExposure;
int iterations = 0;
const int maxIterations = 10;
while (iterations < maxIterations)
{
// 检查是否已在目标区间内
if (maxValue >= thresholdLow && maxValue <= thresholdHigh)
{
std::cout << "自动曝光完成 - 曝光时间:" << exposureTime
<< "ms, 最大值:" << maxValue << std::endl;
break;
}
// 获取当前曝光时间
m_FiberSpectrometer->GetExposureTime(exposureTime);
if (maxValue < thresholdLow)
{
// 曝光不足,增大曝光时间 - 使用二分策略
lowExposure = exposureTime;
int newExposure = (exposureTime + highExposure) / 2;
if (newExposure <= exposureTime)
{
newExposure = exposureTime * 2;
}
exposureTime = std::min(newExposure, allowMaxExposure);
std::cout << "自动曝光 +++ (" << iterations << ") 曝光时间:"
<< exposureTime << "ms, 最大值:" << maxValue << std::endl;
}
else
{
// 曝光过度,减小曝光时间 - 使用二分策略
highExposure = exposureTime;
int newExposure = (lowExposure + exposureTime) / 2;
if (newExposure >= exposureTime) {
newExposure = exposureTime / 2;
}
exposureTime = std::max(newExposure, 1);
std::cout << "自动曝光 --- (" << iterations << ") 曝光时间:"
<< exposureTime << "ms, 最大值:" << maxValue << std::endl;
}
setExposureTime(exposureTime);
singleShot(dataFrame);
maxValue = GetMaxValue(dataFrame.lData, attribute.iPixels);
emit sendExposureTimeSignal(exposureTime);
iterations++;
}
if (iterations >= maxIterations) {
std::cout << "自动曝光达到最大迭代次数,最终曝光时间:"
<< exposureTime << "ms, 最大值:" << maxValue << std::endl;
}
m_iExposureTime = exposureTime;
}
ZZ_S32 JinspFiberImager::GetMaxValue(ZZ_S32 * dark, int number)
{
ZZ_S32 max = 0;
//std::cout << "本帧最大值为" << max << std::endl;
for (size_t i = 0; i < number; i++)
{
// std::cout << dark[i] << std::endl;
if(dark[i]>65535)
continue;
if (dark[i] > max)
{
max = dark[i];
}
}
//std::cout << "本帧最大值为" << max << std::endl;
return max;
}
void JinspFiberImager::setCaptureInterval(int captureIntervalSeconds)
{
m_captureIntervalMilliseconds = captureIntervalSeconds * 1000;
}
void JinspFiberImager::OpenFiberImagerAndRecord(QString posInfo)
{
m_posInfo = posInfo;
//连接光谱仪
QString SN;
QString pixelCount;
QString wavelengthInfo;
connectFiberSpectrometer(SN, pixelCount, wavelengthInfo);
//曝光
emit startExposureSignal();
autoExpose();
emit exposureCompleteSignal(m_iExposureTime);
//采集
m_record = true;
while (m_record)
{
recordTarget(1, AppSettings::instance().FiberImagerDataFolder());
QThread::msleep(m_captureIntervalMilliseconds);
}
std::cout << "close.........." << std::endl;
m_FiberSpectrometer->Close();
}

75
HPPA/JinspFiberImager.h Normal file
View File

@ -0,0 +1,75 @@
//
// Created by 73505 on 2023/5/7.
//
#pragma once
#include <qthread.h>
//#include <QFileDialog>
#include <QDateTime>
#include <QTimer>
#include <iostream>
#include <fstream>
#include "JinspSpectralmeterControl.h"
#include "FiberSpectrometerOperationBase.h"
#include "utility_tc.h"
#include "AppSettings.h"
class JinspFiberImager :public QObject,public FiberSpectrometerOperationBase
{
Q_OBJECT
public:
JinspFiberImager(bool bIsUSBMode, std::string ucPortNumber, std::string strDeviceName);
~JinspFiberImager();
JinspSpectralmeterControl* m_FiberSpectrometer;
void connectFiberSpectrometer(QString& sn, QString& pixelCount, QString& wavelengthInfo);
void disconnectFiberSpectrometer();
void getDeviceAttribute(DeviceAttribute& deviceAttribute);
void getDeviceInfo(DeviceInfo& deviceInfo);
void setExposureTime(int iExposureTimeInMS);
void getExposureTime(int &iExposureTimeInMS);//ok
void getDeviceTemperature(float &fTemperature);//ok
void singleShot(DataFrame &dfData);
void getNonlinearityCoeffs(coeffsFrame &coeffs);
ZZ_S32 GetMaxValue(ZZ_S32 * dark, int number);
bool getRecordStatus() const { return m_record; }
void setCaptureInterval(int captureIntervalSeconds);
// DataFrame m_IntegratingSphereData;
// DataFrame m_DarkData;
protected:
private:
std::string mUcPortNumber;
bool m_record;
int m_captureIntervalMilliseconds;
int m_iExposureTime;
QString m_posInfo;
// ZZ_U32 m_MaxValueOfFiberSpectrometer;
public slots:
void recordDark(QString path);
void recordTarget(int recordTimes, QString path);
void autoExpose();
void OpenFiberImagerAndRecord(QString posInfo);
signals:
void sendExposureTimeSignal(int exposureTime);
void spectalCaptured(DeviceAttribute attribute, DataFrame dataFrame);
void exposureCompleteSignal(int exposureTime);
void startExposureSignal();
};

View File

@ -0,0 +1,85 @@
#include "JinspFiberImagerConfig.h"
#include <QCoreApplication>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QDebug>
const QString JinspFiberImagerConfig::kDefaultPortName = QStringLiteral("COM9");
const QString JinspFiberImagerConfig::kConfigFileName = QStringLiteral("jinsp_fiber_imager_config.json");
JinspFiberImagerConfig::JinspFiberImagerConfig()
: m_configFilePath(QCoreApplication::applicationDirPath() + "/" + kConfigFileName)
, m_portName(kDefaultPortName)
{
loadConfig();
}
JinspFiberImagerConfig& JinspFiberImagerConfig::instance()
{
static JinspFiberImagerConfig s;
return s;
}
QString JinspFiberImagerConfig::portName() const
{
return m_portName;
}
void JinspFiberImagerConfig::setPortName(const QString& port)
{
if (m_portName != port)
{
m_portName = port;
saveConfig();
}
}
void JinspFiberImagerConfig::loadConfig()
{
QFile file(m_configFilePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "JinspFiberImagerConfig: No config file found, using default port:" << kDefaultPortName;
saveConfig();
return;
}
QByteArray jsonData = file.readAll();
file.close();
QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);
if (parseError.error != QJsonParseError::NoError)
{
qWarning() << "JinspFiberImagerConfig: JSON parse error:" << parseError.errorString();
return;
}
QJsonObject obj = doc.object();
if (obj.contains("portName"))
{
m_portName = obj["portName"].toString(kDefaultPortName);
}
}
void JinspFiberImagerConfig::saveConfig()
{
QJsonObject obj;
obj["portName"] = m_portName;
QJsonDocument doc(obj);
QFile file(m_configFilePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
qWarning() << "JinspFiberImagerConfig: Failed to open config file for writing:" << m_configFilePath;
return;
}
file.write(doc.toJson(QJsonDocument::Indented));
file.close();
qDebug() << "JinspFiberImagerConfig: Config saved to" << m_configFilePath;
}

View File

@ -0,0 +1,26 @@
#pragma once
#include <QString>
class JinspFiberImagerConfig
{
public:
static JinspFiberImagerConfig& instance();
QString portName() const;
void setPortName(const QString& port);
static const QString kDefaultPortName;
static const QString kConfigFileName;
private:
JinspFiberImagerConfig();
JinspFiberImagerConfig(const JinspFiberImagerConfig&) = delete;
JinspFiberImagerConfig& operator=(const JinspFiberImagerConfig&) = delete;
QString m_configFilePath;
QString m_portName;
void loadConfig();
void saveConfig();
};

View File

@ -0,0 +1,31 @@
#include "LayerTreeImageNode.h"
#include "RasterImageLayer.h"
LayerTreeImageNode::LayerTreeImageNode(RasterImageLayer* imageLayer,
const QString& name,
QWidget* widget,
QObject* parent)
: LayerTreeNode(name, parent)
, m_imageLayer(imageLayer)
, m_widget(widget)
{
}
LayerTreeImageNode::~LayerTreeImageNode()
{
}
LayerTreeNode::Type LayerTreeImageNode::type() const
{
return Type::Image;
}
QWidget* LayerTreeImageNode::widget() const
{
return m_widget;
}
void LayerTreeImageNode::setWidget(QWidget* widget)
{
m_widget = widget;
}

30
HPPA/LayerTreeImageNode.h Normal file
View File

@ -0,0 +1,30 @@
#pragma once
#include "LayerTreeNode.h"
#include <memory>
class QWidget;
class RasterImageLayer;
class LayerTreeImageNode : public LayerTreeNode
{
Q_OBJECT
public:
explicit LayerTreeImageNode(RasterImageLayer* imageLayer,
const QString& name,
QWidget* widget = nullptr,
QObject* parent = nullptr);
~LayerTreeImageNode();
Type type() const override;
RasterImageLayer* imageLayer() const { return m_imageLayer; }
QWidget* widget() const;
void setWidget(QWidget* widget);
private:
RasterImageLayer* m_imageLayer;
QWidget* m_widget = nullptr;
};

View File

@ -1,7 +1,7 @@
#include "LayerTreeLayerNode.h"
LayerTreeLayer::LayerTreeLayer(MapLayer* layer, QObject* parent)
: LayerTreeNode(layer ? layer->name() : QString(), parent), m_layer(layer)
: LayerTreeGroup(layer ? layer->name() : QString(), parent), m_layer(layer)
{
}

View File

@ -1,5 +1,5 @@
#pragma once
#include "LayerTreeNode.h"
#include "LayerTreeGroupNode.h"
#include "MapLayer.h"
/**
@ -7,13 +7,13 @@
* - 基类为 LayerTreeNode
* - 持有一个 MapLayer 指针(不拥有)
*/
class LayerTreeLayer : public LayerTreeNode
class LayerTreeLayer : public LayerTreeGroup
{
Q_OBJECT
public:
explicit LayerTreeLayer(MapLayer* layer, QObject* parent = nullptr);
Type type() const override;
Type type() const;
void setMapLayer(MapLayer* layer);
MapLayer* mapLayer() const;

View File

@ -133,7 +133,7 @@ LayerTreeNode* LayerTreeModel::addGroup(LayerTreeNode* parent, const QString& na
return g;
}
LayerTreeNode* LayerTreeModel::addLayer(LayerTreeNode* parent, LayerTreeLayer* layerNode, const QIcon& icon)
LayerTreeNode* LayerTreeModel::addLayer(LayerTreeNode* parent, LayerTreeNode* layerNode, const QIcon& icon)
{
if (!parent) parent = m_tree;
if (!layerNode) return nullptr;

View File

@ -34,7 +34,7 @@ public:
LayerTreeNode* root() const;
LayerTreeNode* addGroup(LayerTreeNode* parent, const QString& name, const QIcon& icon = QIcon());
LayerTreeNode* addLayer(LayerTreeNode* parent, LayerTreeLayer* layerNode, const QIcon& icon = QIcon());
LayerTreeNode* addLayer(LayerTreeNode* parent, LayerTreeNode* layerNode, const QIcon& icon = QIcon());
void setCascadeCheckEnabled(bool enabled);
bool cascadeCheckEnabled() const;

View File

@ -19,7 +19,7 @@ class LayerTreeNode : public QObject
{
Q_OBJECT
public:
enum class Type { Group, Layer };
enum class Type { Group, Layer, Image };
explicit LayerTreeNode(const QString& name,
QObject* parent = nullptr);

View File

@ -36,9 +36,20 @@ QMenu* LayerTreeViewMenuProvider::createContextMenu()
if (node->type() == LayerTreeNode::Type::Layer)
{
QAction* removeAction = new QAction(QStringLiteral("移除图层"), menu);
connect(removeAction, &QAction::triggered, HPPA::instance(), &HPPA::removeLayerByTreeIndex);
menu->addAction(removeAction);
QAction* removeLayerAction = new QAction(QStringLiteral("移除图层"), menu);
connect(removeLayerAction, &QAction::triggered, HPPA::instance(), &HPPA::removeLayerByTreeIndex);
QAction* showColorImageAction = new QAction(QStringLiteral("显示彩色图像"), menu);
connect(showColorImageAction, &QAction::triggered, HPPA::instance(), &HPPA::showColorImageByTreeIndex);
menu->addAction(removeLayerAction);
menu->addAction(showColorImageAction);
}
else if (node->type() == LayerTreeNode::Type::Image)
{
QAction* removeImageAction = new QAction(QStringLiteral("移除图像"), menu);
connect(removeImageAction, &QAction::triggered, HPPA::instance(), &HPPA::removeImageByTreeIndex);
menu->addAction(removeImageAction);
}
else if (node->type() == LayerTreeNode::Type::Group)
{

View File

@ -1,60 +1,137 @@
#include "MapLayerStore.h"
#include "MapLayer.h"
#include "RasterImageLayer.h"
#include <QFileInfo>
#include <QWidget>
MapLayerStore::MapLayerStore(QObject* parent)
: QObject(parent)
{
int a = 1;
}
void MapLayerStore::addLayer(MapLayer* layer, QWidget* widget)
void MapLayerStore::addLayer(MapLayer* layer)
{
if (!layer) return;
MapLayer* raw = layer;
m_layers.emplace_back(std::shared_ptr<MapLayer>(layer));
if (widget)
m_layerWidgets[raw] = widget;
emit layerAdded(raw);
int index = (int)m_layers.size();
LayerEntry entry;
entry.mapLayer.reset(layer);
m_layers.push_back(std::move(entry));
m_mapLayerIndex[layer] = index;
emit layerAdded(layer);
}
void MapLayerStore::addImageLayer(MapLayer* mapLayer, RasterImageLayer* imageLayer, QWidget* widget)
{
if (!mapLayer || !imageLayer) return;
LayerEntry* entry = findLayerEntry(mapLayer);
if (!entry) return;
entry->imageLayers.push_back({std::unique_ptr<RasterImageLayer>(imageLayer), widget});
emit imageLayerAdded(imageLayer);
}
void MapLayerStore::removeLayer(MapLayer* layer)
{
if (!layer) return;
for (auto it = m_layers.begin(); it != m_layers.end(); ++it) {
if (it->get() == layer) {
emit layerAboutToBeRemoved(layer);
m_layers.erase(it);
m_layerWidgets.erase(layer);
return;
auto it = m_mapLayerIndex.find(layer);
if (it == m_mapLayerIndex.end()) return;
int index = it->second;
if (index < 0 || index >= (int)m_layers.size()) return;
LayerEntry& entry = m_layers[index];
// Delete all associated widgets
for (auto& imgEntry : entry.imageLayers) {
if (imgEntry.widget) {
delete imgEntry.widget;
}
}
entry.imageLayers.clear();
emit layerAboutToBeRemoved(layer);
m_layers.erase(m_layers.begin() + index);//?????????????????????
m_mapLayerIndex.erase(it);
// Rebuild index for layers after removed one
for (int i = index; i < (int)m_layers.size(); ++i) {
m_mapLayerIndex[m_layers[i].mapLayer.get()] = i;
}
}
void MapLayerStore::removeImageLayer(RasterImageLayer* imageLayer)//可以优化:RasterImageLayer包含一个指向所属MapLayer的指针,这样就不需要遍历所有图层来找到它了
{
if (!imageLayer) return;
for (auto& entry : m_layers) {
for (auto it = entry.imageLayers.begin(); it != entry.imageLayers.end(); ++it) {
if (it->imageLayer.get() == imageLayer) {
emit imageLayerAboutToBeRemoved(imageLayer);
if (it->widget) {
//delete it->widget;//在调用此函数的地方已经删除了widget了,这里不需要再删除一次了
}
entry.imageLayers.erase(it);
return;
}
}
}
}
void MapLayerStore::removeLayerByName(const QString& name)
{
for (auto it = m_layers.begin(); it != m_layers.end(); ++it) {
if ((*it)->name() == name) {
MapLayer* raw = it->get();
emit layerAboutToBeRemoved(raw);
m_layers.erase(it);
m_layerWidgets.erase(raw);
for (auto& entry : m_layers) {
if (entry.mapLayer->name() == name) {
removeLayer(entry.mapLayer.get());
return;
}
}
}
bool MapLayerStore::containsLayer(const QString& url, bool isAbsolutePath) const
{
QFileInfo fi(url);
QString fileName = fi.completeBaseName();
if (!isAbsolutePath) {
return getLayer(fileName) != nullptr;
}
for (const auto& entry : m_layers) {
if (entry.mapLayer->dataPath() == url)
return true;
}
return false;
}
MapLayer* MapLayerStore::getLayer(const QString& name) const
{
for (const auto& l : m_layers) {
if (l->name() == name) return l.get();
for (const auto& entry : m_layers) {
if (entry.mapLayer->name() == name)
return entry.mapLayer.get();
}
return nullptr;
}
MapLayer* MapLayerStore::getLayerAt(int index) const
{
if (index < 0 || index >= (int)m_layers.size()) return nullptr;
return m_layers[index].get();
if (index < 0 || index >= (int)m_layers.size())
return nullptr;
return m_layers[index].mapLayer.get();
}
MapLayer* MapLayerStore::getLayerByAbsolutePath(const QString& absolutePath) const
{
for (const auto& entry : m_layers) {
if (entry.mapLayer->dataPath() == absolutePath)
return entry.mapLayer.get();
}
return nullptr;
}
int MapLayerStore::layerCount() const
@ -62,31 +139,129 @@ int MapLayerStore::layerCount() const
return (int)m_layers.size();
}
QWidget* MapLayerStore::widgetForLayer(MapLayer* layer) const
RasterImageLayer* MapLayerStore::getImageLayer(MapLayer* mapLayer, int index) const
{
auto it = m_layerWidgets.find(layer);
if (it == m_layerWidgets.end()) return nullptr;
return it->second;
const LayerEntry* entry = findLayerEntry(mapLayer);
if (!entry) return nullptr;
if (index < 0 || index >= (int)entry->imageLayers.size())
return nullptr;
return entry->imageLayers[index].imageLayer.get();
}
int MapLayerStore::imageLayerCount(MapLayer* mapLayer) const
{
const LayerEntry* entry = findLayerEntry(mapLayer);
if (!entry) return 0;
return (int)entry->imageLayers.size();
}
std::vector<RasterImageLayer*> MapLayerStore::getAllImageLayers() const
{
std::vector<RasterImageLayer*> result;
for (const auto& entry : m_layers) {
for (const auto& imgEntry : entry.imageLayers) {
if (imgEntry.imageLayer)
result.push_back(imgEntry.imageLayer.get());
}
}
return result;
}
QWidget* MapLayerStore::widgetForImageLayer(RasterImageLayer* imageLayer) const
{
for (const auto& entry : m_layers) {
for (const auto& imgEntry : entry.imageLayers) {
if (imgEntry.imageLayer.get() == imageLayer)
return imgEntry.widget;
}
}
return nullptr;
}
QWidget* MapLayerStore::widgetForLayer(MapLayer* layer) const//需要修改??????????????????????????????????????????????
{
const LayerEntry* entry = findLayerEntry(layer);
if (!entry || entry->imageLayers.empty())
return nullptr;
return entry->imageLayers.front().widget;
}
QWidget* MapLayerStore::widgetForLayer(const QString& absolutePath) const
{
for (const auto& sp : m_layers) {
if (sp && sp->dataPath() == absolutePath) {
MapLayer* raw = sp.get();
auto it = m_layerWidgets.find(raw);
if (it != m_layerWidgets.end()) return it->second;
for (const auto& entry : m_layers) {
if (entry.mapLayer->dataPath() == absolutePath) {
if (!entry.imageLayers.empty())
return entry.imageLayers.front().widget;
return nullptr;
}
}
return nullptr;
}
MapLayer* MapLayerStore::layerForWidget(QWidget* widget) const
std::vector<QWidget*> MapLayerStore::widgetsForMapLayer(MapLayer* mapLayer) const
{
if (!widget) return nullptr;
for (const auto& kv : m_layerWidgets) {
if (kv.second == widget) return kv.first;
std::vector<QWidget*> result;
const LayerEntry* entry = findLayerEntry(mapLayer);
if (!entry) return result;
for (const auto& imgEntry : entry->imageLayers) {
if (imgEntry.widget)
result.push_back(imgEntry.widget);
}
return result;
}
MapLayer* MapLayerStore::mapLayerForImageLayer(RasterImageLayer* imageLayer) const
{
for (const auto& entry : m_layers) {
for (const auto& imgEntry : entry.imageLayers) {
if (imgEntry.imageLayer.get() == imageLayer)
return entry.mapLayer.get();
}
}
return nullptr;
}
MapLayer* MapLayerStore::mapLayerForWidget(QWidget* widget) const
{
if (!widget) return nullptr;
for (const auto& entry : m_layers) {
for (const auto& imgEntry : entry.imageLayers) {
if (imgEntry.widget == widget)
return entry.mapLayer.get();
}
}
return nullptr;
}
RasterImageLayer* MapLayerStore::imageLayerForWidget(QWidget* widget) const
{
if (!widget) return nullptr;
for (const auto& entry : m_layers) {
for (const auto& imgEntry : entry.imageLayers) {
if (imgEntry.widget == widget)
return imgEntry.imageLayer.get();
}
}
return nullptr;
}
MapLayerStore::LayerEntry* MapLayerStore::findLayerEntry(MapLayer* mapLayer)
{
auto it = m_mapLayerIndex.find(mapLayer);
if (it == m_mapLayerIndex.end()) return nullptr;
int index = it->second;
if (index < 0 || index >= (int)m_layers.size()) return nullptr;
return &m_layers[index];
}
const MapLayerStore::LayerEntry* MapLayerStore::findLayerEntry(MapLayer* mapLayer) const
{
auto it = m_mapLayerIndex.find(mapLayer);
if (it == m_mapLayerIndex.end()) return nullptr;
int index = it->second;
if (index < 0 || index >= (int)m_layers.size()) return nullptr;
return &m_layers[index];
}

View File

@ -7,45 +7,66 @@
#include <unordered_map>
class MapLayer;
class RasterImageLayer;
class QWidget;
class MapLayerStore : public QObject
{
Q_OBJECT
struct ImageLayerEntry {
std::unique_ptr<RasterImageLayer> imageLayer;
QWidget* widget;
};
struct LayerEntry {
std::unique_ptr<MapLayer> mapLayer;
std::vector<ImageLayerEntry> imageLayers;
};
public:
explicit MapLayerStore(QObject* parent = nullptr);
~MapLayerStore() override = default;
// Take ownership of the layer (store will own and manage its lifetime)
// Now also accept the associated QWidget so UI widget can be retrieved by layer pointer
void addLayer(MapLayer* layer, QWidget* widget = nullptr);
// Remove by pointer or by name. Destruction happens when removed from store.
public slots:
// Layer management
void addLayer(MapLayer* layer);
void removeLayer(MapLayer* layer);
void removeLayerByName(const QString& name);
bool containsLayer(const QString& url, bool isAbsolutePath = true) const;
// Queries
MapLayer* getLayer(const QString& name) const;
MapLayer* getLayerByAbsolutePath(const QString& absolutePath) const;
MapLayer* getLayerAt(int index) const;
int layerCount() const;
// Get associated widget for a layer (or nullptr if none)
QWidget* widgetForLayer(MapLayer* layer) const;
// Get associated widget by layer absolute data path
QWidget* widgetForLayer(const QString& absolutePath) const;
// ImageLayer management
void addImageLayer(MapLayer* mapLayer, RasterImageLayer* imageLayer, QWidget* widget);
void removeImageLayer(RasterImageLayer* imageLayer);
RasterImageLayer* getImageLayer(MapLayer* mapLayer, int index) const;
int imageLayerCount(MapLayer* mapLayer) const;
std::vector<RasterImageLayer*> getAllImageLayers() const;
// Reverse lookup: find the MapLayer associated with a given widget (or nullptr)
MapLayer* layerForWidget(QWidget* widget) const;
// Widget queries
QWidget* widgetForImageLayer(RasterImageLayer* imageLayer) const;
QWidget* widgetForLayer(MapLayer* layer) const;
QWidget* widgetForLayer(const QString& absolutePath) const;
std::vector<QWidget*> widgetsForMapLayer(MapLayer* mapLayer) const;
// Reverse lookups
MapLayer* mapLayerForImageLayer(RasterImageLayer* imageLayer) const;
MapLayer* mapLayerForWidget(QWidget* widget) const;
RasterImageLayer* imageLayerForWidget(QWidget* widget) const;
signals:
void layerAdded(MapLayer* layer);
// Emitted just before the layer is destroyed/removed from store
void layerAboutToBeRemoved(MapLayer* layer);
void imageLayerAdded(RasterImageLayer* imageLayer);
void imageLayerAboutToBeRemoved(RasterImageLayer* imageLayer);
private:
// store shared ownership so other parts can keep raw pointers safely (or use QPointer)
std::vector<std::shared_ptr<MapLayer>> m_layers;
// mapping from raw MapLayer pointer to associated QWidget*
std::unordered_map<MapLayer*, QWidget*> m_layerWidgets;
LayerEntry* findLayerEntry(MapLayer* mapLayer);
const LayerEntry* findLayerEntry(MapLayer* mapLayer) const;
std::vector<LayerEntry> m_layers;
std::unordered_map<MapLayer*, int> m_mapLayerIndex;
};

View File

@ -41,10 +41,10 @@ void MapToolSpectral::canvasMousePressEvent(QMouseEvent* e)
const int x = static_cast<int>(std::floor(scenePt.x()));
const int y = static_cast<int>(std::floor(scenePt.y()));
RasterLayer* rl = canvas()->rasterLayer();
auto* imageLayer = canvas()->imageLayer();
RasterLayer* rl = imageLayer ? imageLayer->layer() : nullptr;
if (rl && rl->isValidPixel(x, y))
{
// Place crosshair at pixel center
canvas()->updateCrosshair(x + 0.5, y + 0.5);
QVector<double> wavelengths;

View File

@ -4,6 +4,8 @@
#include "MapTool.h"
#include <QVector>
#include "RasterImageLayer.h"
class QGraphicsLineItem;
class MapToolSpectral : public MapTool

View File

@ -0,0 +1,207 @@
#include "MultibandRasterRenderer.h"
#include "RasterDataProvider.h"
#include <QDebug>
#include <algorithm>
#include <cmath>
MultibandRasterRenderer::MultibandRasterRenderer(RasterDataProvider* provider)
: RasterRendererBase(provider)
{
}
void MultibandRasterRenderer::stretchTo8bit(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal)
{
size_t n = in.size();
out.resize(n);
if (maxVal <= minVal)
{
std::fill(out.begin(), out.end(), 0);
return;
}
float denom = 1.0f / (maxVal - minVal);
for (size_t i = 0; i < n; ++i)
{
float v = (in[i] - minVal) * denom;
v = std::min(std::max(v, 0.0f), 1.0f);
out[i] = static_cast<unsigned char>(v * 255.0f);
}
}
void MultibandRasterRenderer::computeHistogram(const std::vector<float>& in, std::vector<long>& hist, float& minVal, float& maxVal)
{
if (in.empty())
{
minVal = 0.0f;
maxVal = 1.0f;
hist.clear();
return;
}
minVal = in[0];
maxVal = in[0];
for (size_t i = 0; i < in.size(); ++i)
{
if (in[i] < minVal) minVal = in[i];
if (in[i] > maxVal) maxVal = in[i];
}
if (maxVal <= minVal)
{
hist.assign(256, 0);
hist[0] = static_cast<long>(in.size());
minVal = 0.0f;
maxVal = 1.0f;
return;
}
const int numBins = 65536;
hist.assign(numBins, 0);
for (size_t i = 0; i < in.size(); ++i)
{
++hist[static_cast<int>(in[i])];
}
}
void MultibandRasterRenderer::findStretchValuesByRatio(const std::vector<long>& hist, float ratio, float& minVal, float& maxVal)
{
if (hist.empty()) return;
long totalPixels = 0;
for (size_t i = 0; i < hist.size(); ++i)
{
totalPixels += hist[i];
}
if (totalPixels == 0) return;
long targetCount = static_cast<long>(totalPixels * ratio);
long cumulative = 0;
for (size_t i = 0; i < hist.size(); ++i)
{
cumulative += hist[i];
if (cumulative >= targetCount)
{
minVal = static_cast<float>(i);
break;
}
}
cumulative = 0;
for (size_t i = hist.size(); i > 0; --i)
{
cumulative += hist[i - 1];
if (cumulative >= targetCount)
{
maxVal = static_cast<float>(i - 1);
break;
}
}
}
void MultibandRasterRenderer::stretchTo8bitByHistogram(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal)
{
size_t n = in.size();
out.resize(n);
if (maxVal <= minVal)
{
std::fill(out.begin(), out.end(), 0);
return;
}
float denom = 1.0f / (maxVal - minVal);
for (size_t i = 0; i < n; ++i)
{
float v = (in[i] - minVal) * denom;
v = std::min(std::max(v, 0.0f), 1.0f);
out[i] = static_cast<unsigned char>(v * 255.0f);
}
}
QImage MultibandRasterRenderer::render()
{
if (!m_provider) return QImage();
int bands = m_provider->bandCount();
int w = m_provider->width();
int h = m_provider->height();
if (w <= 0 || h <= 0) return QImage();
// Find nearest bands for requested wavelengths if wavelengths available
std::vector<double> wavelengths = m_provider->bandWavelengths();
auto chooseBandIndexForWave = [&](double wave)->int {
if (wavelengths.empty()) {
// fallback: select R,G,B as first three bands
if (bands >= 3) return (wave==m_params.rWave?0:(wave==m_params.gWave?1:2));
if (bands >= 1) return 0;
return -1;
}
int best = -1; double bestDiff = 1e12;
for (int i = 0; i < (int)wavelengths.size(); ++i) {
if (wavelengths[i] < 0) continue;
double d = std::abs(wavelengths[i] - wave);
if (d < bestDiff) { bestDiff = d; best = i; }
}
if (best >= 0) return best;
// fallback
return std::min(2, bands-1);
};
int rIdx = chooseBandIndexForWave(m_params.rWave);
int gIdx = chooseBandIndexForWave(m_params.gWave);
int bIdx = chooseBandIndexForWave(m_params.bWave);
std::vector<float> rbuf, gbuf, bbuf;
if (rIdx >= 0) m_provider->readBandAsFloat(rIdx, rbuf);
if (gIdx >= 0) m_provider->readBandAsFloat(gIdx, gbuf);
if (bIdx >= 0) m_provider->readBandAsFloat(bIdx, bbuf);
std::vector<unsigned char> r8, g8, b8;
// Compute histogram-based stretch for each channel
float ratio = m_stretchRatio;
// R channel stretch
if (!rbuf.empty()) {
std::vector<long> rHist;
float rMin, rMax;
computeHistogram(rbuf, rHist, rMin, rMax);
float rStretchMin = rMin, rStretchMax = rMax;
findStretchValuesByRatio(rHist, ratio, rStretchMin, rStretchMax);
stretchTo8bitByHistogram(rbuf, r8, rStretchMin, rStretchMax);
}
// G channel stretch
if (!gbuf.empty()) {
std::vector<long> gHist;
float gMin, gMax;
computeHistogram(gbuf, gHist, gMin, gMax);
float gStretchMin = gMin, gStretchMax = gMax;
findStretchValuesByRatio(gHist, ratio, gStretchMin, gStretchMax);
stretchTo8bitByHistogram(gbuf, g8, gStretchMin, gStretchMax);
}
// B channel stretch
if (!bbuf.empty()) {
std::vector<long> bHist;
float bMin, bMax;
computeHistogram(bbuf, bHist, bMin, bMax);
float bStretchMin = bMin, bStretchMax = bMax;
findStretchValuesByRatio(bHist, ratio, bStretchMin, bStretchMax);
stretchTo8bitByHistogram(bbuf, b8, bStretchMin, bStretchMax);
}
QImage out(w, h, QImage::Format_RGB888);
for (int y = 0; y < h; ++y) {
unsigned char* scan = out.scanLine(y);
for (int x = 0; x < w; ++x) {
int idx = y * w + x;
unsigned char rc = (r8.size() > (size_t)idx) ? r8[idx] : 0;
unsigned char gc = (g8.size() > (size_t)idx) ? g8[idx] : 0;
unsigned char bc = (b8.size() > (size_t)idx) ? b8[idx] : 0;
scan[x*3 + 0] = rc;
scan[x*3 + 1] = gc;
scan[x*3 + 2] = bc;
}
}
return out;
}

View File

@ -0,0 +1,39 @@
#pragma once
#include "RasterRendererBase.h"
#include "RasterRenderParams.h"
#include <vector>
#include <memory>
class RasterDataProvider;
class MultibandRasterRenderer : public RasterRendererBase
{
public:
explicit MultibandRasterRenderer(RasterDataProvider* provider);
QImage render() override;
// Parameter access
MultibandRenderParams params() const { return m_params; }
void setParams(const MultibandRenderParams& params) { m_params = params; }
void setStretchRatio(float ratio) { m_stretchRatio = ratio; }
float stretchRatio() const { return m_stretchRatio; }
private:
MultibandRenderParams m_params;
float m_stretchRatio = 0.02f;
// Helper to map float buffer to 8-bit with min/max stretch
static void stretchTo8bit(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal);
// Helper to compute histogram from float buffer
static void computeHistogram(const std::vector<float>& in, std::vector<long>& hist, float& minVal, float& maxVal);
// Helper to find stretch values by cumulative histogram ratio
static void findStretchValuesByRatio(const std::vector<long>& hist, float ratio, float& minVal, float& maxVal);
// Helper to stretch to 8-bit using histogram-based stretch
static void stretchTo8bitByHistogram(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal);
};

View File

@ -16,6 +16,19 @@ OneMotorControl::OneMotorControl(QWidget* parent) : QDialog(parent)
connect(this->ui.zero_start_btn, SIGNAL(released()), this, SLOT(zeroStart()));
connect(this->ui.rangeMeasurement_btn, SIGNAL(pressed()), this, SLOT(onx_rangeMeasurement()));
// 从 AppSettings 读取速度参数
AppSettings& settings = AppSettings::instance();
ui.speed_lineEdit->setText(QString::number(settings.scanSpeed()));
ui.return_speed_lineEdit->setText(QString::number(settings.returnSpeed()));
// 连接信号,当控件数值变化时保存到 AppSettings
connect(ui.speed_lineEdit, &QLineEdit::editingFinished, [this]() {
AppSettings::instance().setScanSpeed(ui.speed_lineEdit->text().toDouble());
});
connect(ui.return_speed_lineEdit, &QLineEdit::editingFinished, [this]() {
AppSettings::instance().setReturnSpeed(ui.return_speed_lineEdit->text().toDouble());
});
}
OneMotorControl::~OneMotorControl()
@ -25,13 +38,21 @@ OneMotorControl::~OneMotorControl()
}
void OneMotorControl::onConnectMotor()
{
connectMotor(true);
}
void OneMotorControl::connectMotor(bool isNotification)
{
if (getMotorsConnectionStatus())
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("马达已连接!"));
msgBox.exec();
if (isNotification)
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("马达已连接!"));
msgBox.exec();
}
return;
}
@ -202,8 +223,14 @@ void OneMotorControl::record_white()
void OneMotorControl::run()
{
if (m_coordinator)//当高光谱相机停止采集后,马达还未回到原点时,上次任务的m_coordinator还没有被销毁
{
onSequenceComplete(0);
}
qRegisterMetaType<OneMotionCapturePathLine>("OneMotionCapturePathLine");
m_coordinator = new OneMotionCaptureCoordinator(m_multiAxisController, m_Imager);
m_coordinator->setObjectName("testOneMotionCaptureCoordinator");
connect(this, SIGNAL(start(OneMotionCapturePathLine)), m_coordinator, SLOT(startStepMotion(OneMotionCapturePathLine)));
connect(this, SIGNAL(stopStepMotionSignal()), m_coordinator, SLOT(stopStepMotion()));
@ -240,3 +267,278 @@ bool OneMotorControl::getMotorsConnectionStatus()
{
return m_xMotorConnectionStatus;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
OneMotorControl_LiftingPlatform::OneMotorControl_LiftingPlatform(QWidget* parent) : QDialog(parent)
{
ui.setupUi(this);
connect(this->ui.connect_btn, SIGNAL(pressed()), this, SLOT(onConnectMotor()));
connect(this->ui.right_btn, SIGNAL(pressed()), this, SLOT(onxMotorRight()));
connect(this->ui.right_btn, SIGNAL(released()), this, SLOT(onxMotorStop()));
connect(this->ui.left_btn, SIGNAL(pressed()), this, SLOT(onxMotorLeft()));
connect(this->ui.left_btn, SIGNAL(released()), this, SLOT(onxMotorStop()));
connect(this->ui.move2loc_pushButton, SIGNAL(pressed()), this, SLOT(onxMove2Loc()));
connect(this->ui.zero_start_btn, SIGNAL(released()), this, SLOT(zeroStart()));
connect(this->ui.rangeMeasurement_btn, SIGNAL(pressed()), this, SLOT(onx_rangeMeasurement()));
// 从 AppSettings 读取速度参数
AppSettings& settings = AppSettings::instance();
ui.speed_lineEdit->setText(QString::number(settings.scanSpeed()));
ui.return_speed_lineEdit->setText(QString::number(settings.returnSpeed()));
// 连接信号,当控件数值变化时保存到 AppSettings
connect(ui.speed_lineEdit, &QLineEdit::editingFinished, [this]() {
AppSettings::instance().setScanSpeed(ui.speed_lineEdit->text().toDouble());
});
connect(ui.return_speed_lineEdit, &QLineEdit::editingFinished, [this]() {
AppSettings::instance().setReturnSpeed(ui.return_speed_lineEdit->text().toDouble());
});
}
OneMotorControl_LiftingPlatform::~OneMotorControl_LiftingPlatform()
{
m_motorThread.quit();
m_motorThread.wait();
}
void OneMotorControl_LiftingPlatform::onConnectMotor()
{
connectMotor(true);
}
void OneMotorControl_LiftingPlatform::connectMotor(bool isNotification)
{
if (getMotorsConnectionStatus())
{
if (isNotification)
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("马达已连接!"));
msgBox.exec();
}
return;
}
if (m_multiAxisController != nullptr)
{
disconnect(m_multiAxisController, SIGNAL(broadcastLocationSignal(std::vector<double>)), this, SLOT(display_x_loc(std::vector<double>)));
disconnect(this, SIGNAL(moveSignal(int, bool, double, int)), m_multiAxisController, SLOT(move(int, bool, double, int)));
disconnect(this, SIGNAL(move2LocSignal(int, double, double, int)), m_multiAxisController, SLOT(moveTo(int, double, double, int)));
disconnect(this, SIGNAL(stopSignal(int)), m_multiAxisController, SLOT(stop(int)));
disconnect(this, SIGNAL(zeroStartSignal(int)), m_multiAxisController, SLOT(zeroStart(int)));
disconnect(this, SIGNAL(rangeMeasurement(int, double, int)), m_multiAxisController, SLOT(rangeMeasurement(int, double, int)));
disconnect(this, SIGNAL(testConnectivitySignal(int, int)), m_multiAxisController, SLOT(testConnectivity(int, int)));
disconnect(m_multiAxisController, SIGNAL(broadcastConnectivity(std::vector<int>)), this, SLOT(display_motors_connectivity(std::vector<int>)));
m_motorThread.quit();
m_motorThread.wait();
m_multiAxisController = nullptr;
}
try
{
FileOperation* fileOperation = new FileOperation();
string directory = fileOperation->getDirectoryOfExe();
QString configFilePath = QString::fromStdString(directory) + "\\oneMotorConfigFile_LiftingPlatform.cfg";
m_multiAxisController = new IrisMultiMotorController(configFilePath);
}
catch (std::exception const& e)
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("请连接马达!"));
msgBox.exec();
return;
}
m_multiAxisController->moveToThread(&m_motorThread);
connect(&m_motorThread, SIGNAL(finished()), m_multiAxisController, SLOT(deleteLater()));
connect(m_multiAxisController, SIGNAL(broadcastLocationSignal(std::vector<double>)), this, SLOT(display_x_loc(std::vector<double>)));
connect(this, SIGNAL(moveSignal(int, bool, double, int)), m_multiAxisController, SLOT(move(int, bool, double, int)));
connect(this, SIGNAL(move2LocSignal(int, double, double, int)), m_multiAxisController, SLOT(moveTo(int, double, double, int)));
connect(this, SIGNAL(stopSignal(int)), m_multiAxisController, SLOT(stop(int)));
connect(this, SIGNAL(zeroStartSignal(int)), m_multiAxisController, SLOT(zeroStart(int)));
connect(this, SIGNAL(rangeMeasurement(int, double, int)), m_multiAxisController, SLOT(rangeMeasurement(int, double, int)));
connect(this, SIGNAL(testConnectivitySignal(int, int)), m_multiAxisController, SLOT(testConnectivity(int, int)));
connect(m_multiAxisController, SIGNAL(broadcastConnectivity(std::vector<int>)), this, SLOT(display_motors_connectivity(std::vector<int>)));
m_motorThread.start();
emit testConnectivitySignal(0, 1000);
}
void OneMotorControl_LiftingPlatform::display_x_loc(std::vector<double> loc)
{
double tmp = round(loc[0] * 100) / 100;
this->ui.realTimeLoc_lineEdit->setText(QString::number(tmp));
emit broadcastLocationSignal(loc);
}
void OneMotorControl_LiftingPlatform::display_motors_connectivity(std::vector<int> connectivity)
{
//std::cout << "-----------------------------------"<<connectivity.size()<< std::endl;
if (connectivity[0])
{
m_xMotorConnectionStatus = true;
this->ui.motor_state_label->setStyleSheet(R"(
QLabel
{
background-color: #08FACE;
border-radius: 4px;
}
)");
}
else
{
m_xMotorConnectionStatus = false;
this->ui.motor_state_label->setStyleSheet(R"(
QLabel
{
background-color: red;
border-radius: 4px;
}
)");
}
if (getMotorsConnectionStatus())
{
this->ui.connect_btn->setText(QString::fromLocal8Bit("已连接"));
}
else
{
this->ui.connect_btn->setText(QString::fromLocal8Bit("重新连接"));
}
}
void OneMotorControl_LiftingPlatform::zeroStart()
{
zeroStartSignal(0);
}
void OneMotorControl_LiftingPlatform::onx_rangeMeasurement()
{
double s0 = ui.speed_lineEdit->text().toDouble();
emit rangeMeasurement(0, s0, 1000);
}
void OneMotorControl_LiftingPlatform::onxMove2Loc()
{
double s = ui.speed_lineEdit->text().toDouble();
double l = ui.move2loc_lineEdit->text().toDouble();
emit move2LocSignal(0, l, s, 1000);
}
void OneMotorControl_LiftingPlatform::onxMotorRight()
{
double s = ui.speed_lineEdit->text().toDouble();
emit moveSignal(0, false, s, 1000);
}
void OneMotorControl_LiftingPlatform::onxMotorLeft()
{
double s = ui.speed_lineEdit->text().toDouble();
emit moveSignal(0, true, s, 1000);
}
void OneMotorControl_LiftingPlatform::onxMotorStop()
{
emit stopSignal(0);
}
void OneMotorControl_LiftingPlatform::run()
{
m_coordinator = new OneMotionCoordinator(m_multiAxisController,this);
connect(m_coordinator, &OneMotionCoordinator::sequenceComplete, this, &OneMotorControl_LiftingPlatform::sequenceComplete);
connect(m_coordinator, &OneMotionCoordinator::ArrivalSignal, this, &OneMotorControl_LiftingPlatform::onBack2Origin);
double plantDepthValue = DepthValueLogger::instance().readLatestPlantDepthValue();
double liftingPlatformDepthValue = DepthValueLogger::instance().readLatestLiftingPlatformDepthValue();
double targetDepth = liftingPlatformDepthValue - plantDepthValue;
if (targetDepth < 0)
{
return;
}
m_coordinator->moveToTarget(targetDepth, ui.speed_lineEdit->text().toDouble());
}
void OneMotorControl_LiftingPlatform::stop()
{
emit stopStepMotionSignal();
}
void OneMotorControl_LiftingPlatform::onBack2Origin(double pos)
{
emit back2OriginSignal_TimedDataCollection();
m_coordinator->deleteLater();
m_coordinator = nullptr;
}
bool OneMotorControl_LiftingPlatform::getMotorsConnectionStatus()
{
return m_xMotorConnectionStatus;
}

View File

@ -1,6 +1,7 @@
#pragma once
#include <QThread>
#include <QMessageBox>
#include <QPointer>
#include "ui_oneMotorControl.h"
@ -8,6 +9,9 @@
#include "fileOperation.h"
#include "CaptureCoordinator.h"
#include "MotorWindowBase.h"
#include "AppSettings.h"
#include "DepthValueLogger.h"
class OneMotorControl : public QDialog, public MotorWindowBase
{
@ -27,6 +31,8 @@ public:
bool getMotorsConnectionStatus();
void connectMotor(bool isNotification);
public Q_SLOTS:
void onConnectMotor();
@ -65,7 +71,7 @@ private:
QThread m_motorThread;
IrisMultiMotorController* m_multiAxisController = nullptr;
OneMotionCaptureCoordinator* m_coordinator = nullptr;
QPointer<OneMotionCaptureCoordinator> m_coordinator;
ImagerOperationBase* m_Imager;
DarkAndWhiteCaptureCoordinator* m_darkCaptureCoordinator = nullptr;
@ -73,3 +79,62 @@ private:
bool m_xMotorConnectionStatus = false;
};
class OneMotorControl_LiftingPlatform : public QDialog, public MotorWindowBase
{
Q_OBJECT
public:
OneMotorControl_LiftingPlatform(QWidget* parent = nullptr);
~OneMotorControl_LiftingPlatform();
void run();
void stop();
bool getMotorsConnectionStatus();
void connectMotor(bool isNotification);
public Q_SLOTS:
void onConnectMotor();
void display_x_loc(std::vector<double> loc);
void display_motors_connectivity(std::vector<int> connectivity);
void onxMove2Loc();
void zeroStart();
void onx_rangeMeasurement();
void onxMotorRight();
void onxMotorLeft();
void onxMotorStop();
void onBack2Origin(double pos);
signals:
void moveSignal(int, bool, double, int);
void move2LocSignal(int, double, double, int);
void move2LocSignal(const std::vector<double>, const std::vector<double>, int);
void stopSignal(int);
void rangeMeasurement(int, double, int);
void zeroStartSignal(int);
void testConnectivitySignal(int, int);
void start(OneMotionCapturePathLine);
void stopStepMotionSignal();
void sequenceComplete(int status);
void back2OriginSignal_TimedDataCollection();
void broadcastLocationSignal(std::vector<double>);
private:
Ui::OneMotorControl_UI ui;
QThread m_motorThread;
IrisMultiMotorController* m_multiAxisController = nullptr;
QPointer<OneMotionCoordinator> m_coordinator;
bool m_xMotorConnectionStatus = false;
};

319
HPPA/PathLine.cpp Normal file
View File

@ -0,0 +1,319 @@
#include "PathLine.h"
#include <QTableWidgetItem>
#include <cstdio>
PathLineManager::PathLineManager()
{
}
PathLineManager::~PathLineManager()
{
}
QVector<PathLine2> PathLineManager::readFromTableWidget(QTableWidget* tableWidget)
{
QVector<PathLine2> pathLines;
if (tableWidget == nullptr)
return pathLines;
int rowCount = tableWidget->rowCount();
for (int i = 0; i < rowCount; i++)
{
PathLine2 tmp;
tmp.targetYPosition = tableWidget->item(i, 0)->text().toDouble();
tmp.speedTargetYPosition = tableWidget->item(i, 1)->text().toDouble();
tmp.targetXMinPosition = tableWidget->item(i, 2)->text().toDouble();
tmp.speedTargetXMinPosition = tableWidget->item(i, 3)->text().toDouble();
tmp.targetXMaxPosition = tableWidget->item(i, 4)->text().toDouble();
tmp.speedTargetXMaxPosition = tableWidget->item(i, 5)->text().toDouble();
pathLines.append(tmp);
}
return pathLines;
}
void PathLineManager::writeToTableWidget(QTableWidget* tableWidget, const QVector<PathLine2>& pathLines)
{
if (tableWidget == nullptr)
return;
// 清空现有行
int rowCount = tableWidget->rowCount();
for (int i = 0; i < rowCount; i++)
{
tableWidget->removeRow(0);
}
// 添加新行
for (int i = 0; i < pathLines.size(); i++)
{
tableWidget->insertRow(i);
QTableWidgetItem* item0 = new QTableWidgetItem(QString::number(pathLines[i].targetYPosition, 'f', 5));
QTableWidgetItem* item1 = new QTableWidgetItem(QString::number(pathLines[i].speedTargetYPosition, 'f', 5));
QTableWidgetItem* item2 = new QTableWidgetItem(QString::number(pathLines[i].targetXMinPosition, 'f', 5));
QTableWidgetItem* item3 = new QTableWidgetItem(QString::number(pathLines[i].speedTargetXMinPosition, 'f', 5));
QTableWidgetItem* item4 = new QTableWidgetItem(QString::number(pathLines[i].targetXMaxPosition, 'f', 5));
QTableWidgetItem* item5 = new QTableWidgetItem(QString::number(pathLines[i].speedTargetXMaxPosition, 'f', 5));
item0->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item2->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item3->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item4->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item5->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
tableWidget->setItem(i, 0, item0);
tableWidget->setItem(i, 1, item1);
tableWidget->setItem(i, 2, item2);
tableWidget->setItem(i, 3, item3);
tableWidget->setItem(i, 4, item4);
tableWidget->setItem(i, 5, item5);
}
}
bool PathLineManager::saveToFile(const QString& filePath, QTableWidget* tableWidget)
{
if (tableWidget == nullptr || tableWidget->rowCount() <= 0)
return false;
FILE* fileHandle = fopen(filePath.toStdString().c_str(), "wb+");
if (fileHandle == nullptr)
return false;
double number = tableWidget->rowCount() * tableWidget->columnCount();
fwrite(&number, sizeof(double), 1, fileHandle);
double* data = new double[static_cast<int>(number)];
for (int i = 0; i < tableWidget->rowCount(); i++)
{
for (int j = 0; j < tableWidget->columnCount(); j++)
{
data[i * tableWidget->columnCount() + j] = tableWidget->item(i, j)->text().toDouble();
}
}
fwrite(data, sizeof(double), static_cast<size_t>(number), fileHandle);
fclose(fileHandle);
delete[] data;
return true;
}
bool PathLineManager::saveToFile(const QString& filePath, const QVector<PathLine2>& pathLines)
{
if (pathLines.isEmpty())
return false;
FILE* fileHandle = fopen(filePath.toStdString().c_str(), "wb+");
if (fileHandle == nullptr)
return false;
double number = pathLines.size() * COLUMN_COUNT;
fwrite(&number, sizeof(double), 1, fileHandle);
double* data = new double[static_cast<int>(number)];
for (int i = 0; i < pathLines.size(); i++)
{
data[i * COLUMN_COUNT + 0] = pathLines[i].targetYPosition;
data[i * COLUMN_COUNT + 1] = pathLines[i].speedTargetYPosition;
data[i * COLUMN_COUNT + 2] = pathLines[i].targetXMinPosition;
data[i * COLUMN_COUNT + 3] = pathLines[i].speedTargetXMinPosition;
data[i * COLUMN_COUNT + 4] = pathLines[i].targetXMaxPosition;
data[i * COLUMN_COUNT + 5] = pathLines[i].speedTargetXMaxPosition;
}
fwrite(data, sizeof(double), static_cast<size_t>(number), fileHandle);
fclose(fileHandle);
delete[] data;
return true;
}
bool PathLineManager::readFromFile(const QString& filePath, QTableWidget* tableWidget)
{
if (tableWidget == nullptr)
return false;
FILE* fileHandle = fopen(filePath.toStdString().c_str(), "rb");
if (fileHandle == nullptr)
return false;
double number;
fread(&number, sizeof(double), 1, fileHandle);
double* data = new double[static_cast<int>(number)];
for (int i = 0; i < static_cast<int>(number); i++)
{
fread(data + i, sizeof(double), 1, fileHandle);
}
// 清空现有行
int rowCount = tableWidget->rowCount();
for (int i = 0; i < rowCount; i++)
{
tableWidget->removeRow(0);
}
// 添加新行
int recordLineCount = static_cast<int>(number) / tableWidget->columnCount();
for (int i = 0; i < recordLineCount; i++)
{
tableWidget->insertRow(i);
}
// 填充数据
for (int i = 0; i < tableWidget->rowCount(); i++)
{
for (int j = 0; j < tableWidget->columnCount(); j++)
{
QTableWidgetItem* tmp = new QTableWidgetItem(
QString::number(data[i * tableWidget->columnCount() + j], 'f', 5));
tmp->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
tableWidget->setItem(i, j, tmp);
}
}
fclose(fileHandle);
delete[] data;
return true;
}
QVector<PathLine2> PathLineManager::readFromFile(const QString& filePath, bool* success)
{
QVector<PathLine2> pathLines;
FILE* fileHandle = fopen(filePath.toStdString().c_str(), "rb");
if (fileHandle == nullptr)
{
if (success) *success = false;
return pathLines;
}
double number;
fread(&number, sizeof(double), 1, fileHandle);
double* data = new double[static_cast<int>(number)];
for (int i = 0; i < static_cast<int>(number); i++)
{
fread(data + i, sizeof(double), 1, fileHandle);
}
int recordLineCount = static_cast<int>(number) / COLUMN_COUNT;
for (int i = 0; i < recordLineCount; i++)
{
PathLine2 tmp;
tmp.targetYPosition = data[i * COLUMN_COUNT + 0];
tmp.speedTargetYPosition = data[i * COLUMN_COUNT + 1];
tmp.targetXMinPosition = data[i * COLUMN_COUNT + 2];
tmp.speedTargetXMinPosition = data[i * COLUMN_COUNT + 3];
tmp.targetXMaxPosition = data[i * COLUMN_COUNT + 4];
tmp.speedTargetXMaxPosition = data[i * COLUMN_COUNT + 5];
pathLines.append(tmp);
}
fclose(fileHandle);
delete[] data;
if (success) *success = true;
return pathLines;
}
void PathLineManager::addRecordLine(QTableWidget* tableWidget,
double yPos, double ySpeed,
double xMinPos, double xMinSpeed,
double xMaxPos, double xMaxSpeed)
{
if (tableWidget == nullptr)
return;
int currentRow = tableWidget->currentRow();
int insertRow = (currentRow == -1) ? tableWidget->rowCount() : currentRow + 1;
tableWidget->insertRow(insertRow);
QTableWidgetItem* item0 = new QTableWidgetItem(QString::number(yPos, 'f', 2));
QTableWidgetItem* item1 = new QTableWidgetItem(QString::number(ySpeed, 'f', 2));
QTableWidgetItem* item2 = new QTableWidgetItem(QString::number(xMinPos, 'f', 2));
QTableWidgetItem* item3 = new QTableWidgetItem(QString::number(xMinSpeed, 'f', 2));
QTableWidgetItem* item4 = new QTableWidgetItem(QString::number(xMaxPos, 'f', 2));
QTableWidgetItem* item5 = new QTableWidgetItem(QString::number(xMaxSpeed, 'f', 2));
item0->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item2->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item3->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item4->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item5->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
tableWidget->setItem(insertRow, 0, item0);
tableWidget->setItem(insertRow, 1, item1);
tableWidget->setItem(insertRow, 2, item2);
tableWidget->setItem(insertRow, 3, item3);
tableWidget->setItem(insertRow, 4, item4);
tableWidget->setItem(insertRow, 5, item5);
}
double PathLineManager::calculateTimeFromFile(const QString& filePath)
{
bool success = false;
QVector<PathLine2> pathLines = readFromFile(filePath, &success);
if (!success || pathLines.isEmpty())
return 0.0;
double totalTimeSecond = 0.0;
double currentX = 0.0;
double currentY = 0.0;
double yTime;
double xTime;
for (int i = 0; i < pathLines.size(); i++)
{
const PathLine2& line = pathLines[i];
double yDistance = qAbs(line.targetYPosition - currentY);
if (line.speedTargetYPosition > 0.0 && yDistance > 0.0)
{
yTime = yDistance / line.speedTargetYPosition;
}
double xMinDistance = qAbs(line.targetXMinPosition - currentX);
if (line.speedTargetXMinPosition > 0.0 && xMinDistance > 0.0)
{
xTime = xMinDistance / line.speedTargetXMinPosition;
}
totalTimeSecond += std::max(yTime, xTime);
double xMaxDistance = qAbs(line.targetXMaxPosition - line.targetXMinPosition);
if (line.speedTargetXMaxPosition > 0.0 && xMaxDistance > 0.0)
{
totalTimeSecond += xMaxDistance / line.speedTargetXMaxPosition;
}
currentX = line.targetXMaxPosition;
currentY = line.targetYPosition;
}
double returnYDistance = currentY;
double returnXDistance = currentX;
if (currentY > 0.0)
{
yTime += returnYDistance / pathLines[0].speedTargetYPosition;
}
if (currentX > 0.0)
{
xTime += returnXDistance / pathLines[0].speedTargetXMinPosition;
}
totalTimeSecond += std::max(yTime, xTime);
return totalTimeSecond / 60;
}

51
HPPA/PathLine.h Normal file
View File

@ -0,0 +1,51 @@
#pragma once
#include <QString>
#include <QVector>
#include <QTableWidget>
// PathLine 结构体定义(如果还没有在其他地方定义)
struct PathLine2
{
double targetYPosition;
double speedTargetYPosition;
double targetXMinPosition;
double speedTargetXMinPosition;
double targetXMaxPosition;
double speedTargetXMaxPosition;
};
class PathLineManager
{
public:
PathLineManager();
~PathLineManager();
// 从TableWidget读取PathLine数据
static QVector<PathLine2> readFromTableWidget(QTableWidget* tableWidget);
// 将PathLine数据写入TableWidget
static void writeToTableWidget(QTableWidget* tableWidget, const QVector<PathLine2>& pathLines);
// 保存PathLine到文件
static bool saveToFile(const QString& filePath, QTableWidget* tableWidget);
static bool saveToFile(const QString& filePath, const QVector<PathLine2>& pathLines);
// 从文件读取PathLine
static bool readFromFile(const QString& filePath, QTableWidget* tableWidget);
static QVector<PathLine2> readFromFile(const QString& filePath, bool* success = nullptr);
// 添加一行PathLine到TableWidget
static void addRecordLine(QTableWidget* tableWidget,
double yPos = 15.0,
double ySpeed = 1.0,
double xMinPos = 0.0,
double xMinSpeed = 1.0,
double xMaxPos = 50.0,
double xMaxSpeed = 1.0);
static double calculateTimeFromFile(const QString& filePath);
private:
static const int COLUMN_COUNT = 6;
};

100
HPPA/PowerControl3D.cpp Normal file
View File

@ -0,0 +1,100 @@
#include "PowerControl3D.h"
using namespace MotorParams;
PowerControl3D::PowerControl3D(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
connect(ui.halogenLampPowerOn_btn, &QPushButton::clicked, this, &PowerControl3D::halogenLampPowerOn);
connect(ui.halogenLampPowerDown_btn, &QPushButton::clicked, this, &PowerControl3D::halogenLampPowerDown);
connect(ui.d65LampPowerOn_btn, &QPushButton::clicked, this, &PowerControl3D::d65LampPowerOn);
connect(ui.d65LampPowerDown_btn, &QPushButton::clicked, this, &PowerControl3D::d65LampPowerDown);
connect(ui.slrPowerOn_btn, &QPushButton::clicked, this, &PowerControl3D::slrPowerOn);
connect(ui.slrPowerDown_btn, &QPushButton::clicked, this, &PowerControl3D::slrPowerDown);
MotorParams::TCPConnectionParams tcpConnectionParams6003;
tcpConnectionParams6003.port = 6003;
tcpConnectionParams6003.serverIP = "192.168.1.2";
tcpServer6003 = new CommunicationViaTCP(tcpConnectionParams6003, this);
MotorParams::TCPConnectionParams tcpConnectionParams6004;
tcpConnectionParams6004.port = 6004;
tcpConnectionParams6004.serverIP = "192.168.1.2";
tcpServer6004 = new CommunicationViaTCP(tcpConnectionParams6004, this);
}
PowerControl3D::~PowerControl3D()
{
delete tcpServer6003;
delete tcpServer6004;
}
void PowerControl3D::halogenLampPowerOn()
{
tcpServer6003->sendCommand(R"({"key1":1,"type":"event"})");
}
void PowerControl3D::halogenLampPowerDown()
{
tcpServer6003->sendCommand(R"({"key1":0,"type":"event"})");
}
void PowerControl3D::switchHalogenLampPower(int state)
{
if (state==0)
{
halogenLampPowerDown();
}
else if(state == 1)
{
halogenLampPowerOn();
}
}
void PowerControl3D::d65LampPowerOn()
{
tcpServer6004->sendCommand(R"({"key1":1,"type":"event"})");
}
void PowerControl3D::d65LampPowerDown()
{
tcpServer6004->sendCommand(R"({"key1":0,"type":"event"})");
}
void PowerControl3D::switchD65LampPower(int state)
{
if (state == 0)
{
d65LampPowerDown();
}
else if (state == 1)
{
d65LampPowerOn();
}
}
void PowerControl3D::slrPowerOn()
{
tcpServer6003->sendCommand(R"({"key2":1,"type":"event"})");
}
void PowerControl3D::slrPowerDown()
{
tcpServer6003->sendCommand(R"({"key2":0,"type":"event"})");
}
void PowerControl3D::switchSlrPower(int state)
{
if (state == 0)
{
slrPowerDown();
}
else if (state == 1)
{
slrPowerOn();
}
}

42
HPPA/PowerControl3D.h Normal file
View File

@ -0,0 +1,42 @@
#pragma once
#include <QDialog>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include "ui_PowerControl3D.h"
#include "CommunicationViaTCP.h"
//using namespace MotorParams;
class PowerControl3D : public QDialog
{
Q_OBJECT
public:
PowerControl3D(QWidget* parent = nullptr);
~PowerControl3D();
public Q_SLOTS:
void halogenLampPowerOn();
void halogenLampPowerDown();
void switchHalogenLampPower(int state);
void d65LampPowerOn();
void d65LampPowerDown();
void switchD65LampPower(int state);
void slrPowerOn();
void slrPowerDown();
void switchSlrPower(int state);
signals:
//void powerOpened();
private:
Ui::PowerControl3D_UI ui;
MotorParams::CommunicationViaTCP* tcpServer6003;
MotorParams::CommunicationViaTCP* tcpServer6004;
};

350
HPPA/PowerControl3D.ui Normal file
View File

@ -0,0 +1,350 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PowerControl3D_UI</class>
<widget class="QDialog" name="PowerControl3D_UI">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>493</width>
<height>369</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>PowerControl3D</string>
</property>
<property name="styleSheet">
<string notr="true">QGroupBox
{
border: 12px solid transparent;
/*border-top: 12px solid transparent;
border-right: 0px solid transparent;
border-bottom: 0px solid transparent;
border-left: 0px solid transparent;*/
color: #ACCDFF;
}
QPushButton
{
/*width: 172px;
height: 56px;*/
font: 19pt &quot;新宋体&quot;;
background-color: qlineargradient(
spread:pad,
x1:0.5, y1:0, x2:0.5, y2:1,
stop:0 #283D86,
stop:1 #0F1A40
);
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
}
QPushButton:hover
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #3A4875,
stop:1 #5F6B91
);
}
/* 按下时的效果 */
QPushButton:pressed
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #1A254F,
stop:1 #3A466B
);
/* 可选:添加下压效果 */
padding-top: 9px;
padding-bottom: 7px;
}</string>
</property>
<layout class="QGridLayout" name="gridLayout_4" rowstretch="1,2,2,2,1" columnstretch="1,10,1">
<item row="0" column="1">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>66</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>63</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<widget class="QGroupBox" name="groupBox_8">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>卤素灯</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<property name="horizontalSpacing">
<number>18</number>
</property>
<item row="0" column="0">
<widget class="QPushButton" name="halogenLampPowerOn_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>打 开</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="halogenLampPowerDown_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>关 闭</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="1" column="2">
<spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>63</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="0">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>63</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="1">
<widget class="QGroupBox" name="groupBox_7">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>D65灯</string>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<property name="horizontalSpacing">
<number>18</number>
</property>
<item row="0" column="0">
<widget class="QPushButton" name="d65LampPowerOn_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>打 开</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="d65LampPowerDown_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>关 闭</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="2" column="2">
<spacer name="horizontalSpacer_6">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>63</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="0">
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>63</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="1">
<widget class="QGroupBox" name="groupBox_6">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>单反</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<property name="horizontalSpacing">
<number>18</number>
</property>
<item row="0" column="1">
<widget class="QPushButton" name="slrPowerDown_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>下 电</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QPushButton" name="slrPowerOn_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>上 电</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="3" column="2">
<spacer name="horizontalSpacer_5">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>63</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="4" column="1">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>65</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

View File

@ -6,7 +6,8 @@ m_Multiplier(100.0)
{
connect(this, SIGNAL(valueChanged(int)), this, SLOT(notifyValueChanged(int)));
setSingleStep(1);
setSingleStep(0);
setPageStep(0);
setRange(1, 500);
setOrientation(Qt::Horizontal);

81
HPPA/RasterImageLayer.cpp Normal file
View File

@ -0,0 +1,81 @@
#include "RasterImageLayer.h"
#include "RasterLayer.h"
#include "RasterDataProvider.h"
#include "RasterRendererBase.h"
#include "MultibandRasterRenderer.h"
#include "SinglebandRasterRenderer.h"
RasterImageLayer::RasterImageLayer(RasterLayer* layer, RendererType type)
: m_layer(layer)
, m_rendererType(type)
, m_rendererInitialized(false)
{
}
void RasterImageLayer::ensureRenderer()
{
if (m_rendererInitialized) return;
if (!m_layer) return;
RasterDataProvider* provider = nullptr;
if (m_layer->dataProvider())
{
provider = m_layer->dataProvider();
}
else if (m_layer->openDataProvider())
{
provider = m_layer->dataProvider();
}
if (!provider) return;
switch (m_rendererType)
{
case RendererType::Multiband:
{
auto* multiRenderer = new MultibandRasterRenderer(provider);
m_renderer.reset(multiRenderer);
multiRenderer->setParams(m_multibandParams);
break;
}
case RendererType::Singleband:
{
auto* singleRenderer = new SinglebandRasterRenderer(provider);
m_renderer.reset(singleRenderer);
singleRenderer->setParams(m_singlebandParams);
break;
}
}
m_rendererInitialized = true;
}
RasterImageLayer::~RasterImageLayer()
{
m_renderer.reset();
}
QImage RasterImageLayer::render()
{
ensureRenderer();
if (!m_renderer) return QImage();
return m_renderer->render();
}
void RasterImageLayer::setMultibandParams(const MultibandRenderParams& params)
{
m_multibandParams = params;
if (m_rendererInitialized && m_rendererType == RendererType::Multiband) {
auto* r = static_cast<MultibandRasterRenderer*>(m_renderer.get());
r->setParams(params);
}
}
void RasterImageLayer::setSinglebandParams(const SinglebandRenderParams& params)
{
m_singlebandParams = params;
if (m_rendererInitialized && m_rendererType == RendererType::Singleband) {
auto* r = static_cast<SinglebandRasterRenderer*>(m_renderer.get());
r->setParams(params);
}
}

46
HPPA/RasterImageLayer.h Normal file
View File

@ -0,0 +1,46 @@
#pragma once
#include <memory>
#include <QImage>
#include "RasterRendererBase.h"
#include "RasterRenderParams.h"
class RasterLayer;
class RasterRendererBase;
class MultibandRasterRenderer;
class SinglebandRasterRenderer;
class RasterImageLayer
{
public:
enum class RendererType {
Multiband,
Singleband
};
RasterImageLayer(RasterLayer* layer, RendererType type);
~RasterImageLayer();
void ensureRenderer();
QImage render();
RasterLayer* layer() const { return m_layer; }
RasterRendererBase* renderer() const { return m_renderer.get(); }
RendererType rendererType() const { return m_rendererType; }
// Type-safe params access
MultibandRenderParams multibandParams() const { return m_multibandParams; }
SinglebandRenderParams singlebandParams() const { return m_singlebandParams; }
void setMultibandParams(const MultibandRenderParams& params);
void setSinglebandParams(const SinglebandRenderParams& params);
private:
RasterLayer* m_layer;
RendererType m_rendererType;
std::unique_ptr<RasterRendererBase> m_renderer;
MultibandRenderParams m_multibandParams;
SinglebandRenderParams m_singlebandParams;
bool m_rendererInitialized = false;
};

View File

@ -1,21 +1,18 @@
#include "RasterLayer.h"
#include "RasterDataProvider.h"
#include "RasterRenderer.h"
#include <algorithm>
RasterLayer::RasterLayer(const QString& name, const QString& uri)
: MapLayer(name, uri)
{
// lazy creation
}
RasterLayer::~RasterLayer()
{
}
MapLayer::LayerType RasterLayer::layerType() const
{
return MapLayer::LayerType::Raster;
MapLayer::LayerType RasterLayer::layerType() const
{
return MapLayer::LayerType::Raster;
}
RasterDataProvider* RasterLayer::dataProvider() const
@ -23,18 +20,11 @@ RasterDataProvider* RasterLayer::dataProvider() const
return m_provider ? m_provider.get() : nullptr;
}
RasterRenderer* RasterLayer::renderer() const
{
return m_renderer ? m_renderer.get() : nullptr;
}
bool RasterLayer::openDataProvider()
{
if (!m_provider) m_provider = std::make_unique<RasterDataProvider>(dataPath());
if (!m_provider) return false;
bool ok = m_provider->open();
if (ok && !m_renderer) m_renderer = std::make_unique<RasterRenderer>(m_provider.get());
return ok;
return m_provider->open();
}
bool RasterLayer::isValidPixel(int x, int y)
@ -71,31 +61,6 @@ bool RasterLayer::readPixelSpectrum(int x, int y, QVector<double>& wavelengths,
return true;
}
QImage RasterLayer::render(const RenderParams& params)
{
if (!m_provider) {
if (!openDataProvider()) return QImage();
}
if (!m_renderer) m_renderer = std::make_unique<RasterRenderer>(m_provider.get());
RasterRenderer::Params p;
p.rWave = params.rWave;
p.gWave = params.gWave;
p.bWave = params.bWave;
p.minValue = params.minValue;
p.maxValue = params.maxValue;
return m_renderer->render(p);
}
RasterLayer::RenderParams RasterLayer::currentRenderParams() const
{
return m_currentParams;
}
void RasterLayer::setCurrentRenderParams(const RenderParams& params)
{
m_currentParams = params;
}
bool RasterLayer::wavelengthRange(double& minWave, double& maxWave) const
{
auto wl = bandWavelengths();
@ -108,9 +73,26 @@ bool RasterLayer::wavelengthRange(double& minWave, double& maxWave) const
std::vector<double> RasterLayer::bandWavelengths() const
{
if (!m_provider) {
// need to open provider to read wavelengths - cast away const for lazy init
auto* self = const_cast<RasterLayer*>(this);
if (!self->openDataProvider()) return {};
}
return m_provider->bandWavelengths();
}
int RasterLayer::width() const
{
if (!m_provider) {
auto* self = const_cast<RasterLayer*>(this);
if (!self->openDataProvider()) return 0;
}
return m_provider->width();
}
int RasterLayer::height() const
{
if (!m_provider) {
auto* self = const_cast<RasterLayer*>(this);
if (!self->openDataProvider()) return 0;
}
return m_provider->height();
}

View File

@ -2,11 +2,10 @@
#include "MapLayer.h"
#include <memory>
#include <QImage>
#include <QVector>
#include <vector>
class RasterDataProvider;
class RasterRenderer;
class RasterLayer : public MapLayer
{
@ -17,9 +16,8 @@ public:
LayerType layerType() const override;
// Access provider/renderer
// Access provider
RasterDataProvider* dataProvider() const;
RasterRenderer* renderer() const;
// Create or open provider based on this layer's uri
bool openDataProvider();
@ -27,29 +25,16 @@ public:
bool isValidPixel(int x, int y);
bool readPixelSpectrum(int x, int y, QVector<double>& wavelengths, QVector<double>& spectrum);
struct RenderParams {
double rWave = 665.0; // default wavelengths (nm)
double gWave = 560.0;
double bWave = 490.0;
double minValue = 0.0; // optional stretch
double maxValue = 4095.0;
};
// Render the raster using current provider and renderer. Returns an empty QImage on failure.
QImage render(const RenderParams& params);
// Current render params stored per layer
RenderParams currentRenderParams() const;
void setCurrentRenderParams(const RenderParams& params);
// Get wavelength range from data provider (min, max). Returns false if unavailable.
bool wavelengthRange(double& minWave, double& maxWave) const;
// Get all band wavelengths
std::vector<double> bandWavelengths() const;
private:
// Get dimensions
int width() const;
int height() const;
protected:
std::unique_ptr<RasterDataProvider> m_provider;
std::unique_ptr<RasterRenderer> m_renderer;
RenderParams m_currentParams;
};

19
HPPA/RasterRenderParams.h Normal file
View File

@ -0,0 +1,19 @@
#pragma once
// Common base struct for all render parameters
struct RasterRenderParamsBase {
double minValue = 0.0;
double maxValue = 4095.0;
};
// Parameters for multiband rendering (RGB with wavelengths)
struct MultibandRenderParams : RasterRenderParamsBase {
double rWave = 665.0;
double gWave = 560.0;
double bWave = 490.0;
};
// Parameters for singleband rendering (wavelength)
struct SinglebandRenderParams : RasterRenderParamsBase {
double wavelength = 550.0;
};

View File

@ -1,86 +0,0 @@
#include "RasterRenderer.h"
#include "RasterDataProvider.h"
#include <QDebug>
#include <algorithm>
RasterRenderer::RasterRenderer(RasterDataProvider* provider)
: m_provider(provider)
{
}
void RasterRenderer::stretchTo8bit(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal)
{
size_t n = in.size();
out.resize(n);
if (maxVal <= minVal) {
std::fill(out.begin(), out.end(), 0);
return;
}
float denom = 1.0f / (maxVal - minVal);
for (size_t i = 0; i < n; ++i) {
float v = (in[i] - minVal) * denom;
v = std::min(std::max(v, 0.0f), 1.0f);
out[i] = static_cast<unsigned char>(v * 255.0f);
}
}
QImage RasterRenderer::render(const Params& params)
{
if (!m_provider) return QImage();
int bands = m_provider->bandCount();
int w = m_provider->width();
int h = m_provider->height();
if (w <= 0 || h <= 0) return QImage();
// Find nearest bands for requested wavelengths if wavelengths available
std::vector<double> wavelengths = m_provider->bandWavelengths();
auto chooseBandIndexForWave = [&](double wave)->int {
if (wavelengths.empty()) {
// fallback: select R,G,B as first three bands
if (bands >= 3) return (wave==params.rWave?0:(wave==params.gWave?1:2));
if (bands >= 1) return 0;
return -1;
}
int best = -1; double bestDiff = 1e12;
for (int i = 0; i < (int)wavelengths.size(); ++i) {
if (wavelengths[i] < 0) continue;
double d = std::abs(wavelengths[i] - wave);
if (d < bestDiff) { bestDiff = d; best = i; }
}
if (best >= 0) return best;
// fallback
return std::min(2, bands-1);
};
int rIdx = chooseBandIndexForWave(params.rWave);
int gIdx = chooseBandIndexForWave(params.gWave);
int bIdx = chooseBandIndexForWave(params.bWave);
std::vector<float> rbuf, gbuf, bbuf;
if (rIdx >= 0) m_provider->readBandAsFloat(rIdx, rbuf);
if (gIdx >= 0) m_provider->readBandAsFloat(gIdx, gbuf);
if (bIdx >= 0) m_provider->readBandAsFloat(bIdx, bbuf);
std::vector<unsigned char> r8, g8, b8;
float minV = static_cast<float>(params.minValue);
float maxV = static_cast<float>(params.maxValue);
if (!rbuf.empty()) stretchTo8bit(rbuf, r8, minV, maxV);
if (!gbuf.empty()) stretchTo8bit(gbuf, g8, minV, maxV);
if (!bbuf.empty()) stretchTo8bit(bbuf, b8, minV, maxV);
QImage out(w, h, QImage::Format_RGB888);
for (int y = 0; y < h; ++y) {
unsigned char* scan = out.scanLine(y);
for (int x = 0; x < w; ++x) {
int idx = y * w + x;
unsigned char rc = (r8.size() > (size_t)idx) ? r8[idx] : 0;
unsigned char gc = (g8.size() > (size_t)idx) ? g8[idx] : 0;
unsigned char bc = (b8.size() > (size_t)idx) ? b8[idx] : 0;
scan[x*3 + 0] = rc;
scan[x*3 + 1] = gc;
scan[x*3 + 2] = bc;
}
}
return out;
}

View File

@ -1,29 +0,0 @@
#pragma once
#include <QImage>
#include <vector>
class RasterDataProvider;
class RasterRenderer
{
public:
struct Params {
double rWave = 665.0;
double gWave = 560.0;
double bWave = 490.0;
double minValue = 0.0;
double maxValue = 255.0;
};
explicit RasterRenderer(RasterDataProvider* provider);
// Render to an 8-bit RGB image. Returns empty image on failure.
QImage render(const Params& params);
private:
RasterDataProvider* m_provider;
// helper to map float buffer to 8-bit with min/max stretch
static void stretchTo8bit(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal);
};

View File

@ -0,0 +1,6 @@
#include "RasterRendererBase.h"
RasterRendererBase::RasterRendererBase(RasterDataProvider* provider)
: m_provider(provider)
{
}

25
HPPA/RasterRendererBase.h Normal file
View File

@ -0,0 +1,25 @@
#pragma once
#include <QImage>
#include <memory>
class RasterDataProvider;
class RasterRendererBase
{
public:
//struct Params {
// virtual ~Params() = default;
//};
virtual ~RasterRendererBase() = default;
virtual QImage render() = 0;
RasterDataProvider* dataProvider() const { return m_provider; }
protected:
explicit RasterRendererBase(RasterDataProvider* provider);
RasterDataProvider* m_provider = nullptr;
};

View File

@ -30,7 +30,7 @@ void RgbCameraOperation::OpenCamera()
cam->release();
emit CamClosed();
emit CamOpenedSignal();
}
@ -65,4 +65,6 @@ void RgbCameraOperation::CloseCamera()
std::cout << "关闭摄像头+++++++++++++++++++++++++++++++++++++++++++" << std::endl;
record = false;
emit CamClosedSignal();
}

View File

@ -42,6 +42,7 @@ public slots:
signals:
void PlotSignal();
void CamClosed();
void CamOpenedSignal();
void CamClosedSignal();
};
#endif // !RGBCAMERAOPERATION_H

View File

@ -0,0 +1,240 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SingleLensReflexCameraClass</class>
<widget class="QDialog" name="SingleLensReflexCameraClass">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>855</width>
<height>481</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>SingleLensReflexCamera</string>
</property>
<property name="styleSheet">
<string notr="true">QGroupBox
{
border: 12px solid transparent;
/*border-top: 12px solid transparent;
border-right: 0px solid transparent;
border-bottom: 0px solid transparent;
border-left: 0px solid transparent;*/
color: #ACCDFF;
}
QPushButton
{
/*width: 172px;
height: 56px;*/
font: 19pt &quot;新宋体&quot;;
background-color: qlineargradient(
spread:pad,
x1:0.5, y1:0, x2:0.5, y2:1,
stop:0 #283D86,
stop:1 #0F1A40
);
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
}
QPushButton:hover
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #3A4875,
stop:1 #5F6B91
);
}
/* 按下时的效果 */
QPushButton:pressed
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #1A254F,
stop:1 #3A466B
);
/* 可选:添加下压效果 */
padding-top: 9px;
padding-bottom: 7px;
}</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="1">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>18</width>
<height>100</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>135</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="openSLRCamera_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>打 开</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="closeSLRCamera_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>关 闭</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="2" column="2">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>135</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="styleSheet">
<string notr="true">QLabel {
color: rgb(255, 255, 255);
}</string>
</property>
<property name="text">
<string>数据路径</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="dataFolderLineEdit">
<property name="styleSheet">
<string notr="true">QLineEdit {
background-color: #142D7F;
color: #e6eeff;
border: 1px solid #2f6bff;
border-radius: 6px;
padding: 4px 8px;
min-width: 70px;
min-height: 20px;
font-size: 13px;
}</string>
</property>
<property name="text">
<string>./CapturedImages</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="dataFolderBtn">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="4" column="1">
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>18</width>
<height>100</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QPushButton" name="takePhoto_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>拍 摄</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="stopTakePhoto_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>停 拍</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
<zorder>dataFolderLineEdit</zorder>
<zorder>dataFolderBtn</zorder>
<zorder>label</zorder>
<zorder>openSLRCamera_btn</zorder>
<zorder>layoutWidget</zorder>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,189 @@
#pragma once
#include <QDialog>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QImage>
#include <QThread>
#include <QDir>
#include <QTimer>
#include <QMutex>
#include <QDateTime>
#include <QLabel>
#include <QFileDialog>
#include <iostream>
#include "ui_SingleLensReflexCamera.h"
#include "AppSettings.h"
#include <fstream>
#include <opencv2/opencv.hpp>
// 包含Canon EDSDK头文件
#include "EDSDK.h"
#include "EDSDKTypes.h"
#include "EDSDKErrors.h"
typedef void(*func)();
class SingleLensReflexCameraOperation : public QObject
{
Q_OBJECT
public:
SingleLensReflexCameraOperation();
~SingleLensReflexCameraOperation();
QImage m_colorImage;
QImage m_depthImage;
void setCallback(void(*func)());
bool getRecordStatus() const { return m_isRecord; }
// 设置保存路径
void setSavePath(const QString& path);
// 获取当前实时取景图像
QImage getCurrentLiveViewImage();
void setCaptureInterval(int captureIntervalSeconds);
private:
cv::Mat frame;
func m_func;
bool m_isRecord;
// Canon EDSDK相关成员
EdsCameraRef m_camera;
bool m_isSDKInitialized;
bool m_isSessionOpen;
bool m_isLiveViewActive;
QTimer* m_captureTimer; // 拍照定时器
QTimer* m_liveViewTimer; // 实时取景定时器
QString m_savePath;
int m_imageCounter;
int m_captureIntervalMilliseconds;
QMutex m_mutex;
QMutex m_liveViewMutex;
QImage m_liveViewImage; // 当前实时取景图像
// EDSDK辅助函数
EdsError initializeSDK();
EdsError terminateSDK();
EdsError openCamera();
EdsError closeCamera();
EdsError takePicture();
EdsError setupSaveToHost();
// 实时取景相关函数
EdsError startLiveView();
EdsError stopLiveView();
EdsError downloadEvfImage();
// 静态回调函数
static EdsError EDSCALLBACK handleObjectEvent(EdsObjectEvent event, EdsBaseRef object, EdsVoid* context);
static EdsError EDSCALLBACK handlePropertyEvent(EdsPropertyEvent event, EdsPropertyID property, EdsUInt32 param, EdsVoid* context);
static EdsError EDSCALLBACK handleStateEvent(EdsStateEvent event, EdsUInt32 parameter, EdsVoid* context);
// 下载图像
EdsError downloadImage(EdsDirectoryItemRef directoryItem);
public slots:
void OpenSLRCamera();
void takePhoto();
void OpenAndTakePhotoSLRCamera();
void stopTakePhoto();
void OpenSLRCamera_callback();
void CloseSLRCamera();
void onCaptureTimer();
void onLiveViewTimer();
// 控制拍照
void startCapture(); // 开始定时拍照
void stopCapture(); // 停止定时拍照
void captureOnce(); // 拍一张照片
signals:
void PlotSignal();
void CamOpenedSignal();
void CamClosedSignal();
void ImageCapturedSignal(const QString& filePath);
void ErrorSignal(const QString& errorMsg);
// 实时取景信号
void LiveViewImageReady(const QImage& image);
void LiveViewStarted();
void LiveViewStopped();
void CaptureStartedSignal();
void CaptureStoppedSignal();
};
class SingleLensReflexCameraWindow : public QDialog
{
Q_OBJECT
public:
SingleLensReflexCameraWindow(QWidget* parent = nullptr);
~SingleLensReflexCameraWindow();
SingleLensReflexCameraOperation* m_SingleLensReflexCameraOperation;
void setDataFolder(QString dir);
void setCaptureInterval(int captureIntervalSeconds);
public Q_SLOTS:
void onSelectDataFolder();
void openSLRCamera();
void takePhoto();
void OpenAndTakePhotoSLRCamera();
void stopTakePhoto();
void onCamOpened();
void closeSLRCamera();
void onCamClosed();
void onImageCaptured(const QString& filePath);
void onError(const QString& errorMsg);
// 拍照控制
void onStartCapture();
void onStopCapture();
void onCaptureOnce();
void onCaptureStarted();
void onCaptureStopped();
void onStartTimedDataCollection(int lineNum);
void onStopTimedDataCollection();
signals:
void openSLRCameraSignal();
void takePhotoSignal();
void OpenAndTakePhotoSLRCameraSignal();
void stopTakePhotoSignal();
void closeSLRCameraSignal();
void PlotSLRImageSignal();
void SLRCamClosedSignal();
// 控制信号
void startCaptureSignal();
void stopCaptureSignal();
void captureOnceSignal();
// 实时取景信号
void LiveViewImageReady(const QImage& image);
void LiveViewStarted();
void LiveViewStopped();
private:
Ui::SingleLensReflexCameraClass ui;
QThread* m_SLRCameraThread;
// 用于显示实时取景的标签(如果UI中没有,可以动态创建)
QLabel* m_liveViewLabel;
QString m_btnOldText; // 存储拍照按钮的原始文本
bool m_isCapturing; // 是否正在定时拍照
};

View File

@ -0,0 +1,85 @@
#include "SinglebandRasterRenderer.h"
#include "RasterDataProvider.h"
#include <algorithm>
SinglebandRasterRenderer::SinglebandRasterRenderer(RasterDataProvider* provider)
: RasterRendererBase(provider)
{
}
void SinglebandRasterRenderer::stretchTo8bit(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal)
{
size_t n = in.size();
out.resize(n);
if (maxVal <= minVal) {
std::fill(out.begin(), out.end(), 0);
return;
}
float denom = 1.0f / (maxVal - minVal);
for (size_t i = 0; i < n; ++i) {
float v = (in[i] - minVal) * denom;
v = std::min(std::max(v, 0.0f), 1.0f);
out[i] = static_cast<unsigned char>(v * 255.0f);
}
}
int SinglebandRasterRenderer::nearestBandIndex(double wave) const
{
if (!m_provider) return -1;
int bands = m_provider->bandCount();
if (bands <= 0) return -1;
std::vector<double> wavelengths = m_provider->bandWavelengths();
if (wavelengths.empty()) {
// No wavelengths available, fallback to first band
return 0;
}
int best = -1;
double bestDiff = 1e12;
for (int i = 0; i < (int)wavelengths.size(); ++i) {
if (wavelengths[i] < 0) continue;
double d = std::abs(wavelengths[i] - wave);
if (d < bestDiff) {
bestDiff = d;
best = i;
}
}
return (best >= 0) ? best : 0;
}
QImage SinglebandRasterRenderer::render()
{
if (!m_provider) return QImage();
int w = m_provider->width();
int h = m_provider->height();
if (w <= 0 || h <= 0) return QImage();
int bandIdx = nearestBandIndex(m_params.wavelength);
if (bandIdx < 0 || bandIdx >= m_provider->bandCount()) {
bandIdx = 0;
}
std::vector<float> buf;
m_provider->readBandAsFloat(bandIdx, buf);
std::vector<unsigned char> gray8;
float minV = static_cast<float>(m_params.minValue);
float maxV = static_cast<float>(m_params.maxValue);
if (!buf.empty()) {
stretchTo8bit(buf, gray8, minV, maxV);
}
QImage out(w, h, QImage::Format_Grayscale8);
for (int y = 0; y < h; ++y) {
unsigned char* scan = out.scanLine(y);
for (int x = 0; x < w; ++x) {
int idx = y * w + x;
scan[x] = (gray8.size() > (size_t)idx) ? gray8[idx] : 0;
}
}
return out;
}

View File

@ -0,0 +1,27 @@
#pragma once
#include "RasterRendererBase.h"
#include "RasterRenderParams.h"
#include <vector>
class RasterDataProvider;
class SinglebandRasterRenderer : public RasterRendererBase
{
public:
explicit SinglebandRasterRenderer(RasterDataProvider* provider);
QImage render() override;
// Parameter access
SinglebandRenderParams params() const { return m_params; }
void setParams(const SinglebandRenderParams& params) { m_params = params; }
private:
SinglebandRenderParams m_params;
int nearestBandIndex(double wave) const;
// Helper to map float buffer to 8-bit with min/max stretch
static void stretchTo8bit(const std::vector<float>& in, std::vector<unsigned char>& out, float minVal, float maxVal);
};

View File

@ -7,6 +7,24 @@ TabManager::TabManager(QTabWidget* tabWidget, QObject* parent)
Q_ASSERT(m_tabWidget);
}
void TabManager::hideAllTabs()
{
int tabNumber = m_tabWidget->count();
for (size_t i = 0; i < tabNumber; i++)
{
int idx = 0;
TabInfo info;
info.index = idx;
info.text = m_tabWidget->tabText(idx);
info.icon = m_tabWidget->tabIcon(idx);
info.toolTip = m_tabWidget->tabToolTip(idx);
m_hiddenTabs.insert(m_tabWidget->widget(idx), info);
m_tabWidget->removeTab(idx);
}
}
void TabManager::hideTab(QWidget* page)
{
if (!page || !m_tabWidget)

View File

@ -10,6 +10,7 @@ class TabManager : public QObject
public:
explicit TabManager(QTabWidget* tabWidget, QObject* parent = nullptr);
void hideAllTabs();
void hideTab(QWidget* page);
void showTab(QWidget* page);
bool isHidden(QWidget* page) const;

661
HPPA/TaskTreeModel.cpp Normal file
View File

@ -0,0 +1,661 @@
#include "TaskTreeModel.h"
#include <QBrush>
#include <QFont>
#include <QIcon>
// ==================== TaskTreeNode 实现 ====================
TaskTreeNode::TaskTreeNode(TaskTreeNode* parent)
: m_parent(parent)
{
}
TaskTreeNode::~TaskTreeNode()
{
qDeleteAll(m_children);
m_children.clear();
}
void TaskTreeNode::appendChild(TaskTreeNode* child)
{
m_children.append(child);
}
void TaskTreeNode::removeChild(int index)
{
if (index < 0 || index >= m_children.size())
return;
delete m_children.takeAt(index);
}
TaskTreeNode* TaskTreeNode::child(int row)
{
if (row < 0 || row >= m_children.size())
return nullptr;
return m_children.at(row);
}
int TaskTreeNode::childCount() const
{
return m_children.size();
}
int TaskTreeNode::row() const
{
if (m_parent) {
return m_parent->m_children.indexOf(const_cast<TaskTreeNode*>(this));
}
return 0;
}
TaskTreeNode* TaskTreeNode::parentNode()
{
return m_parent;
}
// ==================== TaskTreeModel 实现 ====================
TaskTreeModel::TaskTreeModel(QObject* parent)
: QAbstractItemModel(parent)
, m_rootNode(new TaskTreeNode())
, m_countdownTimer(new QTimer(this))
{
m_rootNode->nodeType = TreeNodeType::Root;
m_countdownTimer->setInterval(1000);
connect(m_countdownTimer, &QTimer::timeout, this, &TaskTreeModel::onCountdownTimerTimeout);
}
TaskTreeModel::~TaskTreeModel()
{
m_countdownTimer->stop();
delete m_rootNode;
}
QModelIndex TaskTreeModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
TaskTreeNode* parentNode;
if (!parent.isValid())
parentNode = m_rootNode;
else
parentNode = static_cast<TaskTreeNode*>(parent.internalPointer());
TaskTreeNode* childNode = parentNode->child(row);
if (childNode)
return createIndex(row, column, childNode);
return QModelIndex();
}
QModelIndex TaskTreeModel::parent(const QModelIndex& index) const
{
if (!index.isValid())
return QModelIndex();
TaskTreeNode* childNode = static_cast<TaskTreeNode*>(index.internalPointer());
TaskTreeNode* parentNode = childNode->parentNode();
if (parentNode == m_rootNode)
return QModelIndex();
return createIndex(parentNode->row(), 0, parentNode);
}
int TaskTreeModel::rowCount(const QModelIndex& parent) const
{
TaskTreeNode* parentNode;
if (!parent.isValid())
parentNode = m_rootNode;
else
parentNode = static_cast<TaskTreeNode*>(parent.internalPointer());
return parentNode->childCount();
}
int TaskTreeModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent)
return ColumnCount;
}
QVariant TaskTreeModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
TaskTreeNode* node = static_cast<TaskTreeNode*>(index.internalPointer());
if (role == Qt::DisplayRole) {
if (node->nodeType == TreeNodeType::Task && node->taskData) {
const TimedTask& task = *node->taskData;
switch (index.column()) {
case ColName:
return QString::fromLocal8Bit("定时任务 %1").arg(task.id);
case ColScheduledTime:
return task.scheduledTime.toString("yyyy-MM-dd HH:mm:ss");
case ColCountdown: {
if (task.status == TaskStatus::Finished || task.status == TaskStatus::Running)
{
return QString::fromLocal8Bit("0");
}
qint64 seconds = QDateTime::currentDateTime().secsTo(task.scheduledTime);
if (seconds < 0)
{
return QString::fromLocal8Bit("已超时");
}
return formatCountdown(seconds);
}
case ColStartTime:
return task.startTime.isValid() ?
task.startTime.toString("HH:mm:ss") : "-";
case ColEndTime:
return task.endTime.isValid() ?
task.endTime.toString("HH:mm:ss") : "-";
case ColDuration:
return formatDuration(task.durationMinutes);
case ColEstimatedDuration:
return formatDuration(task.estimatedDurationMinutes);
case ColStatus:
return statusToString(task.status);
case ColProgress: {
int finished = 0;
for (const auto& sub : task.subTasks) {
if (sub.status == TaskStatus::Finished) finished++;
}
return QString("%1/%2").arg(finished).arg(task.subTasks.size());
}
case ColPath:
return task.savePath;
}
}
else if (node->nodeType == TreeNodeType::SubTask && node->subTaskData) {
const SubTask& subTask = *node->subTaskData;
switch (index.column()) {
case ColName:
return subTaskTypeToString(subTask.type);
case ColScheduledTime:
return "-";
case ColCountdown:
return "-";
case ColStartTime:
return subTask.startTime.isValid() ?
subTask.startTime.toString("HH:mm:ss") : "-";
case ColEndTime:
return subTask.endTime.isValid() ?
subTask.endTime.toString("HH:mm:ss") : "-";
case ColDuration:
return formatDuration(subTask.durationMinutes);
case ColEstimatedDuration:
return formatDuration(subTask.estimatedDurationMinutes);
case ColStatus:
return statusToString(subTask.status);
case ColProgress:
return "-";
case ColPath:
return "-";
}
}
}
else if (role == Qt::BackgroundRole) {
TaskStatus status = TaskStatus::Waiting;
if (node->nodeType == TreeNodeType::Task && node->taskData) {
status = node->taskData->status;
}
else if (node->nodeType == TreeNodeType::SubTask && node->subTaskData) {
status = node->subTaskData->status;
}
return QBrush(statusColor(status));
}
else if (role == Qt::ForegroundRole) {
TaskStatus status = TaskStatus::Waiting;
if (node->nodeType == TreeNodeType::Task && node->taskData) {
status = node->taskData->status;
return QBrush(QColor("#E2EDFF")); // 深绿色文字
}
else if (node->nodeType == TreeNodeType::SubTask && node->subTaskData) {
status = node->subTaskData->status;
return QBrush(QColor("#E2EDFF")); // 深绿色文字
}
if (status == TaskStatus::Running) {
return QBrush(QColor("#E2EDFF")); // 深绿色文字
}
return QBrush(QColor("#E2EDFF")); // 深绿色文字
}
else if (role == Qt::FontRole) {
QFont font;
if (node->nodeType == TreeNodeType::Task) {
font.setBold(true);
if (node->taskData && node->taskData->status == TaskStatus::Running) {
font.setItalic(true);
}
}
else if (node->nodeType == TreeNodeType::SubTask) {
if (node->subTaskData && node->subTaskData->status == TaskStatus::Running) {
font.setBold(true);
}
}
return font;
}
else if (role == Qt::DecorationRole && index.column() == ColName) {
if (node->nodeType == TreeNodeType::Task) {
// 可以返回任务图标
// return QIcon(":/icons/task.png");
}
else if (node->nodeType == TreeNodeType::SubTask && node->subTaskData) {
// 根据子任务类型返回不同图标
switch (node->subTaskData->type) {
case SubTaskType::HyperSpectual400_1000nm:
case SubTaskType::HyperSpectual1000_1700nm:
// return QIcon(":/icons/hyperspectral.png");
break;
case SubTaskType::SingleLensReflex:
// return QIcon(":/icons/camera.png");
break;
case SubTaskType::DepthCamera:
// return QIcon(":/icons/depth.png");
break;
}
}
}
else if (role == Qt::TextAlignmentRole) {
if (index.column() == ColName || index.column() == ColPath) {
return static_cast<int>(Qt::AlignLeft | Qt::AlignVCenter);
}
return Qt::AlignCenter;
}
else if (role == Qt::ToolTipRole) {
if (node->nodeType == TreeNodeType::Task && node->taskData) {
return QString::fromLocal8Bit("任务ID: %1\n保存路径: %2\n预热时间: %3 分钟")
.arg(node->taskData->id)
.arg(node->taskData->savePath)
.arg(node->taskData->HalogenLampPreheatingTime_Minute);
}
else if (node->nodeType == TreeNodeType::SubTask && node->subTaskData) {
QString tip = QString::fromLocal8Bit("类型: %1\n路径文件: %2")
.arg(subTaskTypeToString(node->subTaskData->type))
.arg(node->subTaskData->pathLineFilePath);
if (node->subTaskData->type == SubTaskType::HyperSpectual400_1000nm ||
node->subTaskData->type == SubTaskType::HyperSpectual1000_1700nm) {
tip += QString::fromLocal8Bit("\n帧率: %1\n曝光时间: %2")
.arg(node->subTaskData->frameRate)
.arg(node->subTaskData->exposureTime);
}
return tip;
}
}
return QVariant();
}
QVariant TaskTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
return QVariant();
switch (section) {
case ColName: return QString::fromLocal8Bit("名称");
case ColScheduledTime: return QString::fromLocal8Bit("计划时间");
case ColCountdown: return QString::fromLocal8Bit("倒计时");
case ColStartTime: return QString::fromLocal8Bit("开始时间");
case ColEndTime: return QString::fromLocal8Bit("结束时间");
case ColDuration: return QString::fromLocal8Bit("耗时");
case ColEstimatedDuration: return QString::fromLocal8Bit("预测耗时");
case ColStatus: return QString::fromLocal8Bit("状态");
case ColProgress: return QString::fromLocal8Bit("进度");
case ColPath: return QString::fromLocal8Bit("路径");
}
return QVariant();
}
Qt::ItemFlags TaskTreeModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
void TaskTreeModel::setTasks(const QVector<TimedTask>& tasks)
{
m_countdownTimer->stop();
beginResetModel();
m_tasks = tasks;
clearTree();
setupModelData();
endResetModel();
m_countdownTimer->start();
}
void TaskTreeModel::setupModelData()
{
for (int i = 0; i < m_tasks.size(); ++i) {
TimedTask& task = m_tasks[i];
// 创建任务节点
TaskTreeNode* taskNode = new TaskTreeNode(m_rootNode);
taskNode->nodeType = TreeNodeType::Task;
taskNode->taskId = task.id;
taskNode->taskData = &task;
m_rootNode->appendChild(taskNode);
// 为每个子任务创建节点
for (int j = 0; j < task.subTasks.size(); ++j) {
SubTask& subTask = task.subTasks[j];
TaskTreeNode* subTaskNode = new TaskTreeNode(taskNode);
subTaskNode->nodeType = TreeNodeType::SubTask;
subTaskNode->taskId = task.id;
subTaskNode->subTaskIndex = j;
subTaskNode->subTaskData = &subTask;
taskNode->appendChild(subTaskNode);
}
}
}
void TaskTreeModel::clearTree()
{
// 删除所有子节点
while (m_rootNode->childCount() > 0) {
//delete m_rootNode->child(0);
m_rootNode->removeChild(0);
}
}
void TaskTreeModel::updateTask(const TimedTask& task)
{
int dataIndex = findTaskDataIndex(task.id);
if (dataIndex < 0) return;
// 更新数据
m_tasks[dataIndex] = task;
// 重新设置指针(因为数据被复制了)
TaskTreeNode* taskNode = findTaskNode(task.id);
if (taskNode) {
taskNode->taskData = &m_tasks[dataIndex];
// 更新子任务指针
for (int i = 0; i < taskNode->childCount() && i < m_tasks[dataIndex].subTasks.size(); ++i) {
TaskTreeNode* subNode = taskNode->child(i);
if (subNode) {
subNode->subTaskData = &m_tasks[dataIndex].subTasks[i];
}
}
}
// 通知视图更新任务行
QModelIndex taskIndex = getTaskIndex(task.id);
if (taskIndex.isValid()) {
QModelIndex topLeft = index(taskIndex.row(), 0, taskIndex.parent());
QModelIndex bottomRight = index(taskIndex.row(), ColumnCount - 1, taskIndex.parent());
emit dataChanged(topLeft, bottomRight);
// 更新所有子任务行
int subCount = rowCount(taskIndex);
if (subCount > 0) {
QModelIndex subTopLeft = index(0, 0, taskIndex);
QModelIndex subBottomRight = index(subCount - 1, ColumnCount - 1, taskIndex);
emit dataChanged(subTopLeft, subBottomRight);
}
}
emit taskUpdated(task.id);
}
void TaskTreeModel::updateSubTask(int taskId, int subTaskIndex, const SubTask& subTask)
{
int dataIndex = findTaskDataIndex(taskId);
if (dataIndex < 0 || subTaskIndex >= m_tasks[dataIndex].subTasks.size())
return;
m_tasks[dataIndex].subTasks[subTaskIndex] = subTask;
// 重新设置指针
TaskTreeNode* subNode = findSubTaskNode(taskId, subTaskIndex);
if (subNode) {
subNode->subTaskData = &m_tasks[dataIndex].subTasks[subTaskIndex];
}
QModelIndex subTaskModelIndex = getSubTaskIndex(taskId, subTaskIndex);
if (subTaskModelIndex.isValid()) {
QModelIndex topLeft = index(subTaskModelIndex.row(), 0, subTaskModelIndex.parent());
QModelIndex bottomRight = index(subTaskModelIndex.row(), ColumnCount - 1, subTaskModelIndex.parent());
emit dataChanged(topLeft, bottomRight);
}
// 同时更新父任务的进度显示
QModelIndex taskIndex = getTaskIndex(taskId);
if (taskIndex.isValid()) {
QModelIndex progressIndex = index(taskIndex.row(), ColProgress, taskIndex.parent());
emit dataChanged(progressIndex, progressIndex);
}
emit subTaskUpdated(taskId, subTaskIndex);
}
void TaskTreeModel::setTaskAndSubtaskStatus(int taskId, TaskStatus status)
{
int dataIndex = findTaskDataIndex(taskId);
if (dataIndex < 0) return;
updateTaskStatus(taskId, status);
for (size_t i = 0; i < m_tasks[dataIndex].subTaskCount(); i++)
{
updateSubTaskStatus(taskId, i, status);
}
}
void TaskTreeModel::updateTaskStatus(int taskId, TaskStatus status)
{
int dataIndex = findTaskDataIndex(taskId);
if (dataIndex < 0) return;
m_tasks[dataIndex].status = status;
QModelIndex taskIndex = getTaskIndex(taskId);
if (taskIndex.isValid()) {
QModelIndex topLeft = index(taskIndex.row(), 0, taskIndex.parent());
QModelIndex bottomRight = index(taskIndex.row(), ColumnCount - 1, taskIndex.parent());
emit dataChanged(topLeft, bottomRight);
}
}
void TaskTreeModel::updateSubTaskStatusAndProgress(int taskId, int subTaskIndex, TaskStatus status)
{
updateSubTaskStatus(taskId, subTaskIndex, status);
updateProgress(taskId);
}
void TaskTreeModel::updateSubTaskStatus(int taskId, int subTaskIndex, TaskStatus status)
{
int dataIndex = findTaskDataIndex(taskId);
if (dataIndex < 0 || subTaskIndex >= m_tasks[dataIndex].subTasks.size())
return;
SubTask& subTask = m_tasks[dataIndex].subTasks[subTaskIndex];
subTask.status = status;
QModelIndex subTaskModelIndex = getSubTaskIndex(taskId, subTaskIndex);
if (subTaskModelIndex.isValid()) {
QModelIndex topLeft = index(subTaskModelIndex.row(), 0, subTaskModelIndex.parent());
QModelIndex bottomRight = index(subTaskModelIndex.row(), ColumnCount - 1, subTaskModelIndex.parent());
emit dataChanged(topLeft, bottomRight);
}
}
void TaskTreeModel::updateProgress(int taskId)
{
// 更新父任务进度
QModelIndex taskIndex = getTaskIndex(taskId);
if (taskIndex.isValid()) {
QModelIndex progressIndex = index(taskIndex.row(), ColProgress, taskIndex.parent());
emit dataChanged(progressIndex, progressIndex);
}
}
TimedTask* TaskTreeModel::getTask(int taskId)
{
int idx = findTaskDataIndex(taskId);
if (idx >= 0) {
return &m_tasks[idx];
}
return nullptr;
}
SubTask* TaskTreeModel::getSubTask(int taskId, int subTaskIndex)
{
TimedTask* task = getTask(taskId);
if (task && subTaskIndex >= 0 && subTaskIndex < task->subTasks.size()) {
return &task->subTasks[subTaskIndex];
}
return nullptr;
}
QModelIndex TaskTreeModel::getTaskIndex(int taskId) const
{
for (int i = 0; i < m_rootNode->childCount(); ++i) {
TaskTreeNode* node = m_rootNode->child(i);
if (node && node->taskId == taskId) {
return createIndex(i, 0, node);
}
}
return QModelIndex();
}
QModelIndex TaskTreeModel::getSubTaskIndex(int taskId, int subTaskIndex) const
{
TaskTreeNode* taskNode = findTaskNode(taskId);
if (taskNode && subTaskIndex < taskNode->childCount()) {
TaskTreeNode* subNode = taskNode->child(subTaskIndex);
if (subNode) {
return createIndex(subTaskIndex, 0, subNode);
}
}
return QModelIndex();
}
TaskTreeNode* TaskTreeModel::findTaskNode(int taskId) const
{
for (int i = 0; i < m_rootNode->childCount(); ++i) {
TaskTreeNode* node = m_rootNode->child(i);
if (node && node->taskId == taskId) {
return node;
}
}
return nullptr;
}
TaskTreeNode* TaskTreeModel::findSubTaskNode(int taskId, int subTaskIndex) const
{
TaskTreeNode* taskNode = findTaskNode(taskId);
if (taskNode && subTaskIndex < taskNode->childCount()) {
return taskNode->child(subTaskIndex);
}
return nullptr;
}
int TaskTreeModel::findTaskDataIndex(int taskId) const
{
for (int i = 0; i < m_tasks.size(); ++i) {
if (m_tasks[i].id == taskId) {
return i;
}
}
return -1;
}
QString TaskTreeModel::statusToString(TaskStatus status) const
{
switch (status) {
case TaskStatus::default: return QString::fromLocal8Bit("未调度");
case TaskStatus::Waiting: return QString::fromLocal8Bit("等待中");
case TaskStatus::Running: return QString::fromLocal8Bit("运行中");
case TaskStatus::Finished: return QString::fromLocal8Bit("已完成");
case TaskStatus::Skiped: return QString::fromLocal8Bit("已跳过");
case TaskStatus::Timeout: return QString::fromLocal8Bit("超时");
}
return "";
}
QString TaskTreeModel::subTaskTypeToString(SubTaskType type) const
{
switch (type)
{
case SubTaskType::HyperSpectual400_1000nm: return QString::fromLocal8Bit("高光谱 400-1000nm");
case SubTaskType::HyperSpectual1000_1700nm: return QString::fromLocal8Bit("高光谱 1000-1700nm");
case SubTaskType::SingleLensReflex: return QString::fromLocal8Bit("单反相机");
case SubTaskType::DepthCamera: return QString::fromLocal8Bit("深度相机");
case SubTaskType::ObtainingDepthInformation: return QString::fromLocal8Bit("探测深度信息");
case SubTaskType::AutoFocus: return QString::fromLocal8Bit("自动调焦");
case SubTaskType::LiftingPlatform: return QString::fromLocal8Bit("升降平台");
}
return QString::fromLocal8Bit("未知类型");
}
QString TaskTreeModel::formatDuration(double minutes) const
{
if (minutes <= 0) return "-";
int hours = static_cast<int>(minutes) / 60;
int mins = static_cast<int>(minutes) % 60;
int secs = static_cast<int>((minutes - static_cast<int>(minutes)) * 60);
if (hours > 0) {
return QString::fromLocal8Bit(("%1时%2分%3秒")).arg(hours).arg(mins).arg(secs);
}
else if (mins > 0) {
return QString::fromLocal8Bit(("%1分%2秒")).arg(mins).arg(secs);
}
else {
return QString::fromLocal8Bit(("%1秒")).arg(secs);
}
}
QColor TaskTreeModel::statusColor(TaskStatus status) const
{
switch (status) {
case TaskStatus::Waiting: return QColor("#121945"); // 浅黄
case TaskStatus::Running: return QColor("#121945"); // 浅绿
case TaskStatus::Finished: return QColor("#121945"); // 浅蓝
case TaskStatus::Skiped: return QColor("#121945"); // 浅灰
}
return QColor("#121945");
}
QString TaskTreeModel::formatCountdown(qint64 seconds) const
{
if (seconds < 0) {
return QString::fromLocal8Bit("已超时");
}
int hours = static_cast<int>(seconds) / 3600;
int mins = (static_cast<int>(seconds) % 3600) / 60;
int secs = static_cast<int>(seconds) % 60;
return QString("%1:%2:%3")
.arg(hours, 2, 10, QChar('0'))
.arg(mins, 2, 10, QChar('0'))
.arg(secs, 2, 10, QChar('0'));
}
void TaskTreeModel::onCountdownTimerTimeout()
{
for (int i = 0; i < m_tasks.size(); ++i)
{
const TimedTask& task = m_tasks[i];
QModelIndex taskIndex = getTaskIndex(task.id);
if (taskIndex.isValid())
{
QModelIndex countdownIndex = index(taskIndex.row(), ColCountdown, taskIndex.parent());
emit dataChanged(countdownIndex, countdownIndex);
}
}
}

118
HPPA/TaskTreeModel.h Normal file
View File

@ -0,0 +1,118 @@
#pragma once
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
#include <QTimer>
#include "TimedDataCollectionDataStructures.h"
// 树节点类型
enum class TreeNodeType {
Root,
Task,
SubTask
};
// 树节点数据
class TaskTreeNode
{
public:
explicit TaskTreeNode(TaskTreeNode* parent = nullptr);
~TaskTreeNode();
void appendChild(TaskTreeNode* child);
void removeChild(int index);
TaskTreeNode* child(int row);
int childCount() const;
int row() const;
TaskTreeNode* parentNode();
TreeNodeType nodeType = TreeNodeType::Root;
int taskId = -1; // 任务ID
int subTaskIndex = -1; // 子任务索引(仅子任务节点有效)
// 直接存储数据指针,方便更新
TimedTask* taskData = nullptr;
SubTask* subTaskData = nullptr;
private:
QVector<TaskTreeNode*> m_children;
TaskTreeNode* m_parent;
};
// 树形模型
class TaskTreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
enum Column {
ColName = 0, // 任务名称/子任务类型
ColScheduledTime, // 计划时间
ColCountdown, // 倒计时
ColStartTime, // 开始时间
ColEndTime, // 结束时间
ColDuration, // 耗时
ColEstimatedDuration, // 预测耗时
ColStatus, // 状态
ColProgress, // 进度(仅任务有效)
ColPath, // 路径
ColumnCount
};
explicit TaskTreeModel(QObject* parent = nullptr);
~TaskTreeModel();
// QAbstractItemModel 接口实现
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex& index) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
// 数据操作
void setTasks(const QVector<TimedTask>& tasks);
void updateTask(const TimedTask& task);
void updateSubTask(int taskId, int subTaskIndex, const SubTask& subTask);
void updateTaskStatus(int taskId, TaskStatus status);
void setTaskAndSubtaskStatus(int taskId, TaskStatus status);
void updateSubTaskStatusAndProgress(int taskId, int subTaskIndex, TaskStatus status);
void updateSubTaskStatus(int taskId, int subTaskIndex, TaskStatus status);
void updateProgress(int taskId);
// 获取数据
QVector<TimedTask>& tasks() { return m_tasks; }
const QVector<TimedTask>& tasks() const { return m_tasks; }
TimedTask* getTask(int taskId);
SubTask* getSubTask(int taskId, int subTaskIndex);
// 获取模型索引
QModelIndex getTaskIndex(int taskId) const;
QModelIndex getSubTaskIndex(int taskId, int subTaskIndex) const;
signals:
void taskUpdated(int taskId);
void subTaskUpdated(int taskId, int subTaskIndex);
private slots:
void onCountdownTimerTimeout();
private:
void setupModelData();
void clearTree();
TaskTreeNode* findTaskNode(int taskId) const;
TaskTreeNode* findSubTaskNode(int taskId, int subTaskIndex) const;
int findTaskDataIndex(int taskId) const;
QString statusToString(TaskStatus status) const;
QString subTaskTypeToString(SubTaskType type) const;
QString formatDuration(double minutes) const;
QColor statusColor(TaskStatus status) const;
QString formatCountdown(qint64 seconds) const;
TaskTreeNode* m_rootNode;
QVector<TimedTask> m_tasks;
QTimer* m_countdownTimer;
};

View File

@ -0,0 +1,518 @@
#include "TimedDataCollection.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QGroupBox>
#include <QSplitter>
TimedDataCollection::TimedDataCollection(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
setupUI();
// 初始化调度器
m_scheduler = new TaskScheduler(this);
setupConnections();
// 连接按钮信号
connect(ui.start_btn, &QPushButton::clicked, this, &TimedDataCollection::startScheduler);
connect(ui.stop_btn, &QPushButton::clicked, this, &TimedDataCollection::stopScheduler);
connect(ui.expandAll_btn, &QPushButton::clicked, ui.taskTreeView, &QTreeView::expandAll);
connect(ui.collapseAll_btn, &QPushButton::clicked, ui.taskTreeView, &QTreeView::collapseAll);
connect(ui.taskFileSelect_btn, &QPushButton::clicked, this, &TimedDataCollection::onSelectTaskFile);
// 树视图交互信号
connect(ui.taskTreeView, &QTreeView::clicked,
this, &TimedDataCollection::onTreeItemClicked);
connect(ui.taskTreeView, &QTreeView::doubleClicked,
this, &TimedDataCollection::onTreeItemDoubleClicked);
connect(ui.taskTreeView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &TimedDataCollection::onTreeSelectionChanged);
}
void TimedDataCollection::setupUI()
{
// 设置窗口大小
//resize(1200, 600);
//setWindowTitle("定时数据采集系统");
// 创建任务树形模型
m_taskModel = new TaskTreeModel(this);
// 创建树形视图
ui.taskTreeView->setModel(m_taskModel);
// 配置树形视图
ui.taskTreeView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui.taskTreeView->setSelectionMode(QAbstractItemView::SingleSelection);
ui.taskTreeView->setAlternatingRowColors(true);
ui.taskTreeView->setAnimated(true);
ui.taskTreeView->setExpandsOnDoubleClick(true);
ui.taskTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui.taskTreeView->setUniformRowHeights(true);
ui.taskTreeView->setIndentation(25);
// 配置表头
QHeaderView* header = ui.taskTreeView->header();
header->setStretchLastSection(true);
header->setSectionResizeMode(QHeaderView::Interactive);
header->setDefaultAlignment(Qt::AlignCenter);
// 设置列宽
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColName, 200);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColScheduledTime, 150);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColCountdown, 100);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColStartTime, 100);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColEndTime, 100);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColDuration, 100);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColEstimatedDuration, 100);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColStatus, 100);
ui.taskTreeView->setColumnWidth(TaskTreeModel::ColProgress, 80);
// 创建状态标签
ui.statusLabel->setStyleSheet(
"QLabel {"
" background-color: #3856B8;"
" border: 1px solid #2f6bff;"
" border-radius: 4px;"
" padding: 8px;"
" font-size: 12px;"
"}"
);
}
void TimedDataCollection::setupConnections()
{
// 调度器信号连接
connect(m_scheduler, &TaskScheduler::taskStarted,
this, &TimedDataCollection::onTaskStarted);
connect(m_scheduler, &TaskScheduler::taskFinished,
this, &TimedDataCollection::onTaskFinished);
connect(m_scheduler, &TaskScheduler::subTaskStarted,
this, &TimedDataCollection::onSubTaskStarted);
connect(m_scheduler, &TaskScheduler::subTaskFinished,
this, &TimedDataCollection::onSubTaskFinished);
connect(m_scheduler, &TaskScheduler::taskDataChanged,
this, &TimedDataCollection::onTaskDataChanged);
connect(m_scheduler, &TaskScheduler::errorOccurred,
this, &TimedDataCollection::onErrorOccurred);
// 采集相关信号透传
connect(m_scheduler, &TaskScheduler::hyperCamParm,
this, &TimedDataCollection::hyperCamParm);
connect(m_scheduler, &TaskScheduler::camParm,
this, &TimedDataCollection::camParm);
connect(m_scheduler, &TaskScheduler::motorParm,
this, &TimedDataCollection::motorParm);
connect(m_scheduler, &TaskScheduler::startRecordSignal,
this, &TimedDataCollection::startRecordSignal);
connect(m_scheduler, &TaskScheduler::ObtainingDepthInformationSignals, this, &TimedDataCollection::ObtainingDepthInformationSignals);
connect(m_scheduler, &TaskScheduler::LiftingPlatformSignals, this, &TimedDataCollection::LiftingPlatformSignals);
connect(m_scheduler, &TaskScheduler::AutoFocusSignals, this, &TimedDataCollection::AutoFocusSignals);
connect(m_scheduler, &TaskScheduler::switchHalogenLampSignal,
this, &TimedDataCollection::switchHalogenLampSignal);
connect(m_scheduler, &TaskScheduler::switchD65LampSignal,
this, &TimedDataCollection::switchD65LampSignal);
connect(m_scheduler, &TaskScheduler::switchSlrSignal,
this, &TimedDataCollection::switchSlrSignal);
connect(this, &TimedDataCollection::sequenceCompleteSignal,
m_scheduler, &TaskScheduler::sequenceCompleteSignal);
connect(this, &TimedDataCollection::Back2OriginSignal,
m_scheduler, &TaskScheduler::Back2OriginSignal);
}
TimedDataCollection::~TimedDataCollection()
{
if (m_scheduler) {
m_scheduler->stop();
}
}
void TimedDataCollection::onSelectTaskFile()
{
if (m_scheduler->isRunning())
{
return;
}
QString filePath = QFileDialog::getOpenFileName(this,
tr("Select Task File"),
QString(),
tr("JSON Files (*.json);;All Files (*)"));
if (filePath.isEmpty()) {
return;
}
ui.taskFileSelect_lineEdit->setText(filePath);
readTimedTaskFromFile(filePath);
}
// ==================== 任务状态更新槽实现 ====================
void TimedDataCollection::onTaskStarted(int taskId)
{
m_currentTaskId = taskId;
m_currentSubTaskIndex = -1;
// 展开当前运行的任务
expandRunningTask();
updateStatusBar();
emit taskStarted(taskId);
}
void TimedDataCollection::onTaskFinished(int taskId, bool success)
{
if (m_currentTaskId == taskId) {
m_currentTaskId = -1;
m_currentSubTaskIndex = -1;
}
updateStatusBar();
emit taskFinished(taskId, success);
}
void TimedDataCollection::onSubTaskStarted(int taskId, int subTaskIndex)
{
m_currentSubTaskIndex = subTaskIndex;
m_taskModel->updateProgress(taskId);
// 滚动到当前子任务
QModelIndex subTaskIndex_model = m_taskModel->getSubTaskIndex(taskId, subTaskIndex);
if (subTaskIndex_model.isValid()) {
ui.taskTreeView->scrollTo(subTaskIndex_model);
ui.taskTreeView->setCurrentIndex(subTaskIndex_model);
}
updateStatusBar();
emit subTaskStarted(taskId, subTaskIndex);
}
void TimedDataCollection::onSubTaskFinished(int taskId, int subTaskIndex)
{
m_taskModel->updateSubTaskStatusAndProgress(taskId, subTaskIndex, TaskStatus::Finished);
updateStatusBar();
emit subTaskFinished(taskId, subTaskIndex);
}
void TimedDataCollection::onTaskDataChanged(const TimedTask& task)
{
// 核心:从 TaskExecutor 同步回来的完整任务数据
m_taskModel->updateTask(task);
updateStatusBar();
}
void TimedDataCollection::onErrorOccurred(const QString& error)
{
ui.statusLabel->setText(QString::fromLocal8Bit("错误: %1").arg(error));
ui.statusLabel->setStyleSheet(
"QLabel {"
" background-color: #3856B8;"
" border: 1px solid #2f6bff;"
" border-radius: 4px;"
" padding: 8px;"
" color: #e6eeff;"
"}"
);
QMessageBox::warning(this, "错误", error);
emit errorOccurred(error);
}
void TimedDataCollection::onTreeItemClicked(const QModelIndex& index)
{
if (!index.isValid()) return;
TaskTreeNode* node = static_cast<TaskTreeNode*>(index.internalPointer());
if (!node) return;
QString info;
if (node->nodeType == TreeNodeType::Task && node->taskData) {
info = QString::fromLocal8Bit("选中任务 %1 - 状态: %2")
.arg(node->taskData->id)
.arg(node->taskData->status == TaskStatus::Running ? "运行中" :
node->taskData->status == TaskStatus::Finished ? "已完成" : "等待中");
}
else if (node->nodeType == TreeNodeType::SubTask && node->subTaskData) {
info = QString::fromLocal8Bit("选中子任务 - 类型: %1")
.arg(m_taskModel->data(m_taskModel->index(index.row(),
TaskTreeModel::ColName, index.parent())).toString());
}
// 可以更新状态栏或其他UI
}
void TimedDataCollection::onTreeItemDoubleClicked(const QModelIndex& index)
{
if (!index.isValid()) return;
TaskTreeNode* node = static_cast<TaskTreeNode*>(index.internalPointer());
if (!node) return;
if (node->nodeType == TreeNodeType::Task && node->taskData) {
const TimedTask& task = *node->taskData;
QString details = QString::fromLocal8Bit(
"【任务详情】\n\n"
"任务ID: %1\n"
"计划时间: %2\n"
"开始时间: %3\n"
"结束时间: %4\n"
"耗时: %5 分钟\n"
"状态: %6\n"
"子任务数: %7\n"
"保存路径: %8\n"
"卤素灯预热时间: %9 分钟"
).arg(task.id)
.arg(task.scheduledTime.toString("yyyy-MM-dd HH:mm:ss"))
.arg(task.startTime.isValid() ? task.startTime.toString("yyyy-MM-dd HH:mm:ss") : "-")
.arg(task.endTime.isValid() ? task.endTime.toString("yyyy-MM-dd HH:mm:ss") : "-")
.arg(task.durationMinutes, 0, 'f', 2)
.arg(static_cast<int>(task.status))
.arg(task.subTasks.size())
.arg(task.savePath)
.arg(task.HalogenLampPreheatingTime_Minute);
QMessageBox::information(this, QString::fromLocal8Bit("任务详情"), details);
}
else if (node->nodeType == TreeNodeType::SubTask && node->subTaskData) {
const SubTask& subTask = *node->subTaskData;
QString typeStr;
switch (subTask.type) {
case SubTaskType::HyperSpectual400_1000nm: typeStr = QString::fromLocal8Bit("高光谱 400-1000nm"); break;
case SubTaskType::HyperSpectual1000_1700nm: typeStr = QString::fromLocal8Bit("高光谱 1000-1700nm"); break;
case SubTaskType::SingleLensReflex: typeStr = QString::fromLocal8Bit("单反相机"); break;
case SubTaskType::DepthCamera: typeStr = QString::fromLocal8Bit("深度相机"); break;
}
QString details = QString::fromLocal8Bit(
"【子任务详情】\n\n"
"类型: %1\n"
"开始时间: %2\n"
"结束时间: %3\n"
"耗时: %4 分钟\n"
"路径文件: %5\n"
"状态: %6"
).arg(typeStr)
.arg(subTask.startTime.isValid() ? subTask.startTime.toString("yyyy-MM-dd HH:mm:ss") : "-")
.arg(subTask.endTime.isValid() ? subTask.endTime.toString("yyyy-MM-dd HH:mm:ss") : "-")
.arg(subTask.durationMinutes, 0, 'f', 2)
.arg(subTask.pathLineFilePath)
.arg(static_cast<int>(subTask.status));
if (subTask.type == SubTaskType::HyperSpectual400_1000nm ||
subTask.type == SubTaskType::HyperSpectual1000_1700nm) {
details += QString::fromLocal8Bit("\n帧率: %1\n曝光时间: %2")
.arg(subTask.frameRate)
.arg(subTask.exposureTime);
}
QMessageBox::information(this, QString::fromLocal8Bit("子任务详情"), details);
}
}
void TimedDataCollection::onTreeSelectionChanged()
{
// 可以根据选择更新其他UI组件
}
void TimedDataCollection::updateStatusBar()
{
QString statusText;
QString styleSheet;
if (m_currentTaskId > 0) {
TimedTask* task = m_taskModel->getTask(m_currentTaskId);
if (task) {
int finished = 0;
for (const auto& sub : task->subTasks) {
if (sub.status == TaskStatus::Finished) finished++;
}
statusText = QString::fromLocal8Bit("▶ 正在执行任务 %1 | 子任务进度: %2/%3")
.arg(m_currentTaskId)
.arg(finished)
.arg(task->subTasks.size());
if (m_currentSubTaskIndex >= 0 && m_currentSubTaskIndex < task->subTasks.size()) {
QString subTypeStr;
switch (task->subTasks[m_currentSubTaskIndex].type) {
case SubTaskType::HyperSpectual400_1000nm: subTypeStr = QString::fromLocal8Bit("高光谱400-1000nm"); break;
case SubTaskType::HyperSpectual1000_1700nm: subTypeStr = QString::fromLocal8Bit("高光谱1000-1700nm"); break;
case SubTaskType::SingleLensReflex: subTypeStr = QString::fromLocal8Bit("单反相机"); break;
case SubTaskType::DepthCamera: subTypeStr = QString::fromLocal8Bit("深度相机"); break;
}
statusText += QString::fromLocal8Bit(" | 当前: %1").arg(subTypeStr);
}
styleSheet =
"QLabel {"
" background-color: #3856B8;"
" border: 1px solid #2f6bff;"
" border-radius: 4px;"
" padding: 8px;"
" color: #e6eeff;"
" font-weight: bold;"
"}";
}
}
else {
// 统计任务状态
int waiting = 0, running = 0, finished = 0;
for (const auto& task : m_taskModel->tasks()) {
switch (task.status) {
case TaskStatus::Waiting: waiting++; break;
case TaskStatus::Running: running++; break;
case TaskStatus::Finished: finished++; break;
default: break;
}
}
statusText = QString::fromLocal8Bit("任务统计 | 等待: %1 | 运行中: %2 | 已完成: %3 | 总计: %4")
.arg(waiting).arg(running).arg(finished)
.arg(m_taskModel->tasks().size());
styleSheet =
"QLabel {"
" background-color: #3856B8;"
" border: 1px solid #2f6bff;"
" border-radius: 4px;"
" padding: 8px;"
"}";
}
ui.statusLabel->setText(statusText);
ui.statusLabel->setStyleSheet(styleSheet);
}
void TimedDataCollection::expandRunningTask()
{
if (m_currentTaskId > 0) {
QModelIndex taskIndex = m_taskModel->getTaskIndex(m_currentTaskId);
if (taskIndex.isValid()) {
ui.taskTreeView->expand(taskIndex);
ui.taskTreeView->scrollTo(taskIndex);
ui.taskTreeView->setCurrentIndex(taskIndex);
}
}
}
void TimedDataCollection::readTimedTaskFromFile(const QString& filePath)
{
QVector<TimedTask> loadedTasks;
if (TimedDataCollectionDataStructuresReaderWriter::loadTasksFromFile(filePath, loadedTasks)) {
qDebug() << "Tasks loaded successfully, count:" << loadedTasks.size();
// 预测耗时:计算每个子任务和整个任务的预计耗时
for (int i = 0; i < loadedTasks.size(); ++i)
{
double totalEstimatedMinutes = 0.0;
for (int j = 0; j < loadedTasks[i].subTasks.size(); ++j)
{
loadedTasks[i].subTasks[j].durationMinutes = 0.0; // 初始化实际耗时为0
QString pathLineFilePath = loadedTasks[i].subTasks[j].pathLineFilePath;
if (!pathLineFilePath.isEmpty())
{
double estimatedMinutes = PathLineManager::calculateTimeFromFile(pathLineFilePath);
loadedTasks[i].subTasks[j].estimatedDurationMinutes = estimatedMinutes;
totalEstimatedMinutes += loadedTasks[i].subTasks[j].estimatedDurationMinutes;
}
}
double slrTimeMinute = 135 / 60;
loadedTasks[i].estimatedDurationMinutes = totalEstimatedMinutes + loadedTasks[i].HalogenLampPreheatingTime_Minute + slrTimeMinute;
loadedTasks[i].durationMinutes = 0.0; // 初始化实际耗时为0
}
m_taskModel->setTasks(loadedTasks);
ui.taskTreeView->expandAll(); // 默认展开所有任务
// 更新调度器
if (m_scheduler)
{
m_scheduler->loadTasks(loadedTasks);
}
updateStatusBar();
}
else {
qDebug() << "Failed to load tasks from:" << filePath;
QMessageBox::warning(this, "加载失败",
QString("无法从文件加载任务:\n%1").arg(filePath));
}
}
void TimedDataCollection::startScheduler()
{
if (m_scheduler)
{
if (m_scheduler->isRunning())
{
return;
}
for (size_t i = 0; i < m_taskModel->tasks().size(); i++)
{
m_taskModel->setTaskAndSubtaskStatus(m_taskModel->tasks()[i].id, TaskStatus::Waiting);
}
m_scheduler->loadTasks(m_taskModel->tasks());
m_scheduler->start();
ui.statusLabel->setText(QString::fromLocal8Bit("调度器已启动,等待任务执行..."));
ui.statusLabel->setStyleSheet(
"QLabel {"
" background-color: #3856B8;"
" border: 1px solid #2f6bff;"
" border-radius: 4px;"
" padding: 8px;"
" color: #e6eeff;"
"}");
}
}
void TimedDataCollection::stopScheduler()
{
if (m_scheduler) {
for (size_t i = 0; i < m_taskModel->tasks().size(); i++)
{
m_taskModel->setTaskAndSubtaskStatus(m_taskModel->tasks()[i].id, TaskStatus::default);
}
m_scheduler->stop();
m_currentTaskId = -1;
m_currentSubTaskIndex = -1;
ui.statusLabel->setText(QString::fromLocal8Bit("调度器已停止"));
ui.statusLabel->setStyleSheet(
"QLabel {"
" background-color: #3856B8;"
" border: 1px solid #2f6bff;"
" border-radius: 4px;"
" padding: 8px;"
" color: #e6eeff;"
"}");
}
}
void TimedDataCollection::subTaskCompleted(int status)
{
emit sequenceCompleteSignal(status);
}
void TimedDataCollection::onBack2Origin()
{
emit Back2OriginSignal();
}

View File

@ -0,0 +1,81 @@
#pragma once
#include <QDialog>
#include <QTreeView>
#include <QHeaderView>
#include <QLabel>
#include <QFileDialog>
#include "ui_TimedDataCollection_ui.h"
#include "TimedDataCollectionDataStructures.h"
#include "TaskTreeModel.h"
#include "PathLine.h"
class TimedDataCollection : public QDialog
{
Q_OBJECT
public:
TimedDataCollection(QWidget* parent = nullptr);
~TimedDataCollection();
void readTimedTaskFromFile(const QString& filePath);
public Q_SLOTS:
void startScheduler();
void stopScheduler();
void subTaskCompleted(int status);
void onBack2Origin();
private Q_SLOTS:
// 任务状态更新槽
void onTaskStarted(int taskId);
void onTaskFinished(int taskId, bool success);
void onSubTaskStarted(int taskId, int subTaskIndex);
void onSubTaskFinished(int taskId, int subTaskIndex);
void onTaskDataChanged(const TimedTask& task);
void onErrorOccurred(const QString& error);
// 树视图交互
void onTreeItemClicked(const QModelIndex& index);
void onTreeItemDoubleClicked(const QModelIndex& index);
void onTreeSelectionChanged();
Q_SIGNALS:
void taskStarted(int taskId);
void taskFinished(int taskId, bool success);
void subTaskStarted(int taskId, int subTaskIndex);
void subTaskFinished(int taskId, int subTaskIndex);
void errorOccurred(const QString& error);
void hyperCamParm(int camType, double f, double e, QString filePath, QString fileName);
void camParm(int camType, int captureIntervalSeconds, QString folder);
void motorParm(QString pathLineFilePath);
void startRecordSignal(int camType);
void ObtainingDepthInformationSignals(SubTask info);
void LiftingPlatformSignals(SubTask info);
void AutoFocusSignals(SubTask info);
void switchHalogenLampSignal(int state);
void switchD65LampSignal(int state);
void switchSlrSignal(int state);
void sequenceCompleteSignal(int status);
void Back2OriginSignal();
private:
void setupUI();
void setupConnections();
void updateStatusBar();
void expandRunningTask();
void onSelectTaskFile();
Ui::TimedDataCollection_ui ui;
TaskTreeModel* m_taskModel; // 任务树形模型
TaskScheduler* m_scheduler;
int m_currentTaskId = -1;
int m_currentSubTaskIndex = -1;
};

View File

@ -0,0 +1,824 @@
#include "TimedDataCollectionDataStructures.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QTextStream>
#include <QDebug>
#include <algorithm>
// ==================== 公共接口实现 ====================
bool TimedDataCollectionDataStructuresReaderWriter::saveTasksToFile(const QString& filePath, const QVector<TimedTask>& tasks)
{
QJsonObject root;
root["version"] = "1.0";
root["taskCount"] = tasks.size();
QJsonArray tasksArray;
for (const auto& task : tasks) {
tasksArray.append(timedTaskToJson(task));
}
root["tasks"] = tasksArray;
QJsonDocument doc(root);
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning() << "Failed to open file for writing:" << filePath;
return false;
}
QTextStream out(&file);
//out.setEncoding(QStringConverter::Utf8);
out << doc.toJson(QJsonDocument::Indented);
file.close();
return true;
}
bool TimedDataCollectionDataStructuresReaderWriter::loadTasksFromFile(const QString& filePath, QVector<TimedTask>& tasks)
{
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qWarning() << "Failed to open file for reading:" << filePath;
return false;
}
QByteArray jsonData = file.readAll();
file.close();
QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);
if (parseError.error != QJsonParseError::NoError) {
qWarning() << "JSON parse error:" << parseError.errorString();
return false;
}
if (!doc.isObject()) {
qWarning() << "Invalid JSON root object";
return false;
}
QJsonObject root = doc.object();
QJsonArray tasksArray = root["tasks"].toArray();
tasks.clear();
tasks.reserve(tasksArray.size());
for (const auto& taskValue : tasksArray) {
if (!taskValue.isObject()) continue;
TimedTask task;
if (jsonToTimedTask(taskValue.toObject(), task)) {
tasks.append(task);
}
}
return true;
}
// ==================== 枚举转换函数 ====================
QString TimedDataCollectionDataStructuresReaderWriter::taskStatusToString(TaskStatus status)
{
switch (status) {
case TaskStatus::Waiting: return "Waiting";
case TaskStatus::Running: return "Running";
case TaskStatus::Finished: return "Finished";
default: return "Waiting";
}
}
TaskStatus TimedDataCollectionDataStructuresReaderWriter::stringToTaskStatus(const QString& str)
{
//if (str == "Running") return TaskStatus::Running;
//if (str == "Finished") return TaskStatus::Finished;
return TaskStatus::default;
}
QString TimedDataCollectionDataStructuresReaderWriter::subTaskTypeToString(SubTaskType type)
{
switch (type) {
case SubTaskType::HyperSpectual400_1000nm: return "HyperSpectual400_1000nm";
case SubTaskType::HyperSpectual1000_1700nm: return "HyperSpectual1000_1700nm";
case SubTaskType::SingleLensReflex: return "SingleLensReflex";
case SubTaskType::DepthCamera: return "DepthCamera";
default: return "Unknown";
}
}
SubTaskType TimedDataCollectionDataStructuresReaderWriter::stringToSubTaskType(const QString& str)
{
if (str == "HyperSpectual400_1000nm") return SubTaskType::HyperSpectual400_1000nm;
if (str == "HyperSpectual1000_1700nm") return SubTaskType::HyperSpectual1000_1700nm;
if (str == "SingleLensReflex") return SubTaskType::SingleLensReflex;
if (str == "DepthCamera") return SubTaskType::DepthCamera;
if (str == "ObtainingDepthInformation") return SubTaskType::ObtainingDepthInformation;
if (str == "AutoFocus") return SubTaskType::AutoFocus;
if (str == "LiftingPlatform") return SubTaskType::LiftingPlatform;
return SubTaskType::SingleLensReflex;
}
QString TimedDataCollectionDataStructuresReaderWriter::hyperImagerTypeToString(HyperImagerType type)
{
switch (type) {
case HyperImagerType::Pika_L: return "Pika_L";
case HyperImagerType::Pika_NIR: return "Pika_NIR";
default: return "Unknown";
}
}
HyperImagerType TimedDataCollectionDataStructuresReaderWriter::stringToHyperImagerType(const QString& str)
{
if (str == "Pika_L") return HyperImagerType::Pika_L;
if (str == "Pika_NIR") return HyperImagerType::Pika_NIR;
return HyperImagerType::Pika_L;
}
// ==================== SubTask序列化 ====================
QJsonObject TimedDataCollectionDataStructuresReaderWriter::subTaskToJson(const SubTask& subTask)
{
QJsonObject obj;
obj["type"] = subTaskTypeToString(subTask.type);
obj["startTime"] = subTask.startTime.toString(Qt::ISODate);
obj["endTime"] = subTask.endTime.toString(Qt::ISODate);
obj["durationMinutes"] = subTask.durationMinutes;
obj["estimatedDurationMinutes"] = subTask.estimatedDurationMinutes;
obj["pathLineFilePath"] = subTask.pathLineFilePath;
obj["status"] = taskStatusToString(subTask.status);
obj["frameRate"] = subTask.frameRate;
obj["exposureTime"] = subTask.exposureTime;
obj["defaultRenderBand"] = subTask.defaultRenderBand;
obj["captureIntervalSeconds"] = subTask.captureIntervalSeconds;
obj["autoFocusHyperImagerType"] = hyperImagerTypeToString(subTask.autoFocusHyperImagerType);
obj["autoFocusMotorConfigFilePath"] = subTask.autoFocusMotorConfigFilePath;
obj["autoFocusX"] = subTask.autoFocusX;
obj["autoFocusY"] = subTask.autoFocusY;
obj["depthAlgorithm"] = subTask.depthAlgorithm;
obj["depthInfoX"] = subTask.depthInfoX;
obj["depthInfoY"] = subTask.depthInfoY;
obj["averageNumberOfTimes"] = subTask.averageNumberOfTimes;
obj["percentageOfEffectiveArea"] = subTask.percentageOfEffectiveArea;
obj["depthType"] = subTask.depthType;
obj["depthRangePercentage"] = subTask.depthRangePercentage;
return obj;
}
bool TimedDataCollectionDataStructuresReaderWriter::jsonToSubTask(const QJsonObject& json, SubTask& subTask)
{
subTask.type = stringToSubTaskType(json["type"].toString());
subTask.startTime = QDateTime::fromString(QString(), Qt::ISODate);
subTask.endTime = QDateTime::fromString(QString(), Qt::ISODate);
subTask.durationMinutes = json["durationMinutes"].toDouble();
subTask.estimatedDurationMinutes = json["estimatedDurationMinutes"].toDouble();
subTask.pathLineFilePath = json["pathLineFilePath"].toString();
subTask.status = stringToTaskStatus(json["status"].toString());
subTask.frameRate = json["frameRate"].toDouble();
subTask.exposureTime = json["exposureTime"].toDouble();
subTask.defaultRenderBand = json["defaultRenderBand"].toInt();
subTask.captureIntervalSeconds = json["captureIntervalSeconds"].toDouble();
subTask.autoFocusHyperImagerType = stringToHyperImagerType(json["autoFocusHyperImagerType"].toString());
subTask.autoFocusMotorConfigFilePath = json["autoFocusMotorConfigFilePath"].toString();
subTask.autoFocusX = json["autoFocusX"].toDouble();
subTask.autoFocusY = json["autoFocusY"].toDouble();
subTask.depthAlgorithm = json["depthAlgorithm"].toInt();
subTask.depthInfoX = json["depthInfoX"].toDouble();
subTask.depthInfoY = json["depthInfoY"].toDouble();
subTask.averageNumberOfTimes = json["averageNumberOfTimes"].toInt();
subTask.percentageOfEffectiveArea = json["percentageOfEffectiveArea"].toDouble();
subTask.depthType = json["depthType"].toInt();
subTask.depthRangePercentage = json["depthRangePercentage"].toDouble();
return true;
}
// ==================== TimedTask序列化 ====================
QJsonObject TimedDataCollectionDataStructuresReaderWriter::timedTaskToJson(const TimedTask& task)
{
QJsonObject obj;
obj["id"] = task.id;
obj["scheduledTime"] = task.scheduledTime.toString(Qt::ISODate);
obj["startTime"] = task.startTime.toString(Qt::ISODate);
obj["endTime"] = task.endTime.toString(Qt::ISODate);
obj["durationMinutes"] = task.durationMinutes;
obj["estimatedDurationMinutes"] = task.estimatedDurationMinutes;
obj["savePath"] = task.savePath;
obj["status"] = taskStatusToString(task.status);
obj["HalogenLampPreheatingTime_Minute"] = task.HalogenLampPreheatingTime_Minute;
QJsonArray subTasksArray;
for (const auto& subTask : task.subTasks) {
subTasksArray.append(subTaskToJson(subTask));
}
obj["subTasks"] = subTasksArray;
return obj;
}
bool TimedDataCollectionDataStructuresReaderWriter::jsonToTimedTask(const QJsonObject& json, TimedTask& task)
{
task.id = json["id"].toInt();
task.scheduledTime = QDateTime::fromString(json["scheduledTime"].toString(), Qt::ISODate);
task.startTime = QDateTime::fromString(QString(), Qt::ISODate);
task.endTime = QDateTime::fromString(QString(), Qt::ISODate);
task.durationMinutes = json["durationMinutes"].toDouble();
task.estimatedDurationMinutes = json["estimatedDurationMinutes"].toDouble();
task.savePath = json["savePath"].toString();
task.status = stringToTaskStatus(json["status"].toString());
task.HalogenLampPreheatingTime_Minute = json["HalogenLampPreheatingTime_Minute"].toDouble();
QJsonArray subTasksArray = json["subTasks"].toArray();
task.subTasks.clear();
task.subTasks.reserve(subTasksArray.size());
for (const auto& subTaskValue : subTasksArray) {
if (!subTaskValue.isObject()) continue;
SubTask subTask;
if (jsonToSubTask(subTaskValue.toObject(), subTask)) {
task.subTasks.append(subTask);
}
}
return true;
}
// ==================== TaskExecutor 实现 ====================
TaskExecutor::TaskExecutor(QObject* parent)
: QObject(parent)
, m_currentSubTaskIndex(-1)
, m_isRunning(false)
{
}
TaskExecutor::~TaskExecutor()
{
stop();
}
void TaskExecutor::execute(const TimedTask& task)
{
if (m_isRunning) {
qWarning() << "TaskExecutor: Already running, ignoring execute request";
return;
}
m_task = task;
m_task.startTime = QDateTime::currentDateTime();
m_task.status = TaskStatus::Running;
emit taskUpdated(m_task);
m_currentSubTaskIndex = -1;
m_isRunning = true;
qDebug() << "TaskExecutor: Starting task" << task.id;
makeFolder(m_task.savePath);
double sleepTimeSecond = 1;
QTimer::singleShot(sleepTimeSecond * 1000, this, &TaskExecutor::executeNextSubTask);
}
void TaskExecutor::printMsgAndTime(QString msg)
{
QDateTime now = QDateTime::currentDateTime();
QString timeString = now.toString("yyyy-MM-dd hh:mm:ss.zzz");
qDebug() << msg + " time:" << timeString;
}
void TaskExecutor::stop()
{
if (!m_isRunning) return;
qDebug() << "TaskExecutor: Stopping task" << m_task.id;
m_isRunning = false;
emit finished(false);
}
void TaskExecutor::makeFolder(QString savePath)
{
QDir dir(savePath);
if (!dir.exists()) {
if (dir.mkpath(".")) {
qDebug() << "TaskExecutor: Created data folder:" << savePath;
}
else {
qWarning() << "TaskExecutor: Failed to create data folder:" << savePath;
}
}
else {
qDebug() << "TaskExecutor: Data folder already exists:" << savePath;
}
}
QString TaskExecutor::makeSubTaskDataFolder(QString suffix)
{
QString dateStr = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss");
QString folderPath = m_task.savePath + QDir::separator() + dateStr + "_" + suffix;
makeFolder(folderPath);
return folderPath;
}
void TaskExecutor::onSequenceComplete(int status)
{
if (!m_isRunning) return;
qDebug() << "TaskExecutor: Sequence complete, status:" << status;
// 更新当前子任务状态
if (m_currentSubTaskIndex < m_task.subTasks.size()) {
SubTask& subTask = m_task.subTasks[m_currentSubTaskIndex];
subTask.status = (status == 0) ? TaskStatus::Finished : TaskStatus::Waiting;
subTask.endTime = QDateTime::currentDateTime();
subTask.durationMinutes = (double)subTask.startTime.secsTo(subTask.endTime) / 60;
qDebug() << "TaskExecutor: subtask " << m_currentSubTaskIndex << " time consuming(Minutes): " << subTask.durationMinutes;
// 拷贝subTask.pathLineFilePath到m_currentFolder
if (!subTask.pathLineFilePath.isEmpty() && QFile::exists(subTask.pathLineFilePath)) {
QFileInfo fileInfo(subTask.pathLineFilePath);
QString destPath = m_currentFolder + QDir::separator() + fileInfo.fileName();
if (QFile::copy(subTask.pathLineFilePath, destPath)) {
qDebug() << "TaskExecutor: Copied path line file to" << destPath;
}
else {
qDebug() << "TaskExecutor: Failed to copy path line file from" << subTask.pathLineFilePath << "to" << destPath;
}
}
emit subTaskFinished(m_currentSubTaskIndex, subTask.type, (status == 0));
emit taskUpdated(m_task);
}
//当前任务已经完成,正确关闭灯光或者电源
ensurePostTaskLighting();
emit taskUpdated(m_task);
}
void TaskExecutor::ensurePreTaskLighting()
{
SubTaskType currentTaskType = m_task.subTasks[m_currentSubTaskIndex].type;
if (currentTaskType != SubTaskType::HyperSpectual400_1000nm &&
currentTaskType != SubTaskType::HyperSpectual1000_1700nm)
{
emit switchHalogenLampSignal(0);
}
if (currentTaskType != SubTaskType::SingleLensReflex &&
currentTaskType != SubTaskType::DepthCamera &&
currentTaskType != SubTaskType::ObtainingDepthInformation)
{
emit switchD65LampSignal(0);
}
}
void TaskExecutor::ensurePostTaskLighting()
{
SubTaskType currentTaskType = m_task.subTasks[m_currentSubTaskIndex].type;
if (currentTaskType == SubTaskType::SingleLensReflex ||
currentTaskType == SubTaskType::DepthCamera ||
currentTaskType == SubTaskType::ObtainingDepthInformation)
{
emit switchD65LampSignal(0);
}
int nestSubTaskIndex = m_currentSubTaskIndex + 1;
if (nestSubTaskIndex >= m_task.subTasks.size())
{
emit switchD65LampSignal(0);
emit switchSlrSignal(0);
emit switchHalogenLampSignal(0);
return;
}
// 判断下一次的任务是否为高光谱任务,如果不是就关闭卤素灯
SubTaskType nestTaskType = m_task.subTasks[nestSubTaskIndex].type;
if (nestTaskType != SubTaskType::HyperSpectual400_1000nm &&
nestTaskType != SubTaskType::HyperSpectual1000_1700nm)
{
emit switchHalogenLampSignal(0);
}
}
void TaskExecutor::onBack2Origin()
{
// 关闭单反电源
switch (m_task.subTasks[m_currentSubTaskIndex].type)
{
case SubTaskType::SingleLensReflex:
{
emit switchSlrSignal(0);
break;
}
}
// 检查是否还有更多子任务
int nestSubTaskIndex = m_currentSubTaskIndex + 1;
if (nestSubTaskIndex < m_task.subTasks.size()) {
// 执行下一个子任务
if (m_task.subTasks[nestSubTaskIndex].type == SubTaskType::SingleLensReflex)
{
printMsgAndTime("Slr task,for weak up,please wait 135 seconds!");
emit switchSlrSignal(0);
QTimer::singleShot(135 * 1000, this, &TaskExecutor::executeNextSubTask);
}
else
{
QTimer::singleShot(1000, this, &TaskExecutor::executeNextSubTask);
}
}
else {
// 所有子任务完成
m_task.endTime = QDateTime::currentDateTime();
m_task.durationMinutes = (double)m_task.startTime.secsTo(m_task.endTime) / 60;
m_task.status = TaskStatus::Finished;
qDebug() << "TaskExecutor: task time consuming(Minutes): " << m_task.durationMinutes;
m_isRunning = false;
qDebug() << "TaskExecutor: All subtasks completed";
emit finished(true);
}
emit taskUpdated(m_task);
}
void TaskExecutor::onError(const QString& error)
{
if (!m_isRunning) return;
qWarning() << "TaskExecutor: Error occurred:" << error;
m_isRunning = false;
emit errorOccurred(error);
emit finished(false);
}
void TaskExecutor::executeNextSubTask()
{
m_currentSubTaskIndex++;
if (!m_isRunning || m_currentSubTaskIndex >= m_task.subTasks.size())
{
return;
}
SubTask& subTask = m_task.subTasks[m_currentSubTaskIndex];
subTask.status = TaskStatus::Running;
subTask.startTime = QDateTime::currentDateTime();
emit taskUpdated(m_task);
QString tmp = "TaskExecutor: Starting subtask" + QString::number(m_currentSubTaskIndex) + "type:" + static_cast<int>(subTask.type);
printMsgAndTime(tmp);
//printMsgAndTime("excute " + QString::number(m_currentSubTaskIndex) + " subTask: ");
//qDebug() << "TaskExecutor: Starting subtask" << m_currentSubTaskIndex
// << "type:" << static_cast<int>(subTask.type);
emit subTaskStarted(m_currentSubTaskIndex, subTask.type);
switch (subTask.type)
{
case SubTaskType::ObtainingDepthInformation:
{
//(1)移动到指定位置并通过深度相机获取深度信息(2)调整升降板高度(白板+调焦板)(3)回到零位(0,0)
emit switchD65LampSignal(1);
emit ObtainingDepthInformationSignals(subTask);
break;
}
case SubTaskType::AutoFocus:
{
switch (subTask.autoFocusHyperImagerType)
{
case HyperImagerType::Pika_L:
m_camType = 0;
m_currentFolder = makeSubTaskDataFolder("L");
emit hyperCamParm(m_camType, subTask.frameRate, subTask.exposureTime, m_currentFolder, "L");
break;
case HyperImagerType::Pika_NIR:
m_camType = 1;
m_currentFolder = makeSubTaskDataFolder("NIR");
emit hyperCamParm(m_camType, subTask.frameRate, subTask.exposureTime, m_currentFolder, "NIR");
break;
default:
break;
}
emit switchHalogenLampSignal(1);
//执行自动调焦任务
QTimer::singleShot(3 * 1000, this, &TaskExecutor::emitAutoFocusSignal);
break;
}
case SubTaskType::LiftingPlatform:
{
//执行升降平台任务
emit LiftingPlatformSignals(subTask);
break;
}
case SubTaskType::HyperSpectual400_1000nm:
{
m_camType = 0;
m_currentFolder = makeSubTaskDataFolder("L");
emit hyperCamParm(m_camType, subTask.frameRate, subTask.exposureTime, m_currentFolder, "L");
emit motorParm(subTask.pathLineFilePath);
// 打开卤素灯预热
emit switchHalogenLampSignal(1);
printMsgAndTime("open HalogenLamp");
double sleepTimeSecond = m_task.HalogenLampPreheatingTime_Minute * 60;
QTimer::singleShot(sleepTimeSecond * 1000, this, &TaskExecutor::emitRecordSignal);
break;
}
case SubTaskType::HyperSpectual1000_1700nm:
{
m_camType = 1;
m_currentFolder = makeSubTaskDataFolder("NIR");
emit hyperCamParm(m_camType, subTask.frameRate, subTask.exposureTime, m_currentFolder, "NIR");
emit motorParm(subTask.pathLineFilePath);
QTimer::singleShot(3 * 1000, this, &TaskExecutor::emitRecordSignal);
break;
}
case SubTaskType::SingleLensReflex:
{
m_camType = 2;
m_currentFolder = makeSubTaskDataFolder("SLR");
emit camParm(m_camType, 3, m_currentFolder);
emit motorParm(subTask.pathLineFilePath);
emit switchD65LampSignal(1);
emit switchSlrSignal(1);
QTimer::singleShot(3 * 1000, this, &TaskExecutor::emitRecordSignal);
break;
}
case SubTaskType::DepthCamera:
{
m_camType = 3;
m_currentFolder = makeSubTaskDataFolder("DepthCamera");
emit camParm(m_camType, 3, m_currentFolder);
emit motorParm(subTask.pathLineFilePath);
emit switchD65LampSignal(1);
QTimer::singleShot(3 * 1000, this, &TaskExecutor::emitRecordSignal);
break;
}
}
ensurePreTaskLighting();
}
void TaskExecutor::emitRecordSignal()
{
emit startRecordSignal(m_camType);
}
void TaskExecutor::emitAutoFocusSignal()
{
SubTask& subTask = m_task.subTasks[m_currentSubTaskIndex];
emit AutoFocusSignals(subTask);
}
// ==================== TaskScheduler 实现 ====================
TaskScheduler::TaskScheduler(QObject* parent)
: QObject(parent)
, m_timer(nullptr)
, m_currentExecutor(nullptr)
, m_currentTaskId(-1)
{
}
TaskScheduler::~TaskScheduler()
{
stop();
}
void TaskScheduler::loadTasks(const QVector<TimedTask>& tasks)
{
m_tasks = tasks;
qDebug() << "TaskScheduler: Loaded" << tasks.size() << "tasks";
}
void TaskScheduler::start()
{
if (m_timer) {
qDebug() << "TaskScheduler: Already running";
return;
}
qDebug() << "TaskScheduler: Starting";
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &TaskScheduler::checkTasks);
m_timer->start(1000); // 每秒检查一次
emit schedulerStateChanged(true);
}
void TaskScheduler::stop()
{
if (m_timer) {
m_timer->stop();
delete m_timer;
m_timer = nullptr;
}
if (m_currentExecutor) {
m_currentExecutor->stop();
m_currentExecutor->deleteLater();
m_currentExecutor = nullptr;
}
qDebug() << "TaskScheduler: Stopped";
emit schedulerStateChanged(false);
}
void TaskScheduler::checkTasks()
{
// 检查是否所有任务都不需要执行
bool allTasksDone = std::all_of(m_tasks.begin(), m_tasks.end(),
[](const TimedTask& task) {
return task.status != TaskStatus::Waiting;
});
if (allTasksDone)
{
std::cerr << "TaskScheduler::checkTasks,没有任务等待执行,停止调度器" << std::endl;
stop();
}
QDateTime now = QDateTime::currentDateTime();
if (m_currentTaskId >= 0)//有任务正在执行
{
return;
}
for (auto& task : m_tasks)
{
if (task.status != TaskStatus::Waiting) continue;
// 超过计划时间threSecs,认为任务已过时,跳过
qint64 threSecs = 30;
if (task.scheduledTime.addSecs(threSecs) < now)
{
std::cerr << "TaskScheduler::checkTasks,任务已过时,跳过:" << task.id << std::endl;
task.status = TaskStatus::Timeout;
for (size_t i = 0; i < task.subTaskCount(); i++)
{
task.subTasks[i].status = TaskStatus::Timeout;
}
emit taskDataChanged(task);
continue;
}
if (task.scheduledTime > now) continue;
qint64 fireThreSecs = 5;
if (task.scheduledTime.addSecs(-1 * fireThreSecs) < now && task.scheduledTime.addSecs(fireThreSecs) > now)// 到达计划时间,启动任务
{
std::cerr << "TaskScheduler::checkTasks,到达计划时间,启动任务" << std::endl;
executeTask(task);
break; // 一次只执行一个任务
}
}
}
void TaskScheduler::onTaskFinished(bool success)
{
if (m_currentTaskId > 0) {
TaskStatus status = success ? TaskStatus::Finished : TaskStatus::Waiting;
updateTaskStatus(m_currentTaskId, status);
emit taskFinished(m_currentTaskId, success);
}
// 清理执行器
if (m_currentExecutor) {
m_currentExecutor->deleteLater();
m_currentExecutor = nullptr;
}
m_currentTaskId = -1;
}
void TaskScheduler::onSubTaskStarted(int subTaskIndex, SubTaskType type)
{
if (m_currentTaskId > 0) {
emit subTaskStarted(m_currentTaskId, subTaskIndex);
}
}
void TaskScheduler::onSubTaskFinished(int subTaskIndex, SubTaskType type, bool success)
{
if (m_currentTaskId > 0) {
emit subTaskFinished(m_currentTaskId, subTaskIndex);
}
}
void TaskScheduler::onExecutorError(const QString& error)
{
emitError(error);
}
void TaskScheduler::executeTask(TimedTask& task)
{
qDebug() << "TaskScheduler: Executing task" << task.id;
//updateTaskStatus(task.id, TaskStatus::Running);
m_currentTaskId = task.id;
//emit taskStarted(task.id);
// 创建任务执行器
m_currentExecutor = new TaskExecutor(this);
// 连接信号
connect(m_currentExecutor, &TaskExecutor::finished,
this, &TaskScheduler::onTaskFinished);
connect(m_currentExecutor, &TaskExecutor::subTaskStarted,
this, &TaskScheduler::onSubTaskStarted);
connect(m_currentExecutor, &TaskExecutor::subTaskFinished,
this, &TaskScheduler::onSubTaskFinished);
connect(m_currentExecutor, &TaskExecutor::errorOccurred,
this, &TaskScheduler::onExecutorError);
// 采集相关信号透传
connect(m_currentExecutor, &TaskExecutor::hyperCamParm,
this, &TaskScheduler::hyperCamParm);
connect(m_currentExecutor, &TaskExecutor::camParm,
this, &TaskScheduler::camParm);
connect(m_currentExecutor, &TaskExecutor::motorParm,
this, &TaskScheduler::motorParm);
connect(m_currentExecutor, &TaskExecutor::startRecordSignal,
this, &TaskScheduler::startRecordSignal);
connect(m_currentExecutor, &TaskExecutor::ObtainingDepthInformationSignals, this, &TaskScheduler::ObtainingDepthInformationSignals);
connect(m_currentExecutor, &TaskExecutor::LiftingPlatformSignals, this, &TaskScheduler::LiftingPlatformSignals);
connect(m_currentExecutor, &TaskExecutor::AutoFocusSignals, this, &TaskScheduler::AutoFocusSignals);
connect(m_currentExecutor, &TaskExecutor::switchHalogenLampSignal, this, &TaskScheduler::switchHalogenLampSignal);
connect(m_currentExecutor, &TaskExecutor::switchD65LampSignal, this, &TaskScheduler::switchD65LampSignal);
connect(m_currentExecutor, &TaskExecutor::switchSlrSignal, this, &TaskScheduler::switchSlrSignal);
connect(this, &TaskScheduler::sequenceCompleteSignal, m_currentExecutor, &TaskExecutor::onSequenceComplete);
connect(this, &TaskScheduler::Back2OriginSignal, m_currentExecutor, &TaskExecutor::onBack2Origin);
connect(m_currentExecutor, &TaskExecutor::taskUpdated,
this, [this](const TimedTask& updatedTask) {
for (int i = 0; i < m_tasks.size(); ++i) {
if (m_tasks[i].id == updatedTask.id) {
m_tasks[i] = updatedTask;
break;
}
}
emit taskDataChanged(updatedTask);
});
// 开始执行
m_currentExecutor->execute(task);
}
void TaskScheduler::updateTaskStatus(int taskId, TaskStatus status)
{
for (auto& task : m_tasks) {
if (task.id == taskId) {
task.status = status;
if (status == TaskStatus::Running) {
task.startTime = QDateTime::currentDateTime();
}
else if (status == TaskStatus::Finished) {
task.endTime = QDateTime::currentDateTime();
}
break;
}
}
}
void TaskScheduler::emitError(const QString& error)
{
qWarning() << "TaskScheduler: Error:" << error;
emit errorOccurred(error);
}

View File

@ -0,0 +1,281 @@
#pragma once
#include <QDateTime>
#include <QString>
#include <QVector>
#include <QMetaType>
#include <QTimer>
#include "CaptureCoordinator.h"
// ==================== 枚举定义 ====================
// 任务状态
enum class TaskStatus {
default, //未调度
Waiting, // 等待
Running, // 运行中
Finished, // 结束
Skiped, //跳过
Timeout //超时
};
// 子任务类型
enum class SubTaskType {
HyperSpectual400_1000nm, // 400nm-1000nm高光谱相机
HyperSpectual1000_1700nm, // 1000nm-1700nm高光谱相机
SingleLensReflex, // 单反相机
DepthCamera, // 深度相机采集任务
ObtainingDepthInformation, //通过深度相机获取被测物体的深度信息
AutoFocus, // 自动对焦
LiftingPlatform // 升降平台
};
enum class HyperImagerType {
Pika_L,
Pika_NIR
};
// ==================== 统一子任务封装 ====================
struct SubTask {
SubTaskType type; // 子任务类型
// 共享属性
QDateTime startTime;
QDateTime endTime;
double durationMinutes = 0;
double estimatedDurationMinutes = 0;
QString pathLineFilePath;
TaskStatus status = TaskStatus::Waiting;
// 类型特有属性(根据type选择使用)
double frameRate = 0.0; // 高光谱相机用
double exposureTime = 0.0; // 高光谱相机用
int defaultRenderBand = 550; // 1000-1700nm高光谱用
int captureIntervalSeconds = 5; // 单反/深度相机用
//任务ObtainingDepthInformation所需的x和y坐标
int depthAlgorithm = 0;//0:深度图像的范围(percentageOfEffectiveArea)平均,1:深度范围(depthRangePercentage)的百分比,2:通过彩色图像分割植被区域的深度图像,然后平均
int depthType = 0;//0表示植被深度,1表示白板/调焦版深度
double depthInfoX = 0.0;
double depthInfoY = 0.0;
int averageNumberOfTimes = 1; //任务ObtainingDepthInformation所需的平均次数
double percentageOfEffectiveArea = 50.0; //深度图像的有效范围百分比
double depthRangePercentage = 80.0; //深度范围的百分比
//高光谱自动调焦
HyperImagerType autoFocusHyperImagerType;//取值范围:L、NIR
QString autoFocusMotorConfigFilePath;//马达配置文件
double autoFocusX = 0.0;
double autoFocusY = 0.0;
};
// ==================== 定时任务 ====================
struct TimedTask {
int id = 0;
QDateTime scheduledTime;
QDateTime startTime;
QDateTime endTime;
double durationMinutes = 0;
double estimatedDurationMinutes = 0;
QString savePath;
QVector<SubTask> subTasks;
TaskStatus status = TaskStatus::Waiting;
double HalogenLampPreheatingTime_Minute;
// 计算所有子任务的预计总时间
int totalEstimatedDuration() const {
int total = 0;
for (const auto& subTask : subTasks) {
total += subTask.estimatedDurationMinutes;
}
return total;
}
// 获取子任务数量
int subTaskCount() const {
return subTasks.size();
}
};
// ==================== Qt元类型声明 ====================
Q_DECLARE_METATYPE(TaskStatus)
Q_DECLARE_METATYPE(SubTaskType)
Q_DECLARE_METATYPE(SubTask)
Q_DECLARE_METATYPE(TimedTask)
// ==================== 任务文件读写类 ====================
class TimedDataCollectionDataStructuresReaderWriter
{
public:
// 保存任务到文件
static bool saveTasksToFile(const QString& filePath, const QVector<TimedTask>& tasks);
// 从文件读取任务
static bool loadTasksFromFile(const QString& filePath, QVector<TimedTask>& tasks);
private:
// SubTask序列化
static QJsonObject subTaskToJson(const SubTask& subTask);
static bool jsonToSubTask(const QJsonObject& json, SubTask& subTask);
// TimedTask序列化
static QJsonObject timedTaskToJson(const TimedTask& task);
static bool jsonToTimedTask(const QJsonObject& json, TimedTask& task);
// 枚举转换
static QString taskStatusToString(TaskStatus status);
static TaskStatus stringToTaskStatus(const QString& str);
static QString subTaskTypeToString(SubTaskType type);
static SubTaskType stringToSubTaskType(const QString& str);
static QString hyperImagerTypeToString(HyperImagerType type);
static HyperImagerType stringToHyperImagerType(const QString& str);
};
// ==================== 任务执行器 ====================
class TaskExecutor : public QObject
{
Q_OBJECT
public:
explicit TaskExecutor(QObject* parent = nullptr);
~TaskExecutor();
// 执行任务
void execute(const TimedTask& task);
void makeFolder(QString savePath);
QString makeSubTaskDataFolder(QString suffix);
// 获取当前执行的子任务索引
int currentSubTaskIndex() const { return m_currentSubTaskIndex; }
// 获取正在执行的任务
const TimedTask& currentTask() const { return m_task; }
// 是否正在执行
bool isRunning() const { return m_isRunning; }
// 停止执行
void stop();
signals:
void finished(bool success); // 任务完成
void taskUpdated(const TimedTask& task); // 确保有这个信号
void subTaskStarted(int subTaskIndex, SubTaskType type); // 子任务开始
void subTaskFinished(int subTaskIndex, SubTaskType type, bool success); // 子任务完成
void errorOccurred(const QString& error); // 错误发生
// 采集相关信号
void hyperCamParm(int camType, double f, double e, QString filePath, QString fileName);
void camParm(int camType, int captureIntervalSeconds, QString folder);
void motorParm(QString pathLineFilePath);
void startRecordSignal(int camType);
void ObtainingDepthInformationSignals(SubTask info);
void LiftingPlatformSignals(SubTask info);
void AutoFocusSignals(SubTask info);
void switchHalogenLampSignal(int state);
void switchD65LampSignal(int state);
void switchSlrSignal(int state);
public slots:
void onSequenceComplete(int status);
void onBack2Origin();
void onError(const QString& error);
void emitRecordSignal();
void emitAutoFocusSignal();
private:
QString m_currentFolder;
void executeNextSubTask();
void ensurePreTaskLighting();
void ensurePostTaskLighting();
void printMsgAndTime(QString msg);
TimedTask m_task;
int m_currentSubTaskIndex;
bool m_isRunning;
int m_camType;
};
// ==================== 任务调度器 ====================
class TaskScheduler : public QObject
{
Q_OBJECT
public:
explicit TaskScheduler(QObject* parent = nullptr);
~TaskScheduler();
// 加载任务列表
void loadTasks(const QVector<TimedTask>& tasks);
// 获取任务列表
QVector<TimedTask> tasks() const { return m_tasks; }
// 开始调度
void start();
// 停止调度
void stop();
// 是否正在运行
bool isRunning() const { return m_timer != nullptr && m_timer->isActive(); }
signals:
void taskStarted(int taskId); // 任务开始
void taskFinished(int taskId, bool success); // 任务完成
void taskDataChanged(const TimedTask& task);
void schedulerStateChanged(bool running); // 调度器状态变化
// 子任务的信号
void subTaskStarted(int taskId, int subTaskIndex); // 子任务开始
void subTaskFinished(int taskId, int subTaskIndex); // 子任务完成
void errorOccurred(const QString& error); // 错误发生
// 采集相关信号 (透传 TaskExecutor)
void hyperCamParm(int camType, double f, double e, QString filePath, QString fileName);
void camParm(int camType, int captureIntervalSeconds, QString folder);
void motorParm(QString pathLineFilePath);
void startRecordSignal(int camType);
void ObtainingDepthInformationSignals(SubTask info);
void LiftingPlatformSignals(SubTask info);
void AutoFocusSignals(SubTask info);
void switchHalogenLampSignal(int state);
void switchD65LampSignal(int state);
void switchSlrSignal(int state);
// 马达反馈的信号
void sequenceCompleteSignal(int status);
void Back2OriginSignal();
private slots:
void checkTasks(); // 检查任务是否该启动
void onTaskFinished(bool success);
void onSubTaskStarted(int subTaskIndex, SubTaskType type);
void onSubTaskFinished(int subTaskIndex, SubTaskType type, bool success);
void onExecutorError(const QString& error);
private:
void executeTask(TimedTask& task);
void updateTaskStatus(int taskId, TaskStatus status);
void emitError(const QString& error);
QTimer* m_timer;
QVector<TimedTask> m_tasks;
TaskExecutor* m_currentExecutor;
int m_currentTaskId;
};

View File

@ -0,0 +1,209 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>TimedDataCollection_ui</class>
<widget class="QDialog" name="TimedDataCollection_ui">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1299</width>
<height>658</height>
</rect>
</property>
<property name="windowTitle">
<string>定时采集</string>
</property>
<property name="styleSheet">
<string notr="true">QWidget #contentWidget
{
background: #192770;
/*border-radius: 8px 8px 8px 8px;*/
border: 1px solid #2f6bff;
}
QLineEdit {
background-color: #3856B8;
color: #e6eeff;
border: 1px solid #2f6bff;
border-radius: 6px;
padding: 4px 8px;
min-width: 70px;
min-height: 20px;
font-size: 13px;
}
QLabel
{
background: #243A82;
color: rgb(255, 255, 255);
border: 1px solid #2f6bff;
border-radius: 6px;
}
QPushButton
{
/*width: 172px;
height: 56px;*/
font: 10pt &quot;新宋体&quot;;
background-color: qlineargradient(
spread:pad,
x1:0.5, y1:0, x2:0.5, y2:1,
stop:0 #283D86,
stop:1 #0F1A40
);
color: white;
border: none;
padding: 8px 8px;
border-radius: 4px;
}
QPushButton:hover
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #3A4875,
stop:1 #5F6B91
);
}
/* 按下时的效果 */
QPushButton:pressed
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #1A254F,
stop:1 #3A466B
);
/* 可选:添加下压效果 */
padding-top: 9px;
padding-bottom: 7px;
}
</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<property name="spacing">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QWidget" name="contentWidget" native="true">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="3">
<widget class="QTreeView" name="taskTreeView">
<property name="styleSheet">
<string notr="true">QTreeView
{
background-color: #121945;
border: 0px solid #444;
}
QHeaderView::section
{
background-color: #121945;
color: #ACCDFF;
padding: 6px;
}
QScrollBar:vertical {
background: #0b1440;
width: 10px;
border: 1px solid #1f2a5a;
}
QScrollBar:horizontal {
background: #0b1440;
height: 10px;
border: 1px solid #1f2a5a;
}
QScrollBar::handle:vertical,
QScrollBar::handle:horizontal {
background: #3a5bd6;
border-radius: 4px;
min-height: 20px;
min-width: 20px;
}
QScrollBar::handle:vertical:hover,
QScrollBar::handle:horizontal:hover {
background: #4f73ff;
}
</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLineEdit" name="taskFileSelect_lineEdit">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="taskFileSelect_btn">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="start_btn">
<property name="text">
<string>开始调度</string>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QPushButton" name="expandAll_btn">
<property name="text">
<string>展开</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QPushButton" name="stop_btn">
<property name="text">
<string>停止调度</string>
</property>
</widget>
</item>
<item row="3" column="2">
<widget class="QPushButton" name="collapseAll_btn">
<property name="text">
<string>折叠</string>
</property>
</widget>
</item>
<item row="4" column="0" colspan="3">
<widget class="QLabel" name="statusLabel">
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string>任务统计</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -103,6 +103,185 @@ void TwoMotorControl::record_white()
m_whiteCaptureCoordinator->startStepMotion(s);
}
void TwoMotorControl::run2(SingleLensReflexCameraWindow* window)
{
int rowCount = ui.recordLine_tableWidget->rowCount();
if (rowCount == 0)
{
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("请至少添加一行采集线!"));
emit sequenceComplete(0);
return;
}
m_coordinator_TimedDataCollection = new TwoMotionCaptureCoordinator(m_multiAxisController);
connect(this, SIGNAL(start(QVector<PathLine>)), m_coordinator_TimedDataCollection, SLOT(start(QVector<PathLine>)));
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::startRecordLineNumSignal, this, &TwoMotorControl::receiveStartRecordLineNum);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::finishRecordLineNumSignal, this, &TwoMotorControl::receiveFinishRecordLineNum);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::startRecordLineNumSignal, window, &SingleLensReflexCameraWindow::onStartTimedDataCollection);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::sequenceComplete, window, &SingleLensReflexCameraWindow::onStopTimedDataCollection);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::sequenceComplete, this, &TwoMotorControl::sequenceComplete);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::back2OriginSignal, this, &TwoMotorControl::onBack2Origin2);
QVector<PathLine> pathLines;
//int columnCount = ui.recordLine_tableWidget->columnCount();
for (size_t i = 0; i < rowCount; i++)
{
PathLine tmp;
tmp.targetYPosition = ui.recordLine_tableWidget->item(i, 0)->text().toDouble();
tmp.speedTargetYPosition = ui.recordLine_tableWidget->item(i, 1)->text().toDouble();
tmp.targetXMinPosition = ui.recordLine_tableWidget->item(i, 2)->text().toDouble();
tmp.speedTargetXMinPosition = ui.recordLine_tableWidget->item(i, 3)->text().toDouble();
tmp.targetXMaxPosition = ui.recordLine_tableWidget->item(i, 4)->text().toDouble();
tmp.speedTargetXMaxPosition = ui.recordLine_tableWidget->item(i, 5)->text().toDouble();
pathLines.append(tmp);
}
for (size_t i = 0; i < ui.recordLine_tableWidget->rowCount(); i++)
{
for (size_t j = 0; j < ui.recordLine_tableWidget->columnCount(); j++)
{
ui.recordLine_tableWidget->item(i, j)->setBackgroundColor(QColor("#0E1C4C"));
}
}
emit start(pathLines);
}
void TwoMotorControl::run3(DepthCameraWindow* window)
{
int rowCount = ui.recordLine_tableWidget->rowCount();
if (rowCount == 0)
{
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("请至少添加一行采集线!"));
emit sequenceComplete(0);
return;
}
m_coordinator_TimedDataCollection = new TwoMotionCaptureCoordinator(m_multiAxisController);
connect(this, SIGNAL(start(QVector<PathLine>)), m_coordinator_TimedDataCollection, SLOT(start(QVector<PathLine>)));
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::startRecordLineNumSignal, this, &TwoMotorControl::receiveStartRecordLineNum);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::finishRecordLineNumSignal, this, &TwoMotorControl::receiveFinishRecordLineNum);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::startRecordLineNumSignal, window, &DepthCameraWindow::openDepthCamera);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::sequenceComplete, window, &DepthCameraWindow::closeDepthCamera);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::sequenceComplete, this, &TwoMotorControl::sequenceComplete);
connect(m_coordinator_TimedDataCollection, &TwoMotionCaptureCoordinator::back2OriginSignal, this, &TwoMotorControl::onBack2Origin2);
QVector<PathLine> pathLines;
//int columnCount = ui.recordLine_tableWidget->columnCount();
for (size_t i = 0; i < rowCount; i++)
{
PathLine tmp;
tmp.targetYPosition = ui.recordLine_tableWidget->item(i, 0)->text().toDouble();
tmp.speedTargetYPosition = ui.recordLine_tableWidget->item(i, 1)->text().toDouble();
tmp.targetXMinPosition = ui.recordLine_tableWidget->item(i, 2)->text().toDouble();
tmp.speedTargetXMinPosition = ui.recordLine_tableWidget->item(i, 3)->text().toDouble();
tmp.targetXMaxPosition = ui.recordLine_tableWidget->item(i, 4)->text().toDouble();
tmp.speedTargetXMaxPosition = ui.recordLine_tableWidget->item(i, 5)->text().toDouble();
pathLines.append(tmp);
}
for (size_t i = 0; i < ui.recordLine_tableWidget->rowCount(); i++)
{
for (size_t j = 0; j < ui.recordLine_tableWidget->columnCount(); j++)
{
ui.recordLine_tableWidget->item(i, j)->setBackgroundColor(QColor("#0E1C4C"));
}
}
emit start(pathLines);
}
void TwoMotorControl::onBack2Origin2()
{
m_coordinator_TimedDataCollection->deleteLater();
m_coordinator_TimedDataCollection = nullptr;
emit back2OriginSignal_TimedDataCollection();
}
void TwoMotorControl::run4_ObtainTargetDepthInfo(DepthCameraWindow* window, double depthAlgorithm,int depthType, double depthInfoX, double depthInfoY, int averageNumberOfTimes, double percentageOfEffectiveArea, double depthRangePercentage)
{
m_depthType = depthType;
window->m_DepthCameraOperation->setDepthAlgorithm(depthAlgorithm);
window->m_DepthCameraOperation->setAverageNumberOfTimes(averageNumberOfTimes);
window->m_DepthCameraOperation->setPercentageOfEffectiveArea(percentageOfEffectiveArea);
window->m_DepthCameraOperation->setDepthRangePercentage(depthRangePercentage);
m_ObtainTargetDepthInfoCoordinator = new TwoMotor1PosCoordinator(m_multiAxisController);
connect(m_ObtainTargetDepthInfoCoordinator, &TwoMotor1PosCoordinator::ArrivalSignal, window, &DepthCameraWindow::OpenDepthCamera_getDepthValue);
connect(window->m_DepthCameraOperation, &DepthCameraOperation::DepthValueSignal, m_ObtainTargetDepthInfoCoordinator, &TwoMotor1PosCoordinator::back2origin);
connect(window->m_DepthCameraOperation, &DepthCameraOperation::DepthValueSignal, this, &TwoMotorControl::sequenceComplete, Qt::UniqueConnection);//关灯
connect(window->m_DepthCameraOperation, &DepthCameraOperation::DepthValueSignal, this, &TwoMotorControl::saveDepthValue, Qt::UniqueConnection);
connect(m_ObtainTargetDepthInfoCoordinator, &TwoMotor1PosCoordinator::back2OriginSignal, this, &TwoMotorControl::onBack2Origin3);
double xmotor_move_speed = ui.xmotor_move_speed_lineEdit->text().toDouble();
double ymotor_move_speed = ui.ymotor_move_speed_lineEdit->text().toDouble();
m_ObtainTargetDepthInfoCoordinator->moveToTarget(depthInfoX, depthInfoY, xmotor_move_speed, ymotor_move_speed);
}
void TwoMotorControl::run5_AutoFocus(double autoFocusX, double autoFocusY)
{
m_focusWindow = new focusWindow(this, m_Imager);
m_focusWindow->onConnectMotor();
m_focusWindow->show();
//自动调焦的协调器添加功能:先归零
m_autoFocusCoordinator = new TwoMotor1PosCoordinator(m_multiAxisController);
connect(m_autoFocusCoordinator, &TwoMotor1PosCoordinator::ArrivalSignal, m_focusWindow, &focusWindow::onAutoFocus);
connect(m_focusWindow, &focusWindow::AutoFocusFinishedSignal, m_autoFocusCoordinator, &TwoMotor1PosCoordinator::back2origin);
connect(m_focusWindow, &focusWindow::AutoFocusFinishedSignal, this, &TwoMotorControl::sequenceComplete, Qt::UniqueConnection);
connect(m_autoFocusCoordinator, &TwoMotor1PosCoordinator::back2OriginSignal, this, &TwoMotorControl::onBack2Origin4);
double xmotor_move_speed = ui.xmotor_move_speed_lineEdit->text().toDouble();
double ymotor_move_speed = ui.ymotor_move_speed_lineEdit->text().toDouble();
m_autoFocusCoordinator->moveToTarget(autoFocusX, autoFocusY, xmotor_move_speed, ymotor_move_speed);
}
void TwoMotorControl::saveDepthValue(double depthValue)
{
if (m_depthType == 0)//0表示植被深度,1表示白板/调焦版深度
{
DepthValueLogger::instance().appendPlantDepthValue(depthValue);
}
else if (m_depthType == 1)
{
DepthValueLogger::instance().appendLiftingPlatformDepthValue(depthValue);
}
}
void TwoMotorControl::onBack2Origin3()
{
m_ObtainTargetDepthInfoCoordinator->deleteLater();
m_ObtainTargetDepthInfoCoordinator = nullptr;
emit back2OriginSignal_TimedDataCollection();
}
void TwoMotorControl::onBack2Origin4()
{
m_focusWindow->deleteLater();
m_focusWindow = nullptr;
m_autoFocusCoordinator->deleteLater();
m_autoFocusCoordinator = nullptr;
emit back2OriginSignal_TimedDataCollection();
}
void TwoMotorControl::run()
{
if (getState())
@ -116,19 +295,26 @@ void TwoMotorControl::run()
{
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("请至少添加一行采集线!"));
emit sequenceComplete();
emit sequenceComplete(0);
return;
}
qRegisterMetaType<QVector<PathLine>>("QVector<PathLine>");
m_coordinator = new TwoMotionCaptureCoordinator(m_multiAxisController, m_Imager);
m_coordinator = new TwoMotionCaptureCoordinator(m_multiAxisController);
m_coordinator->moveToThread(&m_coordinatorThread);
connect(&m_coordinatorThread, SIGNAL(finished()), m_coordinator, SLOT(deleteLater()));
connect(this, SIGNAL(start(QVector<PathLine>)), m_coordinator, SLOT(start(QVector<PathLine>)));
connect(this, SIGNAL(stopSignal()), m_coordinator, SLOT(stop()));
connect(m_coordinator, SIGNAL(startRecordLineNumSignal(int)), this, SLOT(receiveStartRecordLineNum(int)));
connect(m_coordinator, SIGNAL(finishRecordLineNumSignal(int)), this, SLOT(receiveFinishRecordLineNum(int)));
connect(m_coordinator, SIGNAL(sequenceComplete(int)), this, SLOT(onSequenceComplete()));
connect(m_coordinator, SIGNAL(sequenceComplete(int)), this, SLOT(onSequenceComplete(int)));
connect(m_coordinator, &TwoMotionCaptureCoordinator::back2OriginSignal, this, &TwoMotorControl::onBack2Origin);
connect(m_coordinator, &TwoMotionCaptureCoordinator::startRecordHSISignal, m_Imager, &ImagerOperationBase::start_record);
connect(m_coordinator, &TwoMotionCaptureCoordinator::stopRecordHSISignal, this, &TwoMotorControl::stop_record);
connect(m_Imager, &ImagerOperationBase::RecordFinishedSignal_WhenFrameNumberMeet, m_coordinator, &TwoMotionCaptureCoordinator::handleCaptureCompleteWhenFrameNumberMeet);
m_coordinatorThread.start();
QVector<PathLine> pathLines;
@ -158,6 +344,11 @@ void TwoMotorControl::run()
emit start(pathLines);
}
void TwoMotorControl::stop_record()
{
m_Imager->stop_record();
}
void TwoMotorControl::stop()
{
emit stopSignal();
@ -173,12 +364,21 @@ TwoMotorControl::~TwoMotorControl()
}
void TwoMotorControl::onConnectMotor()
{
connectMotor(true);
}
void TwoMotorControl::connectMotor(bool isNotification)
{
if (getMotorsConnectionStatus())
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("马达已连接!"));
msgBox.exec();
if (isNotification)
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("马达已连接!"));
msgBox.exec();
}
return;
}
@ -252,16 +452,22 @@ void TwoMotorControl::receiveFinishRecordLineNum(int lineNum)
}
}
void TwoMotorControl::onSequenceComplete()
void TwoMotorControl::onSequenceComplete(int status)
{
isWritePosFile = false;
fclose(m_posFileHandle);
emit sequenceComplete(status);
}
void TwoMotorControl::onBack2Origin()
{
m_coordinatorThread.quit();
m_coordinatorThread.wait();
m_coordinator = nullptr;
emit sequenceComplete();
emit back2OriginSignal();
emit back2OriginSignal_TimedDataCollection();
}
bool TwoMotorControl::getMotorsConnectionStatus()
@ -419,51 +625,15 @@ void TwoMotorControl::on_rangeMeasurement()
void TwoMotorControl::onAddRecordLine_btn()
{
//准备数据:获取y马达的当前位置,获取x马达的当前位置和最大位置
// 准备数据:获取y马达的当前位置,获取x马达的当前位置和最大位置
double currentPosOfYmotor = 15;
double currentPosOfXmotor = 0;
double maxRangeOfXmotor = 50;
//获取选中行的索引
int currentRow = ui.recordLine_tableWidget->currentRow();
std::cout << "currentRow:" << currentRow << std::endl;
QTableWidgetItem* Item1 = new QTableWidgetItem(QString::number(currentPosOfYmotor, 10, 2));
QTableWidgetItem* Item2 = new QTableWidgetItem(QString::number(1, 10, 2));
QTableWidgetItem* Item3 = new QTableWidgetItem(QString::number(currentPosOfXmotor, 10, 2));
QTableWidgetItem* Item4 = new QTableWidgetItem(QString::number(1, 10, 2));
QTableWidgetItem* Item5 = new QTableWidgetItem(QString::number(maxRangeOfXmotor, 10, 2));
QTableWidgetItem* Item6 = new QTableWidgetItem(QString::number(1, 10, 2));
Item1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
Item2->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
Item3->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
Item4->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
Item5->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
Item6->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
if (currentRow == -1)//当没有选中行时
{
int RowCount = ui.recordLine_tableWidget->rowCount();//Returns the number of rows. 从1开始的
ui.recordLine_tableWidget->insertRow(RowCount);//增加一行,形参是从0开始的
ui.recordLine_tableWidget->setItem(RowCount, 0, Item1);
ui.recordLine_tableWidget->setItem(RowCount, 1, Item2);
ui.recordLine_tableWidget->setItem(RowCount, 2, Item3);
ui.recordLine_tableWidget->setItem(RowCount, 3, Item4);
ui.recordLine_tableWidget->setItem(RowCount, 4, Item5);
ui.recordLine_tableWidget->setItem(RowCount, 5, Item6);
}
else
{
ui.recordLine_tableWidget->insertRow(currentRow + 1);//增加一行,形参是从0开始的
ui.recordLine_tableWidget->setItem(currentRow + 1, 0, Item1);
ui.recordLine_tableWidget->setItem(currentRow + 1, 1, Item2);
ui.recordLine_tableWidget->setItem(currentRow + 1, 2, Item3);
ui.recordLine_tableWidget->setItem(currentRow + 1, 3, Item4);
ui.recordLine_tableWidget->setItem(currentRow + 1, 4, Item5);
ui.recordLine_tableWidget->setItem(currentRow + 1, 5, Item6);
}
PathLineManager::addRecordLine(ui.recordLine_tableWidget,
currentPosOfYmotor, 1.0,
currentPosOfXmotor, 1.0,
maxRangeOfXmotor, 1.0);
}
void TwoMotorControl::onRemoveRecordLine_btn()
@ -484,103 +654,40 @@ void TwoMotorControl::onDeleteRecordLine_btn()
void TwoMotorControl::onSaveRecordLine2File_btn()
{
//确保采集线存在
// 确保采集线存在
if (ui.recordLine_tableWidget->rowCount() <= 0)
{
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("请先生成轨迹!"));
QMessageBox::information(this, QString::fromLocal8Bit("提示"),
QString::fromLocal8Bit("请先生成轨迹!"));
return;
}
FileOperation* fileOperation = new FileOperation();
string directory = fileOperation->getDirectoryOfExe();
QString RecordLineFilePath = QFileDialog::getSaveFileName(this, tr("Save RecordLine3 File"),
QString::fromStdString(directory),
tr("RecordLineFile3 (*.RecordLine3)"));
if (RecordLineFilePath.isEmpty())
{
return;
}
FILE* RecordLineFileHandle = fopen(RecordLineFilePath.toStdString().c_str(), "wb+");
double number = ui.recordLine_tableWidget->rowCount() * ui.recordLine_tableWidget->columnCount();
fwrite(&number, sizeof(double), 1, RecordLineFileHandle);
double* data = new double[number];
//double data[number];
for (size_t i = 0; i < ui.recordLine_tableWidget->rowCount(); i++)
{
for (size_t j = 0; j < ui.recordLine_tableWidget->columnCount(); j++)
{
data[i * ui.recordLine_tableWidget->columnCount() + j] = ui.recordLine_tableWidget->item(i, j)->text().toDouble();
}
}
fwrite(data, sizeof(double), number, RecordLineFileHandle);
fclose(RecordLineFileHandle);
delete[] data;
//QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("保存成功!"));
PathLineManager::saveToFile(RecordLineFilePath, ui.recordLine_tableWidget);
}
void TwoMotorControl::onReadRecordLineFile_btn()
{
//打开文件
FileOperation* fileOperation = new FileOperation();
string directory = fileOperation->getDirectoryOfExe();
QString RecordLineFilePath = QFileDialog::getOpenFileName(this, tr("Open RecordLine3 File"),
QString::fromStdString(directory),
tr("RecordLineFile (*.RecordLine3)"));
if (RecordLineFilePath.isEmpty())
{
return;
}
FILE* RecordLineFileHandle = fopen(RecordLineFilePath.toStdString().c_str(), "rb");
double number;
//读取数据
fread(&number, sizeof(double), 1, RecordLineFileHandle);
double* data = new double[number];
for (size_t i = 0; i < number; i++)
{
fread(data + i, sizeof(double), 1, RecordLineFileHandle);
//std::cout << *(data + i) << std::endl;
}
//向tableWidget添加采集线
//(1)去掉tableWidget中所有的行
int rowCount = ui.recordLine_tableWidget->rowCount();
for (size_t i = 0; i < rowCount; i++)
{
ui.recordLine_tableWidget->removeRow(0);
}
//(2)添加行(采集线)
int RecordLineCount = number / ui.recordLine_tableWidget->columnCount();
for (size_t i = 0; i < RecordLineCount; i++)
{
ui.recordLine_tableWidget->insertRow(0);
}
//(3)向tableWidget填充数据
for (size_t i = 0; i < ui.recordLine_tableWidget->rowCount(); i++)
{
for (size_t j = 0; j < ui.recordLine_tableWidget->columnCount(); j++)
{
QTableWidgetItem* tmp = new QTableWidgetItem(QString::number(data[i * ui.recordLine_tableWidget->columnCount() + j], 10, 5));
tmp->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui.recordLine_tableWidget->setItem(i, j, tmp);
}
}
fclose(RecordLineFileHandle);
delete[] data;
//QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("读取成功!"));
readRecordLineFile(RecordLineFilePath);
}
void TwoMotorControl::readRecordLineFile(QString RecordLineFilePath)
{
PathLineManager::readFromFile(RecordLineFilePath, ui.recordLine_tableWidget);
}

View File

@ -10,6 +10,15 @@
#include "CaptureCoordinator.h"
#include "MotorWindowBase.h"
#include "SingleLensReflexCameraWindow.h"
#include "DepthCameraWindow.h"
#include "PathLine.h"
#include "DepthValueLogger.h"
#include "focusWindow.h"
#define PI 3.1415926
class TwoMotorControl : public QDialog, public MotorWindowBase
@ -27,6 +36,10 @@ public:
void record_white();
bool getMotorsConnectionStatus();
void readRecordLineFile(QString RecordLineFilePath);
void connectMotor(bool isNotification);
private:
ImagerOperationBase* m_Imager;
@ -68,7 +81,19 @@ public Q_SLOTS:
void stop();
void receiveStartRecordLineNum(int lineNum);
void receiveFinishRecordLineNum(int lineNum);
void onSequenceComplete();
void onSequenceComplete(int status);
void onBack2Origin();
void run2(SingleLensReflexCameraWindow* w);
void run3(DepthCameraWindow* window);
void run4_ObtainTargetDepthInfo(DepthCameraWindow* window, double depthAlgorithm, int depthType, double depthInfoX, double depthInfoY, int averageNumberOfTimes, double percentageOfEffectiveArea, double depthRangePercentage);
void run5_AutoFocus(double autoFocusX, double autoFocusY);
void onBack2Origin2();
void saveDepthValue(double depthValue);
void onBack2Origin3();
void onBack2Origin4();
void stop_record();
signals:
void moveSignal(int, bool, double, int);
@ -84,7 +109,9 @@ signals:
void stopSignal();
void startLineNumSignal(int lineNum);
void sequenceComplete();//所有采集线正常运行完成
void sequenceComplete(int status);//所有采集线正常运行完成
void back2OriginSignal();
void back2OriginSignal_TimedDataCollection();
void broadcastLocationSignal(std::vector<double>);
@ -92,10 +119,17 @@ private:
Ui::twoMotorControl_UI ui;
QThread m_coordinatorThread;
TwoMotionCaptureCoordinator* m_coordinator = nullptr;
TwoMotionCaptureCoordinator* m_coordinator_TimedDataCollection = nullptr;
TwoMotor1PosCoordinator* m_ObtainTargetDepthInfoCoordinator = nullptr;
TwoMotor1PosCoordinator* m_autoFocusCoordinator = nullptr;
DarkAndWhiteCaptureCoordinator* m_darkCaptureCoordinator = nullptr;
DarkAndWhiteCaptureCoordinator* m_whiteCaptureCoordinator = nullptr;
QThread m_motorThread;
IrisMultiMotorController* m_multiAxisController = nullptr;
int m_depthType;
focusWindow* m_focusWindow = nullptr;
};

View File

@ -372,4 +372,18 @@ void View3DLinearStage::setLoc(std::vector<double> loc)
double x = round(loc[0] * 100) / 100;
m_armTransform->setTranslation(QVector3D(x, 0, 0));
}
}
View3DMicroscopicMotionModel::View3DMicroscopicMotionModel(const QString& baseModelPath, const QString& armModelPath, QWidget* parent)
:View3DBase(baseModelPath, armModelPath, parent)
{
}
void View3DMicroscopicMotionModel::setLoc(std::vector<double> loc)
{
double x = round(loc[0] * 100) / 100;
double y = round(loc[1] * 100) / 100;
m_armTransform->setTranslation(QVector3D(x, y, 0));
}

View File

@ -106,6 +106,24 @@ private:
private:
public Q_SLOTS:
void setLoc(std::vector<double> loc);
};
class View3DMicroscopicMotionModel : public View3DBase
{
Q_OBJECT
public:
View3DMicroscopicMotionModel(const QString& baseModelPath,
const QString& armModelPath,
QWidget* parent = nullptr);
protected:
private:
private:
public Q_SLOTS:
void setLoc(std::vector<double> loc);
};

View File

@ -13,15 +13,21 @@ View3DModelManager::View3DModelManager(QWidget* parent)
void View3DModelManager::switchScenario(ScenarioType type)
{
if (type == ScenarioType::PlantPhenotype) {
if (type == ScenarioType::PlantPhenotype)
{
ensurePlantPhenotypeView();
m_stackedWidget->setCurrentWidget(m_viewPlant);
}
else {
if (type == ScenarioType::OneMotor)
{
ensureOneMotorView();
m_stackedWidget->setCurrentWidget(m_viewMotor);
}
if (type == ScenarioType::MicroscopicMotionControl)
{
ensureMicroscopicMotionControlView();
m_stackedWidget->setCurrentWidget(m_viewMicroscopicMotionControlModel);
}
emit scenarioChanged(type);
}
@ -46,6 +52,27 @@ void View3DModelManager::ensurePlantPhenotypeView()
emit created3DModelPlantPhenotype();
}
void View3DModelManager::ensureMicroscopicMotionControlView()
{
if (m_viewMicroscopicMotionControlModel)
return;
QString basePath = QCoreApplication::applicationDirPath();
m_viewMicroscopicMotionControlModel = new View3DMicroscopicMotionModel(
basePath + "/3DModel/MicroscopicMotionModel_static.obj",
basePath + "/3DModel/MicroscopicMotionModel_moving.obj",
m_stackedWidget
);
m_viewMicroscopicMotionControlModel->setViewCenter(1000, 1000, -1000);
m_viewMicroscopicMotionControlModel->setDistance(5000);
m_stackedWidget->addWidget(m_viewMicroscopicMotionControlModel);
emit created3DModelMicroscopicMotion();
}
void View3DModelManager::ensureOneMotorView()
{
if (m_viewMotor)

View File

@ -16,7 +16,8 @@ class View3DModelManager : public QWidget
public:
enum class ScenarioType {
PlantPhenotype,
OneMotor
OneMotor,
MicroscopicMotionControl
};
explicit View3DModelManager(QWidget* parent = nullptr);
@ -25,14 +26,17 @@ public:
View3DPlantPhenotype* m_viewPlant = nullptr;
View3DLinearStage* m_viewMotor = nullptr;
View3DMicroscopicMotionModel* m_viewMicroscopicMotionControlModel = nullptr;
signals:
void scenarioChanged(ScenarioType type);
void created3DModelPlantPhenotype();
void created3DModelOneMotor();
void created3DModelMicroscopicMotion();
private:
void ensurePlantPhenotypeView();
void ensureMicroscopicMotionControlView();
void ensureOneMotorView();
private:

View File

@ -288,7 +288,7 @@ QPushButton:pressed
}</string>
</property>
<property name="text">
<string>版本:3.0.1</string>
<string>版本:3.1.3</string>
</property>
</widget>
</item>

View File

@ -53,6 +53,10 @@ focusWindow::focusWindow(QWidget *parent, ImagerOperationBase* imager)
connect(this->ui.rangeMeasurement_btn, SIGNAL(pressed()), this, SLOT(onx_rangeMeasurement()));
connect(this->ui.closeBtn, SIGNAL(released()), this, SLOT(onExit()));
connect(this->ui.is_new_version_radioButton, &QRadioButton::toggled, this, [this](bool checked) {
ui.stackedWidget_connetcParm->setCurrentIndex(checked ? 0 : 1);
});
//查找可用串口,并显示
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
@ -72,7 +76,40 @@ focusWindow::focusWindow(QWidget *parent, ImagerOperationBase* imager)
ui.autoFocusProgress_progressBar->reset();
m_dSpeed = 1.0;
}
void focusWindow::showMessageBox(QString msg, QString title)
{
QMessageBox msgBox(this);
msgBox.setWindowTitle(title);
msgBox.setText(msg);
msgBox.setStyleSheet(R"(
QMessageBox {
background-color: #0D1233;
}
QMessageBox QLabel {
color: #ACCDFF;
font-size: 14px;
}
QPushButton {
background-color: #142D7F;
color: #e6eeff;
border: 1px solid #2f6bff;
border-radius: 6px;
padding: 6px 20px;
min-width: 60px;
font-size: 13px;
}
QPushButton:hover {
border: 1px solid #4d8dff;
background-color: red;
}
QPushButton:pressed {
background-color: #23345c;
}
)");
msgBox.exec();
}
focusWindow::~focusWindow()
@ -160,33 +197,7 @@ void focusWindow::onConnectMotor()
{
if (ui.is_new_version_radioButton->isChecked())
{
FileOperation* fileOperation = new FileOperation();
string directory = fileOperation->getDirectoryOfExe();
QString configFilePath = QString::fromStdString(directory) + "\\oneMotorConfigFile_focus.cfg";
m_multiAxisController = new IrisMultiMotorController(configFilePath);
m_multiAxisController->moveToThread(&m_motorThread);
connect(&m_motorThread, SIGNAL(finished()), m_multiAxisController, SLOT(deleteLater()));
connect(this, SIGNAL(rmoveSignal(int, double, double, int)), m_multiAxisController, SLOT(rmove(int, double, double, int)));
connect(this, SIGNAL(move2LocSignal(int, double, double, int)), m_multiAxisController, SLOT(moveTo(int, double, double, int)));
connect(this, SIGNAL(rangeMeasurementSignal(int, double, int)), m_multiAxisController, SLOT(rangeMeasurement(int, double, int)));
connect(this, SIGNAL(zeroStartSignal(int)), m_multiAxisController, SLOT(zeroStart(int)));
connect(this, SIGNAL(move2MaxLocSignal(int, double, int)), m_multiAxisController, SLOT(moveToMax(int, double, int)));
connect(m_multiAxisController, SIGNAL(broadcastLocationSignal(std::vector<double>)), this, SLOT(display_x_loc(std::vector<double>)));
connect(m_multiAxisController, SIGNAL(motorStopSignal(int, double)), this, SLOT(moveAfterAutoFocus(int, double)));
m_motorThread.start();
//归零
//emit zeroStartSignal(0);
//自动调焦逻辑
m_coordinator = new MotionCaptureCoordinator(m_multiAxisController, m_Imager);
m_coordinator->moveToThread(&m_MotionCaptureCoordinatorThread);
connect(&m_MotionCaptureCoordinatorThread, SIGNAL(finished()), m_coordinator, SLOT(deleteLater()));
connect(this, SIGNAL(startStepMotion(double, int, double, double)), m_coordinator, SLOT(startStepMotion(double, int, double, double)));
connect(m_coordinator, SIGNAL(progressChanged(int)), this, SLOT(onAutoFocusProgress(int)));
connect(m_coordinator, SIGNAL(sequenceComplete()), this, SLOT(onAutoFocusFinished()));
m_MotionCaptureCoordinatorThread.start();
connectMotor(true);
}
else
{
@ -257,6 +268,131 @@ void focusWindow::onConnectMotor()
disableBeforeConnect(false);
}
void focusWindow::connectMotor(bool isNotification)//需要修改这个函数
{
if (getMotorsConnectionStatus())
{
if (isNotification)
{
showMessageBox(QString::fromLocal8Bit("马达已连接!"));
}
return;
}
if (m_multiAxisController)
{
disconnect(&m_motorThread, SIGNAL(finished()), m_multiAxisController, SLOT(deleteLater()));
disconnect(this, SIGNAL(rmoveSignal(int, double, double, int)), m_multiAxisController, SLOT(rmove(int, double, double, int)));
disconnect(this, SIGNAL(move2LocSignal(int, double, double, int)), m_multiAxisController, SLOT(moveTo(int, double, double, int)));
disconnect(this, SIGNAL(rangeMeasurementSignal(int, double, int)), m_multiAxisController, SLOT(rangeMeasurement(int, double, int)));
disconnect(this, SIGNAL(zeroStartSignal(int)), m_multiAxisController, SLOT(zeroStart(int)));
disconnect(this, SIGNAL(move2MaxLocSignal(int, double, int)), m_multiAxisController, SLOT(moveToMax(int, double, int)));
disconnect(m_multiAxisController, SIGNAL(broadcastLocationSignal(std::vector<double>)), this, SLOT(display_x_loc(std::vector<double>)));
disconnect(m_multiAxisController, SIGNAL(motorStopSignal(int, double)), this, SLOT(moveAfterAutoFocus(int, double)));
disconnect(m_multiAxisController, SIGNAL(broadcastConnectivity(std::vector<int>)), this, SLOT(display_motors_connectivity(std::vector<int>)));
m_motorThread.quit();
m_motorThread.wait();
m_multiAxisController->deleteLater();
}
if (m_coordinator)
{
disconnect(&m_MotionCaptureCoordinatorThread, SIGNAL(finished()), m_coordinator, SLOT(deleteLater()));
disconnect(this, SIGNAL(startStepMotionSignal(double, int, double, double)), m_coordinator, SLOT(startStepMotion(double, int, double, double)));
disconnect(m_coordinator, SIGNAL(progressChanged(int)), this, SLOT(onAutoFocusProgress(int)));
disconnect(m_coordinator, SIGNAL(sequenceComplete()), this, SLOT(onAutoFocusFinished()));
m_MotionCaptureCoordinatorThread.quit();
m_MotionCaptureCoordinatorThread.wait();
m_coordinator->deleteLater();
}
try
{
FileOperation* fileOperation = new FileOperation();
string directory = fileOperation->getDirectoryOfExe();
QString configFilePath = QString::fromStdString(directory) + "\\oneMotorConfigFile_focus.cfg";
m_multiAxisController = new IrisMultiMotorController(configFilePath);
}
catch (std::exception const& e)
{
showMessageBox(QString::fromLocal8Bit("请连接马达!"));
return;
}
m_multiAxisController->moveToThread(&m_motorThread);
connect(&m_motorThread, SIGNAL(finished()), m_multiAxisController, SLOT(deleteLater()));
connect(this, SIGNAL(rmoveSignal(int, double, double, int)), m_multiAxisController, SLOT(rmove(int, double, double, int)));
connect(this, SIGNAL(move2LocSignal(int, double, double, int)), m_multiAxisController, SLOT(moveTo(int, double, double, int)));
connect(this, SIGNAL(rangeMeasurementSignal(int, double, int)), m_multiAxisController, SLOT(rangeMeasurement(int, double, int)));
connect(this, SIGNAL(zeroStartSignal(int)), m_multiAxisController, SLOT(zeroStart(int)));
connect(this, SIGNAL(move2MaxLocSignal(int, double, int)), m_multiAxisController, SLOT(moveToMax(int, double, int)));
connect(m_multiAxisController, SIGNAL(broadcastLocationSignal(std::vector<double>)), this, SLOT(display_x_loc(std::vector<double>)));
connect(m_multiAxisController, SIGNAL(motorStopSignal(int, double)), this, SLOT(moveAfterAutoFocus(int, double)));
connect(this, SIGNAL(testConnectivitySignal(int, int)), m_multiAxisController, SLOT(testConnectivity(int, int)));
connect(m_multiAxisController, SIGNAL(broadcastConnectivity(std::vector<int>)), this, SLOT(display_motors_connectivity(std::vector<int>)));
m_motorThread.start();
emit testConnectivitySignal(0, 1000);
//归零
//emit zeroStartSignal(0);
//自动调焦逻辑
m_coordinator = new MotionCaptureCoordinator(m_multiAxisController, m_Imager);
m_coordinator->moveToThread(&m_MotionCaptureCoordinatorThread);
connect(&m_MotionCaptureCoordinatorThread, SIGNAL(finished()), m_coordinator, SLOT(deleteLater()));
connect(this, SIGNAL(startStepMotionSignal(double, int, double, double)), m_coordinator, SLOT(startStepMotion(double, int, double, double)));
connect(m_coordinator, SIGNAL(progressChanged(int)), this, SLOT(onAutoFocusProgress(int)));
connect(m_coordinator, SIGNAL(sequenceComplete()), this, SLOT(onAutoFocusFinished()));
m_MotionCaptureCoordinatorThread.start();
}
void focusWindow::display_motors_connectivity(std::vector<int> connectivity)
{
//std::cout << "-----------------------------------"<<connectivity.size()<< std::endl;
if (connectivity[0])
{
m_xMotorConnectionStatus = true;
this->ui.motor_state_label->setStyleSheet(R"(
QLabel
{
background-color: #08FACE;
border-radius: 4px;
}
)");
}
else
{
m_xMotorConnectionStatus = false;
this->ui.motor_state_label->setStyleSheet(R"(
QLabel
{
background-color: red;
border-radius: 4px;
}
)");
}
if (getMotorsConnectionStatus())
{
this->ui.connectMotor_btn->setText(QString::fromLocal8Bit("已连接"));
}
else
{
this->ui.connectMotor_btn->setText(QString::fromLocal8Bit("重新连接"));
}
}
bool focusWindow::getMotorsConnectionStatus()
{
return m_xMotorConnectionStatus;
}
void focusWindow::display_x_loc(std::vector<double> loc)
{
double tmp = round(loc[0] * 100) / 100;
@ -339,7 +475,7 @@ void focusWindow::onAutoFocus()
//获取马达最大位置
std::vector<double> maxRangeLocations = m_multiAxisController->getMaxPos();
double maxPos = maxRangeLocations[0];
emit startStepMotion(m_dSpeed, m_iStepSize, 0, maxPos);
emit startStepMotionSignal(m_dSpeed, m_iStepSize, 0, maxPos);
}
else
{
@ -498,33 +634,61 @@ void focusWindow::onAutoFocusFinished()
void focusWindow::moveAfterAutoFocus(int motorID, double location)
{
//QObject* obj = sender();
//if (obj == m_multiAxisController)
//{
// qDebug() << "sender is m_multiAxisController.";
//}
if (!m_isMoveAfterAutoFocus)
{
//std::cout << "focusWindow::moveAfterAutoFocus" << std::endl;
return;
}
std::cout << "\n已经到达位置:" << location << std::endl;
//移动马达到最佳位置
emit move2LocSignal(0, (double)m_goodPos, m_dSpeed, 1000);
double tmp = abs(location - m_goodPos) / m_goodPos * 100;
if (tmp<5)
double errorRate = getErrorRate(m_goodPos, location);
if (errorRate < 5|| m_moveRetryCount > MAX_MOVE_RETRY)
{
m_isMoveAfterAutoFocus = false;
m_moveRetryCount = 0;
if (!m_isAutoFocusSuccess)
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("纹理较弱,自动调焦效果不佳!请使用调焦纸进行自动调焦!"));
msgBox.exec();
qDebug() << "纹理较弱,自动调焦效果不佳!请使用调焦纸进行自动调焦!";
//showMessageBox(QString::fromLocal8Bit("纹理较弱,自动调焦效果不佳!请使用调焦纸进行自动调焦!"));
}
else
{
QMessageBox msgBox;
msgBox.setText(QString::fromLocal8Bit("自动调焦成功!"));
msgBox.exec();
qDebug() << "自动调焦成功!";
//showMessageBox(QString::fromLocal8Bit("自动调焦成功!"));
}
m_isMoveAfterAutoFocus = false;
emit AutoFocusFinishedSignal(0);
}
else
{
m_moveRetryCount++;
qDebug() << "自动调焦后目标马达位置,重试次数:" << m_moveRetryCount;
//移动马达到最佳位置
emit move2LocSignal(0, (double)m_goodPos, m_dSpeed, 1000);
}
}
double focusWindow::getErrorRate(double targetLoc, double actualLoc)
{
double targetLocTmp;
if (targetLoc == 0)
{
targetLocTmp = 0.001;
}
else
{
targetLocTmp = targetLoc;
}
double errorRate = abs(targetLoc - actualLoc) / targetLocTmp * 100;
return errorRate;
}
void focusWindow::getGaussianInitParam(const std::vector<double>& pos, const std::vector<double>& index, double& a_init, double& mu_init, double& sigma_init, double& c_init)
@ -677,11 +841,15 @@ MotionCaptureCoordinator::MotionCaptureCoordinator(
, m_currentPos(0)
, m_endPos(0)
, m_isRunning(false)
, m_isZeroing(false)
{
//这些信号槽是按照逻辑顺序的
connect(this, SIGNAL(moveTo(int, double, double, int)),
m_motorCtrl, SLOT(moveTo(int, double, double, int)));
connect(this, &MotionCaptureCoordinator::zeroStart,
m_motorCtrl, &IrisMultiMotorController::zeroStart);
connect(m_motorCtrl, &IrisMultiMotorController::motorStopSignal,
this, &MotionCaptureCoordinator::handlePositionReached);
//connect(m_motorCtrl, &IrisMultiMotorController::moveFailed,
@ -718,15 +886,37 @@ void MotionCaptureCoordinator::startStepMotion(double speed, int stepInterval, d
m_speed = speed;
m_iStepInterval = stepInterval;
m_iStepIntervalRealTime = 1;
m_currentPos = startPos;
m_startPos = startPos;
m_endPos = endPos;
m_posInternal = (endPos - startPos) / stepInterval;
m_isRunning = true;
m_isZeroing = true;
// 先执行归零操作
emit zeroStart(0);
qDebug() << "MotionCaptureCoordinator::startStepMotion: Zeroing started.";
}
void MotionCaptureCoordinator::startMotionSequence()
{
QMutexLocker locker(&m_dataMutex);
m_currentPos = m_startPos;
m_isZeroing = false;
qDebug() << "MotionCaptureCoordinator::startMotionSequence: Zeroing complete. Starting motion sequence.";
processNextPosition();
}
void MotionCaptureCoordinator::handleZeroComplete(int motorID, double pos)
{
if (!m_isRunning || !m_isZeroing) return;
// 归零完成,开始分步运动
startMotionSequence();
}
void MotionCaptureCoordinator::stopStepMotion()
{
QMutexLocker locker(&m_dataMutex);
@ -769,6 +959,13 @@ void MotionCaptureCoordinator::handlePositionReached(int motorID, double pos)
{
if (!m_isRunning) return;
// 如果正在等待归零完成,调用归零完成处理
if (m_isZeroing)
{
handleZeroComplete(motorID, pos);
return;
}
QMutexLocker locker(&m_dataMutex);
//验证马达运动位置是否到达指定位置

View File

@ -18,6 +18,7 @@
#include <QtSerialPort/QSerialPortInfo>
#include <QDateTime>
#include <QMutex>
#include <QPointer>
#include "ui_FocusDialog.h"
#include "AbstractPortMiscDefines.h"
@ -69,14 +70,17 @@ signals:
void errorOccurred(const QString& error);
void moveTo(int, double, double, int);
void getFocusIndexSobel();
void zeroStart(int motorID);
private slots:
void handlePositionReached(int motorID, double pos);
void handleCaptureComplete(double index);
void handleError(const QString& error);
void handleZeroComplete(int motorID, double pos);
private:
void processNextPosition();
void startMotionSequence();
IrisMultiMotorController* m_motorCtrl;
ImagerOperationBase* m_cameraCtrl;
@ -85,6 +89,7 @@ private:
double m_posInternal;
double m_currentPos;
double m_startPos;
double m_endPos;
bool m_isRunning;
double m_speed;
@ -92,6 +97,7 @@ private:
int m_iStepInterval;
int m_iStepIntervalRealTime;
int m_counter;
bool m_isZeroing;
};
class focusWindow:public QDialog
@ -123,19 +129,28 @@ private:
void disableBeforeConnect(bool disable);
QThread m_motorThread;
IrisMultiMotorController* m_multiAxisController;
QPointer<IrisMultiMotorController> m_multiAxisController;
double m_dSpeed;
QThread m_MotionCaptureCoordinatorThread;
MotionCaptureCoordinator* m_coordinator;
QPointer<MotionCaptureCoordinator> m_coordinator;
int m_iStepSize;
double m_goodPos;
bool m_isAutoFocusSuccess;
bool m_isMoveAfterAutoFocus = false;
int m_moveRetryCount = 0;
static constexpr int MAX_MOVE_RETRY = 3;
void getGaussianInitParam(const std::vector<double>& pos, const std::vector<double>& index, double& a_init, double& mu_init, double& sigma_init, double& c_init);
void gaussian_fit(const std::vector<double>& x_data, const std::vector<double>& y_data, double& a, double& mu, double& sigma, double& c);
bool m_xMotorConnectionStatus = false;
bool getMotorsConnectionStatus();
void connectMotor(bool isNotification);
void showMessageBox(QString msg, QString title = QString::fromLocal8Bit("提示"));
double getErrorRate(double targetLoc, double actualLoc);
public Q_SLOTS:
void onConnectMotor();
@ -158,6 +173,8 @@ public Q_SLOTS:
void onExit();
void display_motors_connectivity(std::vector<int> connectivity);
signals:
void StartManualFocusSignal(int);//1:开始调焦;0:停止调焦;
@ -166,9 +183,12 @@ signals:
void rmoveSignal(int, double, double, int);
void rangeMeasurementSignal(int, double, int);
void zeroStartSignal(int);
void testConnectivitySignal(int, int);
void startStepMotion(double speed, int stepInterval = 100, double startPos = 0, double endPos = -1);
void startStepMotionSignal(double speed, int stepInterval = 100, double startPos = 0, double endPos = -1);
void closeSignal();
void AutoFocusFinishedSignal(int status);
};
class WorkerThread2 : public QThread

205
HPPA/fodis.ui Normal file
View File

@ -0,0 +1,205 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FodisWindow</class>
<widget class="QDialog" name="FodisWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>857</width>
<height>477</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>FodisWindow</string>
</property>
<property name="styleSheet">
<string notr="true">QGroupBox
{
border: 12px solid transparent;
/*border-top: 12px solid transparent;
border-right: 0px solid transparent;
border-bottom: 0px solid transparent;
border-left: 0px solid transparent;*/
color: #ACCDFF;
}
QPushButton
{
/*width: 172px;
height: 56px;*/
font: 19pt &quot;新宋体&quot;;
background-color: qlineargradient(
spread:pad,
x1:0.5, y1:0, x2:0.5, y2:1,
stop:0 #283D86,
stop:1 #0F1A40
);
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
}
QPushButton:hover
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #3A4875,
stop:1 #5F6B91
);
}
/* 按下时的效果 */
QPushButton:pressed
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #1A254F,
stop:1 #3A466B
);
/* 可选:添加下压效果 */
padding-top: 9px;
padding-bottom: 7px;
}</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="1">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>18</width>
<height>100</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="1">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="1">
<widget class="QPushButton" name="close_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>关 闭</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QPushButton" name="open_btn">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>采 集</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="2" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>135</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="2">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>135</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="styleSheet">
<string notr="true">QLabel {
color: rgb(255, 255, 255);
}</string>
</property>
<property name="text">
<string>数据路径</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="dataFolderLineEdit">
<property name="styleSheet">
<string notr="true">QLineEdit {
background-color: #142D7F;
color: #e6eeff;
border: 1px solid #2f6bff;
border-radius: 6px;
padding: 4px 8px;
min-width: 70px;
min-height: 20px;
font-size: 13px;
}</string>
</property>
<property name="text">
<string>./CapturedImages</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="dataFolderBtn">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="4" column="1">
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>18</width>
<height>100</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

262
HPPA/gonggashanCtl.ui Normal file
View File

@ -0,0 +1,262 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>gongga_control</class>
<widget class="QWidget" name="gongga_control">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>572</width>
<height>384</height>
</rect>
</property>
<property name="windowTitle">
<string>贡嘎山触发采集</string>
</property>
<property name="styleSheet">
<string notr="true">QGroupBox
{
border: 12px solid transparent;
/*border-top: 12px solid transparent;
border-right: 0px solid transparent;
border-bottom: 0px solid transparent;
border-left: 0px solid transparent;*/
color: #ACCDFF;
}
QSpinBox
{
font: 10pt &quot;新宋体&quot;;
background-color: #142D7F;
color: white;
border: none;
}
QPushButton
{
/*width: 172px;
height: 56px;*/
font: 10pt &quot;新宋体&quot;;
background-color: qlineargradient(
spread:pad,
x1:0.5, y1:0, x2:0.5, y2:1,
stop:0 #283D86,
stop:1 #0F1A40
);
color: white;
border: none;
padding: 8px 8px;
border-radius: 4px;
}
QPushButton:hover
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #3A4875,
stop:1 #5F6B91
);
}
/* 按下时的效果 */
QPushButton:pressed
{
background-color: qlineargradient(
spread:pad,
x1:0, y1:0, x2:1, y2:0,
stop:0 #1A254F,
stop:1 #3A466B
);
/* 可选:添加下压效果 */
padding-top: 9px;
padding-bottom: 7px;
}
QLabel {
color: rgb(255, 255, 255);
}
</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout" stretch="1,1,3">
<item>
<widget class="QGroupBox" name="groupAdjustments">
<property name="styleSheet">
<string notr="true">QLabel
{
color: #ACCDFF;
font-size: 14px;
font: 9pt &quot;Adobe Devanagari&quot;;
}</string>
</property>
<property name="title">
<string>通讯参数</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="horizontalSpacing">
<number>16</number>
</property>
<item row="0" column="3">
<widget class="QSpinBox" name="spinbox_Port">
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="maximum">
<number>65535</number>
</property>
<property name="value">
<number>666</number>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="labelPort">
<property name="text">
<string>端口</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="0" column="0">
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="0" column="4">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupPresets">
<property name="title">
<string>采集</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QPushButton" name="btnListen">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>43</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>43</height>
</size>
</property>
<property name="text">
<string>开始监听</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="btnDisListen">
<property name="minimumSize">
<size>
<width>0</width>
<height>43</height>
</size>
</property>
<property name="text">
<string>停止监听</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>系统状态</string>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QTextEdit" name="status_textEdit">
<property name="styleSheet">
<string notr="true">QTextEdit
{
font: 10pt &quot;新宋体&quot;;
background-color: #142D7F;
color: white;
border: none;
}
QScrollBar:vertical {
background: #0E1C4C;
width: 12px;
}
QScrollBar::handle:vertical {
background: #4B60A6;
border-radius: 6px;
min-height: 20px;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
height: 0px;
}
QScrollBar:horizontal {
background: #0E1C4C;
height: 12px;
}
QScrollBar::handle:horizontal {
background: #4B60A6;
border-radius: 6px;
min-width: 20px;
}
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
width: 0px;
}</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="html">
<string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'新宋体'; font-size:10pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -153,22 +153,18 @@ void CImage::FillFocusGrayImage(unsigned short * datacube)
void CImage::FillFocusGrayQImage(unsigned short * datacube)
{
float two_eight = pow(2.0, 8);
float two_sixteen = pow(2.0, 12);
constexpr float scale = 256.0f / 4096.0f; // 2^8 / 2^12
int width = m_qimageFocusGrayImage->width();
int height = m_qimageFocusGrayImage->height();
for (unsigned short i = 0; i < height; i++)
for (int i = 0; i < height; i++)
{
for (unsigned short j = 0; j < width; j++)
QRgb* scanLine = reinterpret_cast<QRgb*>(m_qimageFocusGrayImage->scanLine(i));
const unsigned short* srcRow = datacube + width * i;
for (int j = 0; j < width; j++)
{
//uint tmp = (two_eight* *(datacube + width * i + j)) / two_sixteen;
uint tmp = (two_eight* datacube[width*i + j]) / two_sixteen;
//uint tmp = datacube[width*i + j];
//m_qimageFocusGrayImage->setPixel(j, i, tmp);
m_qimageFocusGrayImage->setPixel(j, i, qRgb((unsigned char)tmp, (unsigned char)tmp, (unsigned char)tmp));
unsigned char gray = static_cast<unsigned char>(srcRow[j] * scale);
scanLine[j] = qRgb(gray, gray, gray);
}
}

View File

@ -1,5 +1,5 @@
#include "imageControl.h"
#include "RasterLayer.h"
#include "RasterImageLayer.h"
#include <algorithm>
#include <cmath>
@ -8,6 +8,14 @@ ImageControl::ImageControl(QWidget* parent)
{
ui.setupUi(this);
ui.sliderRed->setPageStep(0);
ui.sliderGreen->setPageStep(0);
ui.sliderBlue->setPageStep(0);
ui.sliderRed->setSingleStep(0);
ui.sliderGreen->setSingleStep(0);
ui.sliderBlue->setSingleStep(0);
// Spinbox valueChanged: only sync the paired slider (no render)
connect(ui.spinRed, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &ImageControl::onSpinRedValueChanged);
connect(ui.spinGreen, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &ImageControl::onSpinGreenValueChanged);
@ -91,7 +99,7 @@ ImageControl::~ImageControl()
{
}
void ImageControl::setActiveLayer(RasterLayer* layer)
void ImageControl::setActiveLayer(RasterImageLayer* layer)
{
m_activeLayer = layer;
@ -102,8 +110,8 @@ void ImageControl::setActiveLayer(RasterLayer* layer)
}
setEnabled(true);
// Get band wavelengths from the layer's header
m_wavelengths = layer->bandWavelengths();
// Get band wavelengths from the underlying RasterLayer's header
m_wavelengths = layer->layer()->bandWavelengths();
std::sort(m_wavelengths.begin(), m_wavelengths.end());
if (m_wavelengths.empty()) {
@ -137,19 +145,13 @@ void ImageControl::setActiveLayer(RasterLayer* layer)
int maxIdx = static_cast<int>(m_wavelengths.size()) - 1;
ui.sliderRed->setMinimum(0);
ui.sliderRed->setMaximum(maxIdx);
ui.sliderRed->setSingleStep(1);
ui.sliderRed->setPageStep(1);
ui.sliderGreen->setMinimum(0);
ui.sliderGreen->setMaximum(maxIdx);
ui.sliderGreen->setSingleStep(1);
ui.sliderGreen->setPageStep(1);
ui.sliderBlue->setMinimum(0);
ui.sliderBlue->setMaximum(maxIdx);
ui.sliderBlue->setSingleStep(1);
ui.sliderBlue->setPageStep(1);
// Set current values from layer's render params
auto params = layer->currentRenderParams();
// Set current values from layer's render params (multiband)
auto params = layer->multibandParams();
int rIdx = nearestBandIndex(params.rWave);
int gIdx = nearestBandIndex(params.gWave);
@ -166,7 +168,7 @@ void ImageControl::setActiveLayer(RasterLayer* layer)
blockAllSignals(false);
}
RasterLayer* ImageControl::activeLayer() const
RasterImageLayer* ImageControl::activeLayer() const
{
return m_activeLayer;
}
@ -324,13 +326,13 @@ void ImageControl::emitBandChange()
double g = ui.spinGreen->value();
double b = ui.spinBlue->value();
// Update active layer's stored render params
// Update active layer's stored render params (multiband)
if (m_activeLayer) {
auto params = m_activeLayer->currentRenderParams();
auto params = m_activeLayer->multibandParams();
params.rWave = r;
params.gWave = g;
params.bWave = b;
m_activeLayer->setCurrentRenderParams(params);
m_activeLayer->setMultibandParams(params);
}
emit bandSelectionChanged(r, g, b);

View File

@ -6,9 +6,10 @@
#include <QNetworkAccessManager>
#include <vector>
#include "RasterLayer.h"
#include "ui_imgControl.h"
class RasterLayer;
class RasterImageLayer;
class ImageControl : public QDialog
{
@ -18,9 +19,9 @@ public:
ImageControl(QWidget* parent = nullptr);
~ImageControl();
// Populate controls from a RasterLayer's wavelength info and current render params
void setActiveLayer(RasterLayer* layer);
RasterLayer* activeLayer() const;
// Populate controls from a RasterImageLayer's wavelength info and current render params
void setActiveLayer(RasterImageLayer* layer);
RasterImageLayer* activeLayer() const;
public Q_SLOTS:
@ -62,7 +63,7 @@ private:
void setControlsToBandIndex(QDoubleSpinBox* spin, QSlider* slider, int idx);
Ui::ImageControl ui;
RasterLayer* m_activeLayer = nullptr;
RasterImageLayer* m_activeLayer = nullptr;
double m_minWave = 374.5;
double m_maxWave = 948.1;
std::vector<double> m_wavelengths; // band wavelengths from header

View File

@ -1,5 +1,6 @@
#include "stdafx.h"
#include "recordFrameCounter.h"
#include "RasterLayer.h"
recordFrameCounter::recordFrameCounter(QWidget* parent)
: QWidget(parent)
@ -16,19 +17,19 @@ recordFrameCounter::recordFrameCounter(QWidget* parent)
layout->addWidget(m_stackedWidget);
}
void recordFrameCounter::addCounter(QWidget* tabWidget)
void recordFrameCounter::addCounter(RasterLayer* mapLayer)
{
QLabel* label = new QLabel("0");
label->setStyleSheet("color: white;");
label->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
m_labelMap.insert(tabWidget, label);
m_labelMap.insert(mapLayer, label);
m_stackedWidget->addWidget(label);
m_stackedWidget->setCurrentWidget(label);
}
void recordFrameCounter::removeCounter(QWidget* tabWidget)
void recordFrameCounter::removeCounter(RasterLayer* mapLayer)
{
auto it = m_labelMap.find(tabWidget);
auto it = m_labelMap.find(mapLayer);
if (it != m_labelMap.end())
{
QLabel* label = it.value();
@ -38,18 +39,18 @@ void recordFrameCounter::removeCounter(QWidget* tabWidget)
}
}
void recordFrameCounter::switchTo(QWidget* tabWidget)
void recordFrameCounter::switchTo(RasterLayer* mapLayer)
{
auto it = m_labelMap.find(tabWidget);
auto it = m_labelMap.find(mapLayer);
if (it != m_labelMap.end())
{
m_stackedWidget->setCurrentWidget(it.value());
}
}
void recordFrameCounter::updateFrameCount(QWidget* tabWidget, int frameCount)
void recordFrameCounter::updateFrameCount(RasterLayer* mapLayer, int frameCount)
{
auto it = m_labelMap.find(tabWidget);
auto it = m_labelMap.find(mapLayer);
if (it != m_labelMap.end())
{
it.value()->setText(QString::number(frameCount));

View File

@ -6,19 +6,20 @@
#include <QHBoxLayout>
#include <QMap>
class RasterLayer;
class recordFrameCounter : public QWidget
{
Q_OBJECT
public:
explicit recordFrameCounter(QWidget* parent = nullptr);
void addCounter(QWidget* tabWidget);
void removeCounter(QWidget* tabWidget);
void switchTo(QWidget* tabWidget);
void updateFrameCount(QWidget* tabWidget, int frameCount);
void addCounter(RasterLayer* mapLayer);
void removeCounter(RasterLayer* mapLayer);
void switchTo(RasterLayer* mapLayer);
void updateFrameCount(RasterLayer* mapLayer, int frameCount);
private:
QStackedWidget* m_stackedWidget = nullptr;
QMap<QWidget*, QLabel*> m_labelMap;
QMap<RasterLayer*, QLabel*> m_labelMap;
};

View File

@ -18,7 +18,7 @@ rgbCameraWindow::rgbCameraWindow(QWidget* parent)
//connect(this->ui.open_rgb_camera_btn, SIGNAL(clicked()), m_RgbCamera, SLOT(OpenCamera_callback()));//ʹ<>ûص<C3BB><D8B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ˢ<EFBFBD><CBA2><EFBFBD><EFBFBD><EFBFBD>̣߳<DFB3>ui<75>̣߳<DFB3><CCA3>ϵ<EFBFBD><CFB5><EFBFBD>Ƶ <20><> ʧ<><CAA7>
connect(ui.close_rgb_camera_btn, SIGNAL(clicked()), this, SLOT(onCloseRgbCamera()));//<2F>ر<EFBFBD><D8B1><EFBFBD><EFBFBD><EFBFBD>
connect(m_RgbCamera, SIGNAL(CamClosed()), this, SIGNAL(CamClosedSignal()));
connect(m_RgbCamera, SIGNAL(CamClosedSignal()), this, SIGNAL(CamClosedSignal()));
}
rgbCameraWindow::~rgbCameraWindow()

View File

@ -9,8 +9,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>486</width>
<height>229</height>
<width>641</width>
<height>320</height>
</rect>
</property>
<property name="windowTitle">
@ -234,26 +234,58 @@ QPushButton:pressed
</item>
<item row="1" column="0">
<widget class="QWidget" name="widget" native="true">
<layout class="QGridLayout" name="gridLayout_2">
<layout class="QGridLayout" name="gridLayout_2" rowstretch="3,2">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>数据路径</string>
</property>
<widget class="QWidget" name="widget_2" native="true">
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>数据路径</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="dataFolderLineEdit">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QPushButton" name="dataFolderBtn">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="dataFolderLineEdit">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QPushButton" name="dataFolderBtn">
<property name="text">
<string>...</string>
</property>
<item row="1" column="0">
<widget class="QWidget" name="widget_3" native="true">
<layout class="QGridLayout" name="gridLayout_4" columnstretch="5,2">
<item row="0" column="0">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>411</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="confirmBtn">
<property name="text">
<string>确认</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>

Some files were not shown because too many files have changed in this diff Show More