Files
ds-628/HanddleAI/QtCameraDebug.cpp
2024-10-17 16:37:42 +08:00

1704 lines
67 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "QtCameraDebug.h"
#include "qmessagebox.h"
#include"qfiledialog.h"
#include "qdatetime.h"
#include "qmutex.h"
#include "qfuture.h"
#include "QtConcurrent/qtconcurrent"
#pragma execution_character_set("utf-8")
//相机列表添加相机
QString cameraTypeText;
typedef PbGlobalObject* (*CreateFunction)(int type);
typedef void (*ReleaseFunction)(PbGlobalObject* animal);
typedef struct {
PbGlobalObject* module_ptr = nullptr;
ReleaseFunction destory_ptr; // 释放
QMap<QString, QString> myParasValueMap; //配置文件
QString cameraKey;
}MyPbGlobalObject;
//当前的相机模块
MyPbGlobalObject myPbGlobalObject;
//总的相机模块
QQueue< MyPbGlobalObject> queue_MyPbGlobalObject;
QMessageBox* myBox;
QJsonObject cameraListObj;
QString json_cameraList_path = "";
bool ifLoadPar = true;
//初次加载,未点击相机列表,不会显示相机参数;不可进行初始化
bool ifFirstLoad = true;
bool ifSetBox = false;
QString saveDirPath;//图片保存文件夹
QMutex* saveStruct_mutex;
bool ifRun = false;
QString cameraDebugPath;
QtCameraDebug::QtCameraDebug(QWidget* parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//追踪鼠标,写在构造函数中
this->setMouseTracking(true);
ui.centralWidget->setMouseTracking(true);
ui.frame->setMouseTracking(true);
ui.title->setMouseTracking(true);
ui.label_icon->setStyleSheet("image: url(./Icon/logo_Dongsheng.png);");
ui.pushButton_min->setText("");
ui.pushButton_close->setText("");
ui.pushButton_max->setText("");
ui.pushButton_min->setStyleSheet("background-color:transparent;image: url(./Icon/min_n.png);");
ui.pushButton_close->setStyleSheet("background-color:transparent;image: url(./Icon/close_n.png);");
ui.pushButton_max->setStyleSheet("background-color:transparent;image: url(./Icon/Max_n.png);");
connect(ui.pushButton_min, &QPushButton::clicked, [=]() {
this->showMinimized();
qApp->processEvents();
});
connect(ui.pushButton_close, &QPushButton::clicked, [=]() {
this->close();
qApp->processEvents();
});
QScreen* screen = QGuiApplication::primaryScreen();
QSize screenSize = screen->size();
static int screenWidth = screenSize.width();
static int screenHeight = screenSize.height();
qDebug() << "Screen resolution: " << screenWidth << "x" << screenHeight;
static int maxClickedNum = 1;
connect(ui.pushButton_max, &QPushButton::clicked, [=]() {
if (maxClickedNum)
{
//ui.pushButton_max->setStyleSheet("background-color:transparent;image: url(Max_n.png);");
//ui.pushButton_max->setToolTip(tr("向下还原"));
setWindowFlags(Qt::FramelessWindowHint); //隐藏标题栏
this->showMaximized();
maxClickedNum = 0;
}
else {
//ui.pushButton_max->setStyleSheet("background-color:transparent;image: url(Max_n.png);");
//ui.pushButton_max->setToolTip(tr("最大化"));
setWindowFlags(Qt::FramelessWindowHint); //隐藏标题栏
this->showNormal();
this->resize(screenWidth / 3 * 2, screenHeight / 3 * 2);
this->move(screenWidth / 5, screenHeight / 5);
maxClickedNum = 1;
}
qApp->processEvents();
});
setWindowFlags(Qt::FramelessWindowHint); //隐藏标题栏
//this->showNormal();
this->resize(screenWidth / 3 * 2, screenHeight / 3 * 2);
this->move(screenWidth / 5, screenHeight / 5);
myBox = new QMessageBox;
saveStruct_mutex = new QMutex;
ifRun = true;
QFuture<void> future2 = QtConcurrent::run(this, &QtCameraDebug::saveImgThread);
////添加
//connect(ui.pushButton_add, &QPushButton::clicked, [=]() {
// ui.tableWidget->setRowCount(ui.tableWidget->rowCount() + 1);
// int rowNum = ui.tableWidget->rowCount();
// QTableWidgetItem* m_Item0 = new QTableWidgetItem;
// //m_Item0->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
// m_Item0->setText("");
// ui.tableWidget->setItem(rowNum - 1, 0, m_Item0);
// //QString nowTime = QDateTime::currentDateTime().toString("yyyy-MM-dd");
// QTableWidgetItem* m_Item1 = new QTableWidgetItem;
// //m_Item1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
// m_Item1->setText("");
// ui.tableWidget->setItem(rowNum - 1, 1, m_Item1);
// });
////删除
//connect(ui.pushButton_del, &QPushButton::clicked, [=]() {
// if (ui.tableWidget->rowCount() < 2 || ui.tableWidget->currentRow() < 1)
// return;
// ui.tableWidget->removeRow(ui.tableWidget->currentRow());
// });
////加载默认参数
//connect(ui.pushButton_loadExample, &QPushButton::clicked, [=]() {
// ifload_camera_Example = true;
// ifLoadPar = true;
// if (createModule() == true)
// {
// show_myParasValueMap();
// /*if (m_module.module_ptr->initParas(m_module.m_initByte))
// {
// qDebug() << __FUNCTION__ << " line: " << __LINE__ << " key: " << m_module.module_key << " initParas success! ";
// }
// else
// {
// qCritical() << __FUNCTION__ << " line: " << __LINE__ << " moduleName: " << m_module.moduleName << " initParas failed! ";
// return false;
// }*/
// }
// else
// {
// QMessageBox* myBox = new QMessageBox;
// myBox->information(this, "失败", "加载默认参数失败!"); return;
// }
// ui.pushButton_initModel->setDisabled(false);
// ifLoadPar = false;
// });
ui.pushButton_initModel->setStyleSheet("QPushButton{image: url(./Icon/1.1.添加图形.png);}"
"QPushButton:hover{ background-color: rgb(32, 36, 40); border:none; color:rgb(255, 255, 255); }");
//初始化模块
connect(ui.pushButton_initModel, &QPushButton::clicked, [=]() {
ui.pushButton_closeModel->setDisabled(false);
ui.pushButton_initModel->setDisabled(true);
ui.pushButton_GetImage->setDisabled(false);
ui.pushButton_GetImage_Aways->setDisabled(false);
//传入initParas函数,格式为:相机key+参数名1#参数值1#参数值2+参数名2#参数值1...
//QString initByte= ui.tableWidget->item(0,1)->text();
//按照界面参数初始化
QMap<QString, QString> myParasValueMap;
for (int i = 0; i < ui.tableWidget->rowCount(); i++)
{
if (ui.tableWidget->item(i, 0)->text().isEmpty() || ui.tableWidget->item(i, 1)->text().isEmpty())
{
myBox->information(this, "相机参数错误", "相机参数名或参数值为空"); return false;
}
if (ui.tableWidget->item(i, 0)->text() == "相机key" && ui.tableWidget->item(i, 1)->text() == "输入SN")
{
myBox->information(this, "相机key参数错误", "未输入SN"); return false;
}
if (!ui.tableWidget->item(i, 0)->text().isEmpty() && !ui.tableWidget->item(i, 1)->text().isEmpty())
myParasValueMap.insert(ui.tableWidget->item(i, 0)->text(), ui.tableWidget->item(i, 1)->text());
/*if (!ui.tableWidget->item(i, 0)->text().isEmpty())
initByte += "+"+ui.tableWidget->item(i, 0)->text()+"#";
if (!ui.tableWidget->item(i, 1)->text().isEmpty())
initByte += ui.tableWidget->item(i, 1)->text().replace(",", "#");*/
/*{
QStringList values = ui.tableWidget->item(i, 1)->text().split(",");
initByte.replace("1", "2");
}*/
}
if (ui.tableWidget_2->rowCount() == 0 || ui.tableWidget_2->currentItem() == nullptr)
{
myBox->information(this, "失败", "初始化失败,未选择相机");
ui.pushButton_closeModel->setDisabled(!false);
ui.pushButton_initModel->setDisabled(!true);
ui.pushButton_GetImage->setDisabled(!false);
ui.pushButton_GetImage_Aways->setDisabled(!false);
return false;
}
//开头为 相机0
int myIndex = ui.tableWidget_2->currentItem()->text().split(":")[0].split("相机")[1].toInt();
if (queue_MyPbGlobalObject[myIndex].module_ptr == NULL)
{
type = queue_MyPbGlobalObject[myIndex].myParasValueMap.value("type").toInt();
index = myIndex;
//ifload_camera_Example = false;
if (createModule() == false)
{
QMessageBox* myBox = new QMessageBox;
myBox->information(this, "失败", "加载默认参数失败!"); return false;
}
queue_MyPbGlobalObject[myIndex] = myPbGlobalObject;
}
queue_MyPbGlobalObject[myIndex].module_ptr->setParameter(myParasValueMap);
qDebug() << "id::"<<queue_MyPbGlobalObject[myIndex].module_ptr->id;
if (!queue_MyPbGlobalObject[myIndex].module_ptr->init())
{
myBox->information(this, "失败", "相机模块初始化失败!");
ui.pushButton_closeModel->setDisabled(!false);
ui.pushButton_initModel->setDisabled(!true);
ui.pushButton_GetImage->setDisabled(!false);
ui.pushButton_GetImage_Aways->setDisabled(!false);
return false;
}
});
ui.pushButton_GetImage->setStyleSheet("QPushButton{image: url(./Icon/5.单样本.png);}"
"QPushButton:hover{ background-color: rgb(32, 36, 40); border:none; color:rgb(255, 255, 255); }");
//获取一张图像
connect(ui.pushButton_GetImage, &QPushButton::clicked, [=]() {
std::vector<cv::Mat> ImgS;
QStringList data;
clock_t start, stop;
start = clock();
if (ui.tableWidget_2->rowCount() == 0 || ui.tableWidget_2->currentItem() == nullptr)
return;
//开头为 相机0
int myIndex = ui.tableWidget_2->currentItem()->text().split(":")[0].split("相机")[1].toInt();
bool runResult = queue_MyPbGlobalObject[myIndex].module_ptr->setData(ImgS, data);
stop = clock();
std::cout << "setData Time::" << stop - start << std::endl;
start = clock();
if (runResult == true)
{
queue_MyPbGlobalObject[myIndex].module_ptr->data(ImgS, data);
stop = clock();
std::cout << "data Time::" << stop - start << std::endl;
start = clock();
if (ImgS.size() > 0)
decodeImage("m_PbGlobalObject.module_key", ImgS[0]);
stop = clock();
std::cout << "decodeImage Time::" << stop - start << std::endl;
start = clock();
}
});
static bool ifFirstAways = true;
static QTimer* myTimer = new QTimer;
connect(myTimer, &QTimer::timeout, [=]() {
if (ifFirstAways == true)
return;
std::vector<cv::Mat> ImgS;
QStringList data;
if (ui.tableWidget_2->rowCount() == 0 || ui.tableWidget_2->currentItem() == nullptr)
return;
//开头为 相机0
int myIndex = ui.tableWidget_2->currentItem()->text().split(":")[0].split("相机")[1].toInt();
if (queue_MyPbGlobalObject[myIndex].module_ptr == nullptr)
return;
bool runResult = queue_MyPbGlobalObject[myIndex].module_ptr->setData(ImgS, data);
if (runResult == true)
{
queue_MyPbGlobalObject[myIndex].module_ptr->data(ImgS, data);
if (ImgS.size() > 0)
decodeImage("m_PbGlobalObject.module_key", ImgS[0]);
}
qApp->processEvents();
});
ui.pushButton_GetImage_Aways->setStyleSheet("QPushButton{image: url(./Icon/4.1.项目运行.png);}"
"QPushButton:hover{ background-color: rgb(32, 36, 40); border:none; color:rgb(255, 255, 255); }");
//循环运行
connect(ui.pushButton_GetImage_Aways, &QPushButton::clicked, [=]() {
if (ifFirstAways)
{
ui.pushButton_GetImage->setDisabled(true);
myTimer->start(1);
ui.label_GetImage_Aways->setText("循环获取图像-停止");
ui.pushButton_GetImage_Aways->setStyleSheet("QPushButton{image: url(./Icon/4.6.项目运行.png);}"
"QPushButton:hover{ background-color: rgb(32, 36, 40); border:none; color:rgb(255, 255, 255); }");
}
else
{
ui.pushButton_GetImage->setDisabled(false);
myTimer->stop();
ui.label_GetImage_Aways->setText("循环获取图像-开始");
ui.pushButton_GetImage_Aways->setStyleSheet("QPushButton{image: url(./Icon/4.1.项目运行.png);}"
"QPushButton:hover{ background-color: rgb(32, 36, 40); border:none; color:rgb(255, 255, 255); }");
}
ifFirstAways = !ifFirstAways;
});
ui.pushButton_closeModel->setStyleSheet("QPushButton{image: url(./Icon/16.1.关闭.png);}"
"QPushButton:hover{ background-color: rgb(32, 36, 40); border:none; color:rgb(255, 255, 255); }");
//卸载模块
connect(ui.pushButton_closeModel, &QPushButton::clicked, [=]() {
if (ifFirstAways == false)
{
ui.pushButton_GetImage_Aways->click();
}
ui.pushButton_closeModel->setDisabled(true);
ui.pushButton_GetImage->setDisabled(true);
ui.pushButton_GetImage_Aways->setDisabled(true);
ui.pushButton_initModel->setDisabled(false);
if (ui.tableWidget_2->rowCount() == 0 || ui.tableWidget_2->currentItem() == nullptr)
return;
//开头为 相机0
int myIndex = ui.tableWidget_2->currentItem()->text().split(":")[0].split("相机")[1].toInt();
bool ifOK = closeCameraModel(myIndex);
if (!ifOK)
{
myBox->information(this, "失败", "卸载模块失败"); return;
}
/*PbGlobalObject* base_ptr = const_cast<PbGlobalObject*>(queue_MyPbGlobalObject[myIndex].module_ptr);
queue_MyPbGlobalObject[myIndex].destory_ptr(base_ptr);
queue_MyPbGlobalObject[myIndex].module_ptr = nullptr;*/
});
QImageWidget* myQImageWidget = nullptr;
m_pImageList.append(myQImageWidget);
QGraphicsScene* myqgraphicsScene = new QGraphicsScene;
qgraphicsSceneList.append(myqgraphicsScene);
QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Expanding);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
ui.tableWidget->setSizePolicy(sizePolicy1);
ui.tableWidget->setColumnCount(2);
ui.tableWidget->setMouseTracking(true);
ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); // 整行选中
ui.tableWidget->horizontalHeader()->setSectionsClickable(false);
ui.tableWidget->verticalHeader()->hide();
ui.tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui.tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:rgb(65,65,65);}");
ui.tableWidget_2->setColumnCount(1);
ui.tableWidget_2->setMouseTracking(true);
ui.tableWidget_2->setSelectionBehavior(QAbstractItemView::SelectRows); // 整行选中
ui.tableWidget_2->horizontalHeader()->setSectionsClickable(false);
ui.tableWidget_2->verticalHeader()->hide();
ui.tableWidget_2->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui.tableWidget_2->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:rgb(65,65,65);}");
ui.tableWidget_2->horizontalHeader()->hide();
ui.pushButton_saveCamera->setStyleSheet("QPushButton{background-color:rgb(68, 74, 80);border-radius:10px;}"
"QPushButton:hover{ background-color: rgb(0, 0, 0); border:none; color:rgb(255, 255, 255); }");
connect(ui.pushButton_saveCamera, &QPushButton::clicked, [=]() {
qApp->processEvents();
if (ifLoadPar == true )//|| ifload_camera_Example == true)
{
myBox->information(this, "失败", "不匹配,保存参数失败!");
return;
}
if (ui.tableWidget_2->currentRow() < 0)
{
myBox->information(this, "失败", "未选择相机,保存参数失败!");
return;
}
if (refresh_myParasValueMap())
{
int myindex = ui.tableWidget_2->currentRow();
if (myindex < 0)
return;
queue_MyPbGlobalObject[myindex] = myPbGlobalObject;
saveCfg();
}
});
connect(ui.tableWidget_2, &QTableWidget::cellClicked, [=]() {
ifLoadPar = true;
if (ui.tableWidget_2->currentRow() < 0)
return;
QString mytext = ui.tableWidget_2->currentItem()->text();
QString moduleType = mytext.split(": ")[1];//拼接有空格
if (mytext.contains("硬触发"))
{
ui.checkBox_hard->setChecked(true);
moduleType.replace("硬触发", "");
}
else if (mytext.contains("软触发"))
{
ui.checkBox_soft->setChecked(true);
moduleType.replace("软触发", "");
}
ifSetBox = true;
ui.comboBox->setCurrentText(moduleType); //有问题把?
//开头为 相机0
int myIndex = ui.tableWidget_2->currentItem()->text().split(":")[0].split("相机")[1].toInt();
if (queue_MyPbGlobalObject.size() <= myIndex)
return;
myPbGlobalObject = queue_MyPbGlobalObject[myIndex];
//显示参数
show_myParasValueMap();
ifLoadPar = false;
if (ifFirstLoad == true)
{
ui.pushButton_initModel->setDisabled(false);
ifFirstLoad = false;
}
ifSetBox = false;
QImage* itemImage = new QImage(100,100,QImage::Format_RGB888);
itemImage->fill(QColor(Qt::black));
showTransferImage("null", itemImage);
ui.pushButton_closeModel->click();
});
initCombox();
this->show();
Sleep(50);
connect(ui.comboBox, &QComboBox::currentTextChanged, [=]() {
////显示到界面
//for (int i = 1; i < ui.tableWidget->rowCount(); i++)
// ui.tableWidget->removeRow(i);
ifLoadPar = true;
ui.tableWidget->setRowCount(0);
if (ifSetBox == false)
ifLoadPar = false;
QJsonObject newprogramObj;
newprogramObj.insert("上次打开", ui.comboBox->currentText());
//内存中的数据写到文件
QJsonDocument doc(newprogramObj);
//将json对象转换成字符串
QByteArray data = doc.toJson();
QFile file(cameraDebugPath);
file.open(QIODevice::WriteOnly);
file.write(data);
file.close();
ui.pushButton_closeModel->click();
queue_MyPbGlobalObject.clear();
showCameraList(ui.comboBox->currentText());
});
QDir dir = QApplication::applicationDirPath();
QString currPath = dir.path();
cameraDebugPath = currPath + "/config/cameraDebug_lastCfg.json";
QFile myf(cameraDebugPath);
if (myf.exists())
{
QByteArray m_Byte = myf.readAll();
if (!m_Byte.isEmpty())
{
QJsonDocument jsonDocument(QJsonDocument::fromJson(m_Byte));
if (jsonDocument.isObject())
{
QJsonObject json_object = jsonDocument.object();
myf.close();
QString lastName = json_object.value("上次打开").toString();
if (lastName.contains(".json"))
{
QString lastjson = currPath + "/config/"+ lastName;
QFile lastF(lastjson);
if (myf.exists())
{
showCameraList(lastName);
}
}
}
}
}
else
{
myf.open(QIODevice::Append);
}
ui.pushButton_closeModel->setDisabled(true);
ui.pushButton_GetImage->setDisabled(true);
ui.pushButton_GetImage_Aways->setDisabled(true);
ui.pushButton_initModel->setDisabled(true);
ui.pushButton->setStyleSheet("QPushButton{background-color:rgb(68, 74, 80);border-radius:10px;}"
"QPushButton:hover{ background-color: rgb(0, 0, 0); border:none; color:rgb(255, 255, 255); }");
connect(ui.pushButton, &QPushButton::clicked, [=]() {
saveDirPath = QFileDialog::getExistingDirectory(this, QString("选择图片文件夹"), QString("/"),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (saveDirPath.isEmpty() && !ui.lineEdit->text().isEmpty())
saveDirPath = ui.lineEdit->text();
ui.lineEdit->setText(saveDirPath);
if (saveDirPath.isEmpty())
ui.checkBox->setChecked(false);
});
connect(ui.checkBox, &QCheckBox::clicked, [=]() {
if(ui.checkBox->isChecked())
if (ui.lineEdit->text().isEmpty())
{
myBox->information(this, "错误", "保存图像路径为空,请先选择路径");
ui.checkBox->setChecked(false);
}
});
ui.pushButton_set->setStyleSheet("QPushButton{background-color:rgb(68, 74, 80);border-radius:10px;}"
"QPushButton:hover{ background-color: rgb(0, 0, 0); border:none; color:rgb(255, 255, 255); }");
//设置参数
connect(ui.pushButton_set, &QPushButton::clicked, [=]() {
std::vector<cv::Mat> ImgS;
QStringList data;
clock_t start, stop;
start = clock();
if (ui.tableWidget_2->rowCount() == 0 || ui.tableWidget_2->currentItem() == nullptr)
return;
//开头为 相机0
int myIndex = ui.tableWidget_2->currentItem()->text().split(":")[0].split("相机")[1].toInt();
data.append("SetExposureTime_" + ui.spinBox->text()+"#");
data.append("SetGain_" + ui.doubleSpinBox->text());
if (queue_MyPbGlobalObject[myIndex].module_ptr == nullptr)
{
myBox->information(this, "错误", "相机未初始化");
return;
}
bool runResult = queue_MyPbGlobalObject[myIndex].module_ptr->setData(ImgS, data);
});
}
QJsonObject QtCameraDebug::load_camera_Example()
{
QDir dir = QApplication::applicationDirPath();
QString currPath = dir.path();
QString json_cfg_file_path = currPath + "/config/camera_Example.json";
QJsonObject json_object;
try
{
QJsonParseError jsonError;
if (json_cfg_file_path.isEmpty())
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " JsonPath is null!";
return json_object;
}
QFile JsonFile;
JsonFile.setFileName(json_cfg_file_path);
if (!JsonFile.isReadable())
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " camera_cfg.json not isReadable!";
//return json_object;
}
JsonFile.open(QIODevice::ReadOnly);
QByteArray m_Byte = JsonFile.readAll();
if (m_Byte.isEmpty())
{
qDebug() << __FUNCTION__ << " line:" << __LINE__ << json_cfg_file_path + " Content is empty";
JsonFile.close();
return json_object;
}
QJsonDocument jsonDocument(QJsonDocument::fromJson(m_Byte, &jsonError));
if (!jsonDocument.isNull() && jsonError.error == QJsonParseError::NoError)
{
if (jsonDocument.isObject())
{
json_object = jsonDocument.object();
JsonFile.close();
return json_object;
}
}
else
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << json_cfg_file_path + " is error!";
}
JsonFile.close();
}
catch (QString ev)
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " ev:" << ev;
}
return json_object;
}
void QtCameraDebug::decodeImage(QString key, cv::Mat mtx)
{
try
{
if (!mtx.empty()) {
if ((mtx.dataend - mtx.datastart) != mtx.cols * mtx.rows * mtx.channels()) //尝试能否解决mtx内容异常问题
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " mtx.dataend - mtx.datastart err!!:";
return;// false;
}
//保存
if (ui.checkBox->isChecked() && !ui.lineEdit->text().isEmpty())
{
QString tmpDate = QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss-zzz");
QString savePath = saveDirPath + "/" + tmpDate + ".bmp";
addImgToSaveStruct(mtx, key, savePath);
}
cv::Mat rgb;
//while (mtx.cols > 2000 || mtx.rows > 2000)
// cv::resize(mtx, mtx, cv::Size(), 0.1, 0.1); //吃cpu性能,i7 8700,4800*4800的resize耗时100ms;QImage*的scaled缩放,耗时200ms
QImage* itemImage = nullptr;
if (mtx.type() == CV_8UC1)
{
rgb = mtx.clone(); //mtx.data检查后,只有2个数据,clone崩溃
itemImage = new QImage(QSize(rgb.cols, rgb.rows), QImage::Format_Grayscale8);
QImage qim((const unsigned char*)rgb.data, rgb.cols, rgb.rows, rgb.step, QImage::Format_Grayscale8);
*itemImage = qim.copy();
}
else if (mtx.type() == CV_16U) // 双通道转单通道显示
{
cv::normalize(mtx, mtx, 0, 255, cv::NORM_MINMAX);
cv::convertScaleAbs(mtx, rgb);
itemImage = new QImage(QSize(rgb.cols, rgb.rows), QImage::Format_Grayscale8);
QImage qim((const unsigned char*)rgb.data, rgb.cols, rgb.rows, rgb.step, QImage::Format_Grayscale8);
*itemImage = qim.copy();
}
else if (mtx.type() == CV_8UC3)
{
cv::cvtColor(mtx, rgb, cv::COLOR_BGR2RGB);
itemImage = new QImage(QSize(rgb.cols, rgb.rows), QImage::Format_RGB888);
QImage qim((const unsigned char*)rgb.data, rgb.cols, rgb.rows, rgb.step, QImage::Format_RGB888);
*itemImage = qim.copy();
}
else if (mtx.type() == CV_8UC4)
{
cv::cvtColor(mtx, rgb, cv::COLOR_BGRA2RGBA);
itemImage = new QImage(QSize(rgb.cols, rgb.rows), QImage::Format_ARGB32);
QImage qim((const unsigned char*)rgb.data, rgb.cols, rgb.rows, rgb.step, QImage::Format_ARGB32);
*itemImage = qim.copy();
}
//重新设置画布,有时耗时稍长,导致崩溃
nwith = ui.graphicsView->width();//获取界面控件Graphics View的宽度
nheight = ui.graphicsView->height();//获取界面控件Graphics View的高度
showTransferImage(key, itemImage);
}
}
catch (QString ev)
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " ev:" << ev;
return;// false;
}
return;// true;
}
void QtCameraDebug::showTransferImage(QString cameraKey_index, QImage* image)
{
//加锁卡死;不加锁,if (image)访问冲突
//QMutexLocker locker(showMutex);
//匹配
int index = 0;
//for (int i = 0; i < cameraKeyList.size(); i++)
// //if (cameraKey_index.contains(cameraKeyList[i]))
// if (cameraKey_index.split("_").size() > 1)
// if (cameraKey_index.split("_")[0] == cameraKeyList[i])
// {
// index = i;
// break;
// }
//if (index == -1)
//{
// if (image)
// {
// delete image;
// image = nullptr;
// }
// return;
//}
qgraphicsSceneList[index]->clear();
//ui.graphicsView->scene()->clear();
QPixmap ConvertPixmap;// = QPixmap::fromImage(image);//The QPixmap class is an off-screen image representation that can be used as a paint device
//ConvertPixmap.load(imgPath);
ConvertPixmap.convertFromImage(*image);
if (m_pImageList[index] != NULL)
m_pImageList[index] = nullptr;
//= new QGraphicsScene;//要用QGraphicsView就必须要有QGraphicsScene搭配着用
m_pImageList[index] = new QImageWidget(&ConvertPixmap);//实例化类ImageWidget的对象m_Image,该类继承自QGraphicsItem,是自己写的类
//int nwith = ui.graphicsView->width();//获取界面控件Graphics View的宽度
//int nheight = ui.graphicsView->height();//获取界面控件Graphics View的高度
m_pImageList[index]->setQGraphicsViewWH(nwith, nheight);//将界面控件Graphics View的width和height传进类m_Image中
qgraphicsSceneList[index]->addItem(m_pImageList[index]);//将QGraphicsItem类对象放进QGraphicsScene中
ui.graphicsView->setSceneRect(QRectF(-(nwith / 2), -(nheight / 2), nwith, nheight));//使视窗的大小固定在原始大小,不会随图片的放大而放大(默认状态下图片放大的时候视窗两边会自动出现滚动条,并且视窗内的视野会变大),防止图片放大后重新缩小的时候视窗太大而不方便观察图片
ui.graphicsView->setScene(qgraphicsSceneList[index]);//Sets the current scene to scene. If scene is already being viewed, this function does nothing.
ui.graphicsView->setFocus();//将界面的焦点设置到当前Graphics View控件
//qApp->processEvents();
/*_sleep(10);
if (qgraphicsScene)
{
delete qgraphicsScene;
qgraphicsScene = nullptr;
}*/
if (image)
{
delete image;
image = nullptr;
}
}
QtCameraDebug::~QtCameraDebug()
{
//emit QtCameraDebug_done();
Sleep(10);
ifRun = false;
Sleep(100);
if (myBox)
delete myBox;
}
bool QtCameraDebug::initCamera(int cameraIndex)
{
if (queue_MyPbGlobalObject.size() <= cameraIndex + 1)
return false;
if (queue_MyPbGlobalObject[cameraIndex].module_ptr == nullptr)
return false;
//参数检查
if (!queue_MyPbGlobalObject[cameraIndex].myParasValueMap.keys().contains("相机key"))
{
myBox->information(this, "失败", "模块参数错误!"); return false;
}
foreach(QString key, queue_MyPbGlobalObject[cameraIndex].myParasValueMap.keys())
{
QString value = queue_MyPbGlobalObject[cameraIndex].myParasValueMap.value(key);
if ((key.contains("相机key") && value.contains("输入")) || value.isEmpty())
{
myBox->information(this, "失败", "模块参数错误!"); return false;
}
}
queue_MyPbGlobalObject[cameraIndex].module_ptr->setParameter(queue_MyPbGlobalObject[cameraIndex].myParasValueMap);
if (!queue_MyPbGlobalObject[cameraIndex].module_ptr->init())
{
return false;
}
return true;
}
bool QtCameraDebug::setData(int cameraIndex, const vector<cv::Mat>& ImgS, const QStringList& data)
{
if (queue_MyPbGlobalObject.size() <= cameraIndex + 1)
return false;
if (queue_MyPbGlobalObject[cameraIndex].module_ptr == nullptr)
return false;
return queue_MyPbGlobalObject[cameraIndex].module_ptr->setData(ImgS, data);
}
bool QtCameraDebug::data(int cameraIndex, std::vector<cv::Mat>& ImgS, QStringList& data)
{
if (queue_MyPbGlobalObject.size() <= cameraIndex + 1)
return false;
if (queue_MyPbGlobalObject[cameraIndex].module_ptr == nullptr)
return false;
queue_MyPbGlobalObject[cameraIndex].module_ptr->data(ImgS, data);
if (ImgS.size() > 0)
decodeImage("m_PbGlobalObject.module_key", ImgS[0]);
else
return false;
return true;
}
bool QtCameraDebug::closeCameraModel(int cameraIndex)
{
ifLoadPar = true;
myPbGlobalObject.module_ptr = nullptr;
if (queue_MyPbGlobalObject.size() < cameraIndex + 1)
return false;
/*if (queue_MyPbGlobalObject[cameraIndex].module_ptr == nullptr)
{
queue_MyPbGlobalObject.removeAt(cameraIndex);
return true;
}*/
if (queue_MyPbGlobalObject[cameraIndex].module_ptr != nullptr)
{
//emit removeCamera(queue_MyPbGlobalObject[cameraIndex].module_ptr);
PbGlobalObject* base_ptr = const_cast<PbGlobalObject*>(queue_MyPbGlobalObject[cameraIndex].module_ptr);
queue_MyPbGlobalObject[cameraIndex].destory_ptr(base_ptr);
queue_MyPbGlobalObject[cameraIndex].module_ptr = nullptr;
//queue_MyPbGlobalObject[cameraIndex].cameraKey.clear();
queue_MyPbGlobalObject[cameraIndex].destory_ptr = nullptr;
//queue_MyPbGlobalObject[cameraIndex].myParasValueMap.clear();
}
bool closeOk = true;
qDebug() << "closeModel(myIndex)::" << closeOk;
//if (closeOk)
//{
// ui.tableWidget_2->removeRow(cameraIndex);
// qDebug() << "queue_MyPbGlobalObject.size():" << queue_MyPbGlobalObject.size();
// //是否考虑序号问题
// {
// index--;
// if (ui.tableWidget_2->currentRow() >= 0)
// {
// for (int i = cameraIndex; i < ui.tableWidget_2->rowCount(); i++)
// {
// QString text = ui.tableWidget_2->item(i, 0)->text();
// int myIndex = text.split(":")[0].split("相机")[1].toInt();
// text.replace("相机" + QString::number(myIndex), "");
// myIndex--;
// if (myIndex < 0)
// {
// myBox->information(this, "失败", "卸载模块失败");
// return false;
// }
// ui.tableWidget_2->item(i, 0)->setText("相机" + QString::number(myIndex) + text);
// }
// }
// queue_MyPbGlobalObject.removeAt(cameraIndex);
// }
//}
/*for (int i = 0; i < queue_MyPbGlobalObject.size(); i++)
{
QJsonObject newCameraObj;
foreach(QString key, queue_MyPbGlobalObject[i].myParasValueMap.keys())
{
newCameraObj.insert(key, queue_MyPbGlobalObject[i].myParasValueMap.value(key));
}
newprogramObj.insert(QString::number(i), newCameraObj);
}*/
saveCfg();
ifLoadPar = false;
return true;
}
bool QtCameraDebug::createModule()
{
//QString moduleName = "";
{
type = -1;
if (cameraTypeText.contains("2D:海康(面阵/线扫)") && ui.checkBox_hard->isChecked())
//moduleName = "Hd_CameraModule_HIK_hard#" + ui.spinBox_index->text();
type = HIK_Hard;
else if (cameraTypeText.contains("2D:海康(面阵/线扫)") && ui.checkBox_soft->isChecked())
type = HIK_Soft;
//moduleName = "Hd_CameraModule_HIK_soft#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:Basler(面阵/线扫)") && ui.checkBox_hard->isChecked())
type = Basler_Hard;
//moduleName = "Hd_CameraModule_Basler_hard#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:Basler(面阵/线扫)") && ui.checkBox_soft->isChecked())
type = Basler_Soft;
//moduleName = "Hd_CameraModule_Basler_soft#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:大恒(面阵)") && ui.checkBox_hard->isChecked())
type = DaHeng_Hard;
//moduleName = "Hd_CameraModule_DaHeng_hard#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:大恒(面阵)") && ui.checkBox_soft->isChecked())
type = DaHeng_Soft;
//moduleName = "Hd_CameraModule_DaHeng_soft#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:大华(面阵)") && ui.checkBox_hard->isChecked())
type = DaHua_Hard;
//moduleName = "Hd_CameraModule_DaHua_hard#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:大华(面阵)") && ui.checkBox_soft->isChecked())
type = DaHua_Soft;
//moduleName = "Hd_CameraModule_DaHua_soft#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:埃科(线扫)") && ui.checkBox_hard->isChecked())
type = ITEK_Hard;
//moduleName = "Hd_CameraModule_ITEK_hard#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:埃科(线扫)") && ui.checkBox_soft->isChecked())
type = ITEK_Soft;
//moduleName = "Hd_CameraModule_ITEK_soft#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:Opt(面阵)") && ui.checkBox_soft->isChecked())
type = OPT_Soft;
//moduleName = "Hd_CameraModule_OPT_soft#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:Dalsa(网口线扫)"))
type = Dalsa;
//moduleName = "Hd_CameraModule_Dalsa#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:Dalsa(采集卡线扫)") && ui.checkBox_hard->isChecked())
type = DalsaDAQ_Hard;
//moduleName = "Hd_CameraModule_DalsaDAQH#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2D:Dalsa(采集卡线扫)") && ui.checkBox_soft->isChecked())
type = DalsaDAQ_Soft;
//moduleName = "Hd_CameraModule_DalsaDAQ#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("3D:基恩士"))
type = Keyence_3D;
//moduleName = "Hd_CameraModule_3DKeyence#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("3D:LMI"))
type = LMI_3D;
//moduleName = "Hd_CameraModule_3DLMI#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("3D:深视智能"))
type = Sszn_3D;
//moduleName = "Hd_CameraModule_3DSszn#" + ui.spinBox_index->text();
else if (cameraTypeText.contains("2.5D:基恩士"))
type = Keyence_25D;
else if (cameraTypeText.contains("离线:读图模块"))
type = ReadImage;
}
if (type == -1)
{
myBox->information(this, "失败", "加载默认相机参数失败"); return false;
}
//moduleName = "Hd_25DCameraVJ_module#" + ui.spinBox_index->text();
//qDebug() << "moduleName::" << moduleName;
QDir dir = QApplication::applicationDirPath();
QString currPath = dir.path();
QString module_path = currPath + "/Hd_CameraModule_All#" + QString::number(index);
if (module_path.contains("#"))
{
QStringList myList = module_path.split("#");
if (myList.size() == 2)
{
//if (myList[1].toInt() > 0)
{
//命名格式: 模块名#1/2/3...13/14...;如:Hd_AI_Bian_module#1;按此修改配置文件
//注意,模块代码修改后,要删除复制的模块,再运行程序;
QFile dllFile(module_path + ".dll");
if (dllFile.exists())
{
dllFile.remove();
Sleep(100);
}
QString path_model = myList[0];// module_path.mid(0, module_path.size() - 1);
//if (!QFile::exists(module_path + ".dll") && QFile::exists(path_model + ".dll"))
{
QFile::copy(path_model + ".dll", module_path + ".dll");
//QFile::copy(path_model + ".pdb", module_path + ".pdb");
//qDebug() << "[INFO] " << "copy dll " << m_module.moduleName;
}
}
}
}
QLibrary* m_lib = new QLibrary(module_path);
//lib_list.append(m_lib);
bool flag = m_lib->load();
if (!m_lib->isLoaded())
{
qDebug() << __FUNCTION__ << __LINE__ << " Loaded error:" << m_lib->errorString();
delete m_lib;
m_lib = nullptr;
return false;
}
CreateFunction createFun = (CreateFunction)m_lib->resolve("create");
ReleaseFunction releaseFun = (ReleaseFunction)m_lib->resolve("destory");
if (createFun && releaseFun)
{
myPbGlobalObject.module_ptr = createFun(type);
myPbGlobalObject.destory_ptr = releaseFun;
myPbGlobalObject.module_ptr->id = index;
//if (ifload_camera_Example)
//{
// //获取示例参数
// QMap<QString, QString> myParasValueMap = myPbGlobalObject.module_ptr->parameters();
// myPbGlobalObject.myParasValueMap = myParasValueMap;
// show_myParasValueMap();
//}
//else
{
refresh_myParasValueMap();
}
}
else
{
delete m_lib;
m_lib = nullptr;
return false;
}
return true;
}
void QtCameraDebug::show_myParasValueMap()
{
//显示到界面
for (int i = 1; i < ui.tableWidget->rowCount(); i++)
ui.tableWidget->removeRow(i);
ui.tableWidget->setRowCount(1);
ui.tableWidget->setItem(0, 0, new QTableWidgetItem("相机key"));
ui.tableWidget->setItem(0, 1, new QTableWidgetItem(myPbGlobalObject.myParasValueMap.value("相机key")));
QStringList list;
list << "参数名" << "参数值" ;
ui.tableWidget->setHorizontalHeaderLabels(list);
myPbGlobalObject.cameraKey = myPbGlobalObject.myParasValueMap.value("相机key");
foreach(QString key, myPbGlobalObject.myParasValueMap.keys())
{
if (key == "相机key" || key == "type")
continue;
ui.tableWidget->setRowCount(ui.tableWidget->rowCount() + 1);
int rowNum = ui.tableWidget->rowCount();
QTableWidgetItem* m_Item0 = new QTableWidgetItem;
//m_Item0->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
m_Item0->setText(key);
ui.tableWidget->setItem(rowNum - 1, 0, m_Item0);
//QString nowTime = QDateTime::currentDateTime().toString("yyyy-MM-dd");
QTableWidgetItem* m_Item1 = new QTableWidgetItem;
//m_Item1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
m_Item1->setText(myPbGlobalObject.myParasValueMap.value(key));
ui.tableWidget->setItem(rowNum - 1, 1, m_Item1);
}
}
bool QtCameraDebug::refresh_myParasValueMap()
{
if (ifLoadPar == true)
return true;
QMap<QString, QString> myParasValueMap;
int rowcout = ui.tableWidget->rowCount();
for (int i = 0; i < rowcout; i++)
{
if (ui.tableWidget->item(i, 0)->text().isEmpty() || ui.tableWidget->item(i, 1)->text().isEmpty())
{
myBox->information(this, "相机参数错误", "相机参数名或参数值为空"); return false;
}
if (ui.tableWidget->item(i, 0)->text() == "相机key" && ui.tableWidget->item(i, 1)->text() == "输入SN")
{
myBox->information(this, "相机key参数错误", "未输入SN"); return false;
}
if (!ui.tableWidget->item(i, 0)->text().isEmpty() && !ui.tableWidget->item(i, 1)->text().isEmpty())
myParasValueMap.insert(ui.tableWidget->item(i, 0)->text(), ui.tableWidget->item(i, 1)->text());
}
myPbGlobalObject.myParasValueMap = myParasValueMap;
myPbGlobalObject.cameraKey = myParasValueMap.value("相机key");
return true;
}
QJsonObject QtCameraDebug::load_cameraList(QString cfgName)
{
QDir dir = QApplication::applicationDirPath();
QString currPath = dir.path();
json_cameraList_path = currPath + "/config/"+ cfgName;// +ui.comboBox->currentText();
QJsonObject json_object;
try
{
QJsonParseError jsonError;
if (json_cameraList_path.isEmpty())
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " JsonPath is null!";
return json_object;
}
QFile JsonFile;
JsonFile.setFileName(json_cameraList_path);
/*if (!JsonFile.isReadable())
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " camera_Example.json not isReadable!";
return json_object;
}*/
JsonFile.open(QIODevice::ReadOnly);
QByteArray m_Byte = JsonFile.readAll();
if (m_Byte.isEmpty())
{
qDebug() << __FUNCTION__ << " line:" << __LINE__ << json_cameraList_path + " Content is empty";
JsonFile.close();
return json_object;
}
QJsonDocument jsonDocument(QJsonDocument::fromJson(m_Byte, &jsonError));
if (!jsonDocument.isNull() && jsonError.error == QJsonParseError::NoError)
{
if (jsonDocument.isObject())
{
json_object = jsonDocument.object();
JsonFile.close();
return json_object;
}
}
else
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << json_cameraList_path + " is error!";
}
JsonFile.close();
}
catch (QString ev)
{
qCritical() << __FUNCTION__ << " line:" << __LINE__ << " ev:" << ev;
}
return json_object;
}
void QtCameraDebug::initCombox()
{
QDir dir = QApplication::applicationDirPath();
QString cfgPath = dir.path()+"/config";
QStringList imgFilters;
imgFilters << "*.json" ;
QDir qdir(cfgPath);
QStringList localSourceImgsName;
//返回文件名列表
localSourceImgsName = qdir.entryList(imgFilters, QDir::Files | QDir::Readable, QDir::Name);
ui.comboBox->clear();
for (int i = 0; i < localSourceImgsName.size(); i++)
ui.comboBox->addItem(localSourceImgsName[i]);
}
int QtCameraDebug::mathcCmaeraType(QString moduleName, QString triggerType)
{
type = -1;
if (moduleName.contains("HIK") && triggerType.contains("hard"))
type = HIK_Hard;
else if (moduleName.contains("HIK") && triggerType.contains("soft"))
type = HIK_Soft;
else if (moduleName.contains("Basler") && triggerType.contains("hard"))
type = Basler_Hard;
else if (moduleName.contains("Basler") && triggerType.contains("soft"))
type = Basler_Soft;
else if (moduleName.contains("DaHeng") && triggerType.contains("hard"))
type = DaHeng_Hard;
else if (moduleName.contains("DaHeng") && triggerType.contains("soft"))
type = DaHeng_Soft;
else if (moduleName.contains("DAHUA") && triggerType.contains("hard"))
type = DaHua_Hard;
else if (moduleName.contains("DAHUA") && triggerType.contains("soft"))
type = DaHua_Soft;
else if (moduleName.contains("ITEK") && triggerType.contains("hard"))
type = ITEK_Hard;
else if (moduleName.contains("ITEK") && triggerType.contains("soft"))
type = ITEK_Soft;
else if (moduleName.contains("OPT") && triggerType.contains("soft"))
type = OPT_Soft;
else if (moduleName.contains("DalsaDAQH") && triggerType.contains("hard"))
type = DalsaDAQ_Hard;
else if (moduleName.contains("DalsaDAQ") && triggerType.contains("soft"))
type = DalsaDAQ_Soft;
else if (moduleName.contains("Dalsa"))
type = Dalsa;
else if (moduleName.contains("Hd_CameraModule_3DKeyence"))
type = Keyence_3D;
else if (moduleName.contains("Hd_CameraModule_3DLMI"))
type = LMI_3D;
else if (moduleName.contains("Hd_CameraModule_3DSszn"))
type = Sszn_3D;
else if (moduleName.contains("Hd_25DCameraVJ_module"))
type = Keyence_25D;
else if (moduleName.contains("Hd_CameraModule_readImage"))
type = ReadImage;
return type;
}
bool QtCameraDebug::saveCfg()
{
QJsonObject newprogramObj;
QJsonArray newstationlist_array;
QJsonArray stationlist_array = cameraListObj.value("工站列表").toArray();
for (int i = 0; i < stationlist_array.size(); i++)
{
QJsonObject station_obj = stationlist_array.at(i).toObject();
QJsonArray cameramodulelist = station_obj.value("相机模块列表").toArray();
QJsonArray newcameramodulelist;
for (auto val = 0; val < cameramodulelist.size(); val++)
{
QJsonObject camera_obj = cameramodulelist.at(val).toObject();
//相机SN或usrID
QString camera_key = camera_obj.value("相机key").toString();
QString moduleName = camera_obj.value("模块名称").toString(); // 相机模块名
QJsonArray init_array = camera_obj.value("相机参数").toArray();
QString triggerType = camera_obj.value("触发方式").toString(); // 相机模块名
int type = mathcCmaeraType(moduleName, triggerType);
/* QMap<QString, QString> myParasValueMap;
myParasValueMap.insert("type", QString::number(type));
myParasValueMap.insert("相机key", camera_key);
myParasValueMap.insert("取图超时", camera_obj.value("取图超时").toString());*/
QJsonArray newinit_array;
QMap<QString, QString> myParasValueMap;
for (int p = 0; p < queue_MyPbGlobalObject.size(); p++)
if (queue_MyPbGlobalObject[p].myParasValueMap.value("相机key") == camera_key)
myParasValueMap = queue_MyPbGlobalObject[p].myParasValueMap;
for (int V = 0; V < init_array.size(); V++)
{
QJsonObject initCfg_obj = init_array.at(V).toObject();
QString valKey = initCfg_obj.value("参数名").toString();
QJsonArray cfg_array = initCfg_obj.value("相机参数值").toArray();
QString init_string;
for (int j = 0; j < cfg_array.size(); j++)
if (j > 0)
init_string += "," + cfg_array[j].toString();
else
init_string += cfg_array[j].toString();
QJsonArray newcfg_array;
QStringList newinit_string = myParasValueMap.value(valKey).split(",");
for (int s = 0; s < newinit_string.size(); s++)
newcfg_array.append(newinit_string[s]);
initCfg_obj.insert("相机参数值", newcfg_array);
newinit_array.append(initCfg_obj);
//myParasValueMap.insert(valKey, init_string);
}
camera_obj.insert("相机参数", newinit_array);
newcameramodulelist.append(camera_obj);
}
station_obj.insert("相机模块列表", newcameramodulelist);
newstationlist_array.append(station_obj);
}
cameraListObj.insert("工站列表", newstationlist_array);
newprogramObj = cameraListObj;
//内存中的数据写到文件
QJsonDocument doc(newprogramObj);
//将json对象转换成字符串
QByteArray data = doc.toJson();
QFile file(json_cameraList_path);
file.open(QIODevice::WriteOnly);
file.write(data);
file.close();
return true;
}
//存图加入队列
void QtCameraDebug::addImgToSaveStruct(cv::Mat img2D, QString mysaveKey, QString savePath)
{
//存图数据加保存队列,加锁,避免数据访问冲突
saveStruct_mutex->lock();
saveImgStruct mySave;
mySave.out_Mat = img2D.clone();
//img2D.copyTo(mySave.out_Mat);
mySave.saveKey = (mysaveKey).toStdString();
mySave.savePath = (savePath).toStdString();
saveStruct.enqueue(mySave);
if (saveStruct.size() > 100)
myBox->information(this, "警告", "存图队列>100,内存溢出风险");
saveStruct_mutex->unlock();
}
void QtCameraDebug::saveImgThread()
{
while (1)
{
if (!ifRun)return;
_sleep(1);
qApp->processEvents();
if (saveStruct.size() < 1)continue;
for (int i = 0; i < saveStruct.size(); i++)
{
clock_t start, stop;
start = clock();
saveStruct_mutex->lock();
saveImgStruct mysaveStruct = saveStruct.dequeue();
saveStruct_mutex->unlock();
stop = clock();
if (stop - start > 1000)
std::cout << "lock stop-start >1000::************************" << stop - start << std::endl;
start = clock();
if (mysaveStruct.out_Mat.data)imwrite(mysaveStruct.savePath, mysaveStruct.out_Mat);
//std::cout << "savePath::" << mysaveStruct.savePath << std::endl;
stop = clock();
if (stop - start > 1000)
std::cout << "imwrite stop-start >1000::--------------------------" << stop - start << std::endl;
_sleep(1);
}
}
}
void QtCameraDebug::showCameraList(QString cfgName)
{
index = 0;
ui.tableWidget->setRowCount(0);
ui.tableWidget->clear();
ui.tableWidget_2->setRowCount(0);
ui.tableWidget_2->clear();
//加载文件
cameraListObj = load_cameraList(cfgName);
//显示到界面
if (!cameraListObj.isEmpty())
{
ifSetBox = true;
QJsonArray stationlist_array = cameraListObj.value("工站列表").toArray();
for (int i = 0; i < stationlist_array.size(); i++)
{
QJsonObject station_obj = stationlist_array.at(i).toObject();
QJsonArray cameramodulelist = station_obj.value("相机模块列表").toArray();
for (auto val = 0; val < cameramodulelist.size(); val++)
{
QJsonObject camera_obj = cameramodulelist.at(val).toObject();
//相机SN或usrID
QString camera_key = camera_obj.value("相机key").toString();
QString moduleName = camera_obj.value("模块名称").toString(); // 相机模块名
QJsonArray init_array = camera_obj.value("相机参数").toArray();
QString triggerType = camera_obj.value("触发方式").toString(); // 相机模块名
int type = mathcCmaeraType(moduleName, triggerType);
QMap<QString, QString> myParasValueMap;
myParasValueMap.insert("type", QString::number(type));
myParasValueMap.insert("相机key", camera_key);
myParasValueMap.insert("取图超时", camera_obj.value("取图超时").toString());
for (int V = 0; V < init_array.size(); V++)
{
QJsonObject initCfg_obj = init_array.at(V).toObject();
QString valKey = initCfg_obj.value("参数名").toString();
QJsonArray cfg_array = initCfg_obj.value("相机参数值").toArray();
QString init_string;
for (int j = 0; j < cfg_array.size(); j++)
if (j > 0)
init_string += "," + cfg_array[j].toString();
else
init_string += cfg_array[j].toString();
myParasValueMap.insert(valKey, init_string);
}
MyPbGlobalObject readPbGlobalObject;
readPbGlobalObject.myParasValueMap = myParasValueMap;
queue_MyPbGlobalObject.enqueue(readPbGlobalObject);
if (type == HIK_Hard)
{
cameraTypeText = "2D:海康(面阵/线扫)";
ui.checkBox_hard->setChecked(true);
ui.checkBox_soft->setChecked(false);
}
else if (type == HIK_Soft)
{
cameraTypeText = "2D:海康(面阵/线扫)";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == Basler_Hard)
{
cameraTypeText = "2D:Basler(面阵/线扫)";
ui.checkBox_hard->setChecked(true);
ui.checkBox_soft->setChecked(false);
}
else if (type == Basler_Soft)
{
cameraTypeText = "2D:Basler(面阵/线扫)";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == DaHeng_Hard)
{
cameraTypeText = "2D:大恒(面阵)";
ui.checkBox_hard->setChecked(true);
ui.checkBox_soft->setChecked(false);
}
else if (type == DaHeng_Soft)
{
cameraTypeText = "2D:大恒(面阵)";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == DaHua_Hard)
{
cameraTypeText = "2D:大华(面阵)";
ui.checkBox_hard->setChecked(true);
ui.checkBox_soft->setChecked(false);
}
else if (type == DaHua_Soft)
{
cameraTypeText = "2D:大华(面阵)";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == ITEK_Hard)
{
cameraTypeText = "2D:埃科(线扫)";
ui.checkBox_hard->setChecked(true);
ui.checkBox_soft->setChecked(false);
}
else if (type == ITEK_Soft)
{
cameraTypeText = "2D:埃科(线扫)";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == OPT_Soft)
{
cameraTypeText = "2D:Opt(面阵)";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == Dalsa)
{
cameraTypeText = "2D:Dalsa(网口线扫)";
ui.checkBox_hard->setChecked(true);
ui.checkBox_soft->setChecked(false);
}
else if (type == DalsaDAQ_Hard)
{
cameraTypeText = "2D:Dalsa(采集卡线扫)";
ui.checkBox_hard->setChecked(true);
ui.checkBox_soft->setChecked(false);
}
else if (type == DalsaDAQ_Soft)
{
cameraTypeText = "2D:Dalsa(采集卡线扫)";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == Keyence_3D)
{
cameraTypeText = "3D:基恩士";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == LMI_3D)
{
cameraTypeText = "3D:LMI";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == Sszn_3D)
{
cameraTypeText = "3D:深视智能";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == Keyence_25D)
{
cameraTypeText = "2.5D:基恩士";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else if (type == ReadImage)
{
cameraTypeText = "离线:读图模块";
ui.checkBox_hard->setChecked(false);
ui.checkBox_soft->setChecked(true);
}
else
{
myBox->information(this, "失败", "匹配失败");
}
QString text = "相机" + QString::number(index++) + ": " + cameraTypeText;
if (ui.checkBox_hard->isChecked())
text += " 硬触发";
else if (ui.checkBox_soft->isChecked())
text += " 软触发";
ui.tableWidget_2->setRowCount(ui.tableWidget_2->rowCount() + 1);
int rowNum2 = ui.tableWidget_2->rowCount();
ui.tableWidget_2->setItem(rowNum2 - 1, 0, new QTableWidgetItem(text));
}
}
ifSetBox = false;
}
}
void QtCameraDebug::closeEvent(QCloseEvent*)
{
ui.pushButton_closeModel->click();
Sleep(10);
emit QtCameraDebug_done();
}
#define MOUSE_MARGIN 2
//计算鼠标位置
QtCameraDebug::MousePoss QtCameraDebug::calcmouseposs(QPoint p)
{
QtCameraDebug::MousePoss mp;
if (p.x() < MOUSE_MARGIN && p.y() < MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::LeftUp; //左上
else if (p.x() > MOUSE_MARGIN && p.y() < MOUSE_MARGIN && p.x() < this->width() - MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::Up; //上
else if (p.x() > this->width() - MOUSE_MARGIN && p.y() < MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::RightUp; //右上
else if (p.x() > this->width() - MOUSE_MARGIN && p.y() > MOUSE_MARGIN && p.y() < this->height() - MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::Right; //右
else if (p.x() > this->width() - MOUSE_MARGIN && p.y() > this->height() - MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::RightDown; //右下
else if (p.x() > MOUSE_MARGIN && p.x() < this->width() - MOUSE_MARGIN && p.y() > this->height() - MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::Down; //下
else if (p.x() < MOUSE_MARGIN && p.y() > this->height() - MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::LeftDown; //左下
else if (p.x() < MOUSE_MARGIN && p.y() < this->height() - MOUSE_MARGIN && p.y() > MOUSE_MARGIN)
mp = QtCameraDebug::MousePoss::Left; //左
else
mp = QtCameraDebug::MousePoss::Middle; //中间
return mp;
}
//修改鼠标样式
void QtCameraDebug::setCursorType(QtCameraDebug::MousePoss type)
{
Qt::CursorShape cursor;
switch (type)
{
case QtCameraDebug::MousePoss::LeftUp:
case QtCameraDebug::MousePoss::RightDown:
cursor = Qt::SizeFDiagCursor;
break;
case QtCameraDebug::MousePoss::Up:
case QtCameraDebug::MousePoss::Down:
cursor = Qt::SizeVerCursor;
break;
case QtCameraDebug::MousePoss::RightUp:
case QtCameraDebug::MousePoss::LeftDown:
cursor = Qt::SizeBDiagCursor;
break;
case QtCameraDebug::MousePoss::Right:
case QtCameraDebug::MousePoss::Left:
cursor = Qt::SizeHorCursor;
break;
default:
cursor = Qt::ArrowCursor;
break;
}
setCursor(cursor);
}
//改变窗口的大小
void QtCameraDebug::changeWindowSize(QtCameraDebug::MousePoss type, QRect& wid, QPoint ptemp, int minWidth, int minHeight)
{
switch (type)//改变窗口的大小
{
case QtCameraDebug::MousePoss::LeftUp:
{
QPoint pos = wid.topLeft();
if (wid.width() > minWidth || ptemp.x() < 0)
pos.rx() = pos.rx() + ptemp.x();
if (wid.height() > minHeight || ptemp.y() < 0)
pos.ry() = pos.ry() + ptemp.y();
wid.setTopLeft(pos);
break;//左上角
}
case QtCameraDebug::MousePoss::RightUp:
{
QPoint pos = wid.topRight();
if (wid.width() > minWidth || ptemp.x() > 0)
pos.rx() = pos.rx() + ptemp.x();
if (wid.height() > minHeight || ptemp.y() < 0)
pos.ry() = pos.ry() + ptemp.y();
wid.setTopRight(pos);
break;//右上角
}
case QtCameraDebug::MousePoss::LeftDown:
{
QPoint pos = wid.bottomLeft();
if (wid.width() > minWidth || ptemp.x() < 0)
pos.rx() = pos.rx() + ptemp.x();
if (wid.height() > minHeight || ptemp.y() > 0)
pos.ry() = pos.ry() + ptemp.y();
wid.setBottomLeft(pos);
break;//左下角
}
case QtCameraDebug::MousePoss::RightDown:
{
QPoint pos = wid.bottomRight();
if (wid.width() > minWidth || ptemp.x() > 0)
pos.rx() = pos.rx() + ptemp.x();
if (wid.height() > minHeight || ptemp.y() > 0)
pos.ry() = pos.ry() + ptemp.y();
wid.setBottomRight(pos);
break;//右下角
}
case QtCameraDebug::MousePoss::Up:
{
int topY = wid.top();
if (wid.height() > minHeight || ptemp.y() < 0)
topY = topY + ptemp.y();
wid.setTop(topY);
break;//上
}
case QtCameraDebug::MousePoss::Left:
{
int leftX = wid.left();
if (wid.width() > minWidth || ptemp.x() < 0)
leftX = leftX + ptemp.x();
wid.setLeft(leftX);
break;//左
}
case QtCameraDebug::MousePoss::Right:
{
int rightX = wid.right();
if (wid.width() > minWidth || ptemp.x() > 0)
rightX = rightX + ptemp.x();
wid.setRight(rightX);
break;//右
}
case QtCameraDebug::MousePoss::Down:
{
int botY = wid.bottom();
if (wid.height() > minHeight || ptemp.y() > 0)
botY = botY + ptemp.y();
wid.setBottom(botY);
break;//下
}
default:
break;
}
}
//三个鼠标事件的重写
void QtCameraDebug::mousePressEvent(QMouseEvent* e)
{
if (e->button() == Qt::LeftButton) //鼠标左键按下
{
m_lastPos = e->globalPos();
e->ignore();
}
}
//鼠标移动
void QtCameraDebug::mouseMoveEvent(QMouseEvent* e)
{
//最大化状态,鼠标是否在标题栏,拖拽还原
if (this->isMaximized())
{
if (ui.title->geometry().contains(this->mapFromGlobal(QCursor::pos())) && e->buttons() == Qt::LeftButton)
{
QPoint ptemp = e->globalPos();
if (ptemp != m_lastPos)
{
this->showNormal();
}
}
}
QtCameraDebug::MousePoss curPos = calcmouseposs(e->pos());
if (!e->buttons())
{
setCursorType(curPos);
mp_curPos = curPos;
}
if (e->buttons() == Qt::LeftButton) //坐标左键按下并移动
{
QPoint ptemp = e->globalPos();
ptemp = ptemp - m_lastPos; //鼠标移动的偏移量
if (mp_curPos == QtCameraDebug::MousePoss::Middle && ui.title->geometry().contains(this->mapFromGlobal(QCursor::pos()))
&& !ui.pushButton_max->geometry().contains(this->mapFromGlobal(QCursor::pos()))
&& !ui.pushButton_min->geometry().contains(this->mapFromGlobal(QCursor::pos()))
&& !ui.pushButton_close->geometry().contains(this->mapFromGlobal(QCursor::pos())))
{
move(ptemp + pos());
}
else
{
QRect wid = geometry();
int minWidth = this->minimumWidth();
int minHeight = this->minimumHeight();
if (ptemp.x() < 50 && ptemp.x() > -50)
{
changeWindowSize(mp_curPos, wid, ptemp, minWidth, minHeight);
//更新大小
setGeometry(wid);
}
}
m_lastPos = e->globalPos();
}
e->ignore();
}
//鼠标释放
void QtCameraDebug::mouseReleaseEvent(QMouseEvent* e)
{
if (e->button() == Qt::LeftButton && ui.title->geometry().contains(this->mapFromGlobal(QCursor::pos()))
&& !ui.pushButton_max->geometry().contains(this->mapFromGlobal(QCursor::pos()))
&& !ui.pushButton_min->geometry().contains(this->mapFromGlobal(QCursor::pos()))
&& !ui.pushButton_close->geometry().contains(this->mapFromGlobal(QCursor::pos()))) //鼠标左键释放
{
int dx = e->globalX() - m_lastPos.x();
int dy = e->globalY() - m_lastPos.y();
move(x() + dx, y() + dy);
}
QApplication::restoreOverrideCursor();//恢复鼠标指针性状
e->ignore();
}