| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909 |
- /*!
- \author Igor Mironchik (igor dot mironchik at gmail dot com).
- MIT License
- Copyright (c) 2022 Igor Mironchik
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE.
- */
- #include "cameramanager.h"
- // Qt include.
- #include <QQmlEngine>
- #include <QCameraDevice>
- #include <QThreadPool>
- #include <QTimer>
- #include <QDateTime>
- #include <QDebug>
- #include <QtConcurrent/QtConcurrent>
- #include <m_workthread.h>
- #include <mserial.h>
- #include <curl/curl.h>
- #include <main.h>
- #include <m_loger.h>
- #include <QMessageBox>
- // #include "im2d.hpp"
- // #include "im2d_common.h"
- // #include "RgaUtils.h"
- class param;
- namespace Qt6QCamera {
- //< hikrobot
- void *handle = NULL;
- unsigned int nRet = MV_OK;
- MVCC_ENUMVALUE current_pixel;
- SenderCustom sender_custom;
- cv::Mat cv_frame;
- FPSTimer::FPSTimer(QObject *parent) : QObject(parent)
- {
- m_timer = new QTimer(this);
- m_elapsed_timer = new QElapsedTimer();
- m_timer->setInterval(m_interval);
- connect(m_timer, &QTimer::timeout,
- this, &FPSTimer::onTimerTimeout);
- }
- void FPSTimer::onTimerTimeout()
- {
- double seconds_elapsed = static_cast<double>(m_elapsed_timer->nsecsElapsed()) / 1000000000.0;
- m_elapsed_timer->start();
- double fps = static_cast<double>(m_frame_count) /seconds_elapsed;
- emit fpsUpdated(fps);
- m_frame_count = 0;
- }
- void FPSTimer::setInterval(int interval)
- {
- m_interval = interval;
- m_timer->setInterval(interval);
- }
- void FPSTimer::setRunning(bool running)
- {
- if(running) {
- m_timer->start(m_interval);
- m_elapsed_timer->start();
- }
- else {
- m_timer->stop();
- m_elapsed_timer->invalidate();
- emit fpsUpdated(0.0);
- }
- }
- bool FPSTimer::isRunning()
- {
- return m_timer->isActive();
- }
- //
- // Frames
- //
- Frames::Frames(QObject * parent)
- : //QVideoSink(parent),
- QObject(parent),
- m_decoding(false),
- m_fps( 0 ),
- m_1s( new QTimer( this ) )
- {
- QMetaType id = QMetaType::fromName("cv::Mat");
- if(id.flags() == QMetaType::UnknownType) {
- qRegisterMetaType<cv::Mat>("cv::Mat");
- }
- stitch_des = 0;
- connect( m_1s, &QTimer::timeout, this, &Frames::timer);
- m_1s->setInterval( 500 ); //1000
- m_1s->stop();
- m_fps_timer = new FPSTimer(this);
- connect(m_fps_timer, &FPSTimer::fpsUpdated,
- this, &Frames::onFPSUpdated);
- connect(this,&Frames::startGrabbing,
- this,&Frames::handleGrab);
- // connect(this,&Frames::uvcframeAvailable,
- // this,&Frames::parseFrame);
- connect(this,&Frames::frameAvailable,
- this,&Frames::displayFrame);
- connect(this,&Frames::stopGrabbing,
- this,&Frames::setCameraSw);
- connect(this,&Frames::signal_photo_saved,
- this,&Frames::upload_handle);
- initCam();
- }
- Frames::~Frames()
- {
- qDebug() << "=== Frames Destructor Start ===";
- // 1. 先停止所有定时器
- if (m_1s && m_1s->isActive()) {
- m_1s->stop();
- }
- if (m_fps_timer && m_fps_timer->isRunning()) {
- m_fps_timer->setRunning(false);
- }
- // 2. 设置停止标志,确保相机不再运行
- camera_sta = false;
- if (handle)
- {
- // 先停止抓图
- if (MV_CC_StopGrabbing(handle) != MV_OK) {
- qDebug() << "Warning: Failed to stop grabbing";
- }
- // 等待抓图线程结束
- if (m_grabThread.isRunning()) {
- m_grabThread.cancel(); // 先尝试取消
- m_grabThread.waitForFinished();
- }
- // 关闭设备
- if (MV_CC_CloseDevice(handle) != MV_OK) {
- qDebug() << "Warning: Failed to close device";
- }
- MV_CC_DestroyHandle(handle);
- handle = NULL;
- }
- // 清理JNI资源
- if (jClass) {
- delete jClass;
- jClass = nullptr;
- }
- if (m_1s) {
- delete m_1s;
- m_1s = nullptr;
- }
- if (m_fps_timer) {
- delete m_fps_timer;
- m_fps_timer = nullptr;
- }
- if(m_videoSink)
- {
- delete m_videoSink;
- m_videoSink = nullptr;
- }
- qDebug() << "=== Frames Destructor End ===";
- }
- void
- Frames::setVideoSink( QVideoSink * newVideoSink )
- {
- qDebug() << "setVideoSink:"<<newVideoSink;
- if( m_videoSink == newVideoSink )
- {
- qDebug() << "m_videoSink == newVideoSink";
- return;
- }
- m_videoSink = newVideoSink;
- emit videoSinkChanged();
- }
- void
- Frames::setChange(bool stat_t)
- {
- LOG("开始自动对焦,发送指令到控制板,{}!",stat_t);
- if(stat_t){
- emit serial_data(m_json.Autofocus());
- }
- }
- void
- Frames::setCameraSw(bool stat_cam)
- {
- unsigned int nIP[4] = {192,168,100,100};
- unsigned int nMask[4] = {255,255,255,0};
- unsigned int nGateway[4] = {192,168,100,1};
- unsigned int nIpAddr = 0, nNetWorkMask = 0, nDefaultGateway = 0;
- z_step = 0;
- x_step = 0;
- auto qtContext = QJniObject(QNativeInterface::QAndroidApplication::context());
- jboolean javaState = stat_cam ? JNI_TRUE :JNI_FALSE;
- param::camera_tc = 0;
- stitch_des = 0;
- camera_sta = stat_cam;
- if(camera_sta && m_streaming_active) return; //如果已经是打开状态,退出
- MVCC_FLOATVALUE stExposureTime = {0};
- static int fd = 0;
- if(camera_sta){
- if(param::camera_type.contains("hikrobot"))
- {
- int ret = testJNI();
- LOG("testJNI ret:{}",ret);
- #if 0
- if(qtContext.isValid()&&jClass->isValid()){
- jClass->callMethod<void>("EnumDevice","(Landroid/content/Context;)V",qtContext.object());
- jClass->callMethod<void>("openDevice","(Landroid/content/Context;)V",qtContext.object());
- }
- #else
- if (handle)
- {
- MV_CC_StopGrabbing(handle);
- MV_CC_CloseDevice(handle);
- MV_CC_DestroyHandle(handle);
- handle = NULL;
- }
- unsigned int nIndex = 0;
- MV_CC_DEVICE_INFO_LIST stDeviceList;
- memset(&stDeviceList, 0, sizeof(MV_CC_DEVICE_INFO_LIST));
- // 枚举设备
- nRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &stDeviceList);
- if (MV_OK != nRet)
- {
- emit cameraOpenFailed("MV_CC_EnumDevices fail!");
- ERROR("MV_CC_EnumDevices fail! {:x}",nRet);
- return ;
- }
- else
- {
- LOG("MV_CC_EnumDevices Success!");
- }
- if (stDeviceList.nDeviceNum > 0)
- {
- for (int i = 0; i < (int)stDeviceList.nDeviceNum; i++)
- {
- LOG("[device {}]:", i);
- MV_CC_DEVICE_INFO *pDeviceInfo = stDeviceList.pDeviceInfo[i];
- if (NULL == pDeviceInfo)
- {
- emit cameraOpenFailed("pDeviceInfo is NULL!");
- ERROR("pDeviceInfo is NULL!");
- return;
- }
- //PrintDeviceInfo(pDeviceInfo);
- }
- }else{
- emit cameraOpenFailed("Find No Devices!");
- ERROR("Find No Devices!");
- // break;
- return;
- }
- ConvertToHexIp(&nIpAddr,nIP);
- ConvertToHexIp(&nNetWorkMask,nMask);
- ConvertToHexIp(&nDefaultGateway,nGateway);
- // 选择设备并创建句柄
- // select device and create handle
- nRet = MV_CC_CreateHandle(&handle, stDeviceList.pDeviceInfo[nIndex]);
- if (MV_OK != nRet)
- {
- emit cameraOpenFailed("MV_CC_CreateHandle fail!");
- ERROR("MV_CC_CreateHandle fail! {:x}",nRet);
- return ;
- }else{
- LOG("MV_CC_CreateHandle Success!");
- }
- //判断设备Ip是否可达
- bool bAccessible = MV_CC_IsDeviceAccessible(stDeviceList.pDeviceInfo[nIndex],MV_ACCESS_Exclusive);
- if(bAccessible){
- //ch:设置IP配置选项 | en:set IP config
- nRet = MV_GIGE_SetIpConfig(handle,MV_IP_CFG_STATIC);
- if(MV_OK != nRet){
- ERROR("MV_GIGE_SetIpConfig failed:{:x}",nRet);
- }
- nRet = MV_GIGE_ForceIpEx(handle,nIpAddr,nNetWorkMask,nDefaultGateway);
- if(MV_OK!=nRet){
- ERROR("MV_GIGE_ForceIpEx failed:{:x}",nRet);
- }
- }else{
- nRet = MV_GIGE_ForceIpEx(handle,nIpAddr,nNetWorkMask,nDefaultGateway);
- if(MV_OK!=nRet){
- ERROR("MV_GIGE_ForceIpEx failed:{:x}",nRet);
- }else{
- LOG("MV_GIGE_ForceIpEx Success!");
- }
- if (handle)
- {
- MV_CC_DestroyHandle(handle);
- handle = NULL;
- }
- MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &stDeviceList);
- if (stDeviceList.nDeviceNum > 0)
- {
- for (int i = 0; i < (int)stDeviceList.nDeviceNum; i++)
- {
- LOG("[device {}]:", i);
- MV_CC_DEVICE_INFO *pDeviceInfo = stDeviceList.pDeviceInfo[i];
- if (NULL == pDeviceInfo)
- {
- emit cameraOpenFailed("pDeviceInfo is NULL!");
- qDebug() << "pDeviceInfo is NULL!";
- return;
- }
- }
- }else{
- emit cameraOpenFailed("Find No Devices!");
- WARN("Find No Devices!");
- return;
- }
- MV_CC_CreateHandle(&handle, stDeviceList.pDeviceInfo[nIndex]);
- }
- nRet = MV_CC_OpenDevice(handle);
- if (MV_OK != nRet)
- {
- emit cameraOpenFailed("MV_CC_OpenDevice fail!");
- MV_CC_DestroyHandle(handle);
- handle = NULL;
- ERROR("MV_CC_OpenDevice fail! {:x}",nRet);
- camera_sta = false;
- return;
- }else{
- LOG("MV_CC_OpenDevice Success!");
- }
- // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
- if (stDeviceList.pDeviceInfo[nIndex]->nTLayerType == MV_GIGE_DEVICE)
- {
- int nPacketSize = MV_CC_GetOptimalPacketSize(handle);
- if (nPacketSize > 0)
- {
- nRet = MV_CC_SetIntValue(handle,"GevSCPSPacketSize",nPacketSize);
- if(nRet != MV_OK)
- {
- ERROR("Warning: Set Packet Size fail nRet:{:x}",nRet);
- }
- }
- else
- {
- WARN("Warning: Get Packet Size fail nRet:{}",nPacketSize);
- }
- LOG("stDeviceList.pDeviceInfo[nIndex]->nTLayerType:{}",stDeviceList.pDeviceInfo[nIndex]->nTLayerType);
- }
- // ch:设置触发模式为off | eb:Set trigger mode as off
- nRet = MV_CC_SetEnumValue(handle, "TriggerMode", MV_TRIGGER_MODE_OFF);
- if (MV_OK != nRet)
- {
- ERROR("Set Trigger Mode fail! {:x}",nRet);
- return;
- }
- #if 0
- //注册抓图回调
- nRet = MV_CC_RegisterImageCallBackEx(handle,ImageCallBackEx,this);
- if (MV_OK != nRet)
- {
- unsigned int unsignedValue = static_cast<unsigned int>(nRet);
- qDebug() << "MV_CC_RegisterImageCallBackEx fail! nRet" << QString::number(unsignedValue, 16).toUpper();
- return ;
- }else{
- qDebug() << "MV_CC_RegisterImageCallBackEx Success!";
- }
- #endif
- MVCC_INTVALUE_EX width,height;
- nRet = MV_CC_GetIntValueEx(handle, "Width", &width);
- if(nRet==MV_OK){
- LOG("[MV_CC_GetIntValueEx Width]:{}",width.nCurValue);
- }else{
- ERROR("[MV_CC_GetIntValueEx Width]:{:x}",nRet);
- }
- nRet = MV_CC_GetIntValueEx(handle, "Height", &height);
- if(nRet==MV_OK){
- LOG("[MV_CC_GetIntValueEx Height]:{}",height.nCurValue);
- }else{
- ERROR("[MV_CC_GetIntValueEx Height]:{:x}",nRet);
- }
- //获取像素格式
- nRet = MV_CC_GetPixelFormat(handle,¤t_pixel);
- if(nRet==MV_OK){
- LOG("MV_CC_GetPixelFormat:{}",current_pixel.nCurValue);
- }else{
- ERROR("[MV_CC_GetPixelFormat Failed]:{:x}",nRet);
- }
- nRet = MV_CC_GetFloatValue(handle, "ExposureTime", &stExposureTime);
- if (MV_OK == nRet)
- {
- m_fExposureTime = QString::number(stExposureTime.fCurValue);
- emit exposureTimeChanged();
- LOG("exposure time current value:{}",stExposureTime.fCurValue);
- }
- else
- {
- ERROR("get exposure time failed! nRet [{:X}]", nRet);
- }
- // 开始取流
- // start grab image
- nRet = MV_CC_StartGrabbing(handle);
- if (MV_OK != nRet)
- {
- emit cameraOpenFailed("MV_CC_StartGrabbing fail!");
- camera_sta = false;
- ERROR("[MV_CC_StartGrabbing Failed]:{:x}",nRet);
- return ;
- }else{
- //创建归档路径
- QDateTime currentDateTime = QDateTime::currentDateTime();
- QString currentDateTimeString = currentDateTime.toString("yyyyMMddhhmmss");
- QString standPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)+ "/Pictures";
- //创建年目录
- QString YeayPath = standPath + "/" + currentDateTime.toString("yyyy");
- //createFolder(YeayPath);
- //创建月目录
- QString MonthPath = standPath + "/" + currentDateTime.toString("MM");
- //createFolder(YeayPath);
- //创建日目录
- QString DayPath = standPath + "/" + currentDateTime.toString("dd");
- //createFolder(DayPath);
- //创建图片归档目录
- picture_path_floader = standPath + "/" +
- currentDateTime.toString("yyyy") + "/" +
- currentDateTime.toString("MM") + "/" +
- currentDateTime.toString("dd") + "/" +
- currentDateTimeString;
- createFolder(picture_path_floader);
- m_fps_timer->setRunning(true);
- m_1s->start();
- m_streaming_active = true;
- emit startGrabbing(true);
- }
- #endif
- }
- }else{ //关闭相机
- if(param::camera_type.contains("qcamera")){
- }else if(param::camera_type.contains("uvc")){
- #if 1
- if(qtContext.isValid()&&jClass->isValid()){
- jClass->callMethod<void>("SetCamera_State","(Landroid/content/Context;Z)V",qtContext.object(),javaState);
- }
- #endif
- }else if(param::camera_type.contains("hikrobot")){
- nRet = MV_CC_StopGrabbing(handle);
- if (MV_OK != nRet)
- {
- ERROR("[MV_CC_StopGrabbing Failed]:{:x}",nRet);
- }
- #if 0
- // ch:注销抓图回调 | en:Unregister image callback
- nRet = MV_CC_RegisterImageCallBackEx(handle, NULL, NULL);
- if (MV_OK != nRet)
- {
- unsigned int unsignedValue = static_cast<unsigned int>(nRet);
- qDebug() << "MV_CC_RegisterImageCallBackEx fail! nRet:" << QString::number(unsignedValue, 16).toUpper();
- }
- #endif
- // close device
- nRet = MV_CC_CloseDevice(handle);
- if (MV_OK != nRet)
- {
- ERROR("[MV_CC_CloseDevice Failed]:{:x}",nRet);
- }
- // 销毁句柄
- // destroy handle
- if(handle){
- nRet = MV_CC_DestroyHandle(handle);
- if (MV_OK != nRet)
- {
- ERROR("[MV_CC_DestroyHandle Failed]:{:x}",nRet);
- }
- }
- }
- m_fps_timer->setRunning(false);
- m_1s->stop(); //视频信息发送定时器停止
- m_streaming_active = false;
- }
- LOG("设置相机状态:{}",camera_sta);
- emit cameraStaChanged(camera_sta); //同步状态到qml
- emit serial_data(m_json.setLedState(camera_sta)); //设置补光灯状态
- if(!param::ptlist.empty())
- {
- //emit signal_photo_saved();
- //开始景深融合
- }
- }
- void
- Frames::setExposureTime(const QString &exptime)
- {
- bool ok = false;
- float exposure_time = exptime.toFloat(&ok);
- if(handle&&ok){
- //关闭自动曝光
- nRet = MV_CC_SetExposureAutoMode(handle,MV_EXPOSURE_AUTO_MODE_OFF);
- if(nRet==MV_OK){
- LOG("MV_CC_SetExposureAutoMode OFF Success");
- }else{
- ERROR("MV_CC_SetExposureAutoMode OFF Failed");
- }
- nRet = MV_CC_SetExposureTime(handle,exposure_time);
- if(nRet==MV_OK){
- LOG("MV_CC_SetExposureTime Success");
- m_fExposureTime = exptime;
- }else{
- ERROR("MV_CC_SetExposureTime Failed");
- }
- //大部分参数修改完成后,调用此命令进行保存,不建议频繁调用
- nRet = MV_CC_SetCommandValue(handle,"UserSetSave");
- if (MV_OK != nRet)
- {
- ERROR("MV_CC_SetCommandValue UserSetSave fail! nRet [{:x}]", nRet);
- }else{
- LOG("save successful!");
- }
- }
- emit exposureTimeChanged();
- }
- void
- Frames::upload_handle()
- {
- if(!param::ptlist.empty()){
- emit signal_wait_upload(param::ptlist.first());
- param::ptlist.removeFirst();
- }
- }
- void
- Frames::handle_reult_upload(bool success, const QString &error)
- {
- if(success)
- {
- LOG("上传成功:{}",error.toStdString());
- //匹配数据库进行删除
- }else
- {
- WARN("上传失败:{}",error.toStdString());
- }
- upload_handle();
- }
- void
- Frames::saveMatAsJpeg(const QVideoFrame &frame){
- QString ts = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
- if (frame.isValid()) {
- QString name = picture_path_floader + "/" + ts +
- "z" + QString::number(z_step) +
- "x" + QString::number(x_step) + ".jpg";
- QString name_sharp = picture_path_floader + "/" + ts +
- "z" + QString::number(z_step) +
- "x" + QString::number(x_step) + "_sharp.jpg";
- if (frame.toImage().save(name,"jpg",100)) {
- //param::ptlist.append(name);
- LOG("[saveMatAsJpeg] saved:{}",name.toStdString());
- #if 1
- emit stopGrabbing(false);
- //图像锐化
- Mat image = imread(name.toStdString());
- cv::Mat fused_sharp = m_opencvfunc.unsharpMask(image, 2.0, 3.0);
- //对比度
- cv::Mat Contrast_Image = m_opencvfunc.enhanceContrast(fused_sharp,0);
- std::vector<int> params = {cv::IMWRITE_PNG_COMPRESSION, 3};
- if (!cv::imwrite(name_sharp.toStdString(), Contrast_Image, params)) {
- ERROR("Failed to save fused image:{}",name_sharp.toStdString());
- }else{
- param::ptlist.append(name_sharp);
- emit signal_photo_saved();
- }
- #else
- param::ptlist.append(name);
- emit stopGrabbing(false);
- #endif
- } else {
- WARN("[saveMatAsJpeg] write failed:{}",name.toStdString());
- }
- }else{
- ERROR("[saveMatAsJpeg] empty image!");
- }
- }
- void
- Frames::processFrameAsync(const RawFrame& frame){
- //QtConcurrent::run([=]() {
- cv::Mat raw;
- switch (frame.pixelType) {
- case PixelType_Gvsp_BayerRG8:
- raw = cv::Mat(frame.height, frame.width, CV_8UC1,
- (void*)frame.data.constData());
- cv::cvtColor(raw, m_frame, cv::COLOR_BayerRG2BGRA);
- break;
- case PixelType_Gvsp_BayerGR8:
- raw = cv::Mat(frame.height, frame.width, CV_8UC1,
- (void*)frame.data.constData());
- cv::cvtColor(raw, m_frame, cv::COLOR_BayerGR2BGRA);
- break;
- case PixelType_Gvsp_BayerBG8:
- raw = cv::Mat(frame.height, frame.width, CV_8UC1,
- (void*)frame.data.constData());
- cv::cvtColor(raw, m_frame, cv::COLOR_BayerBG2BGRA);
- break;
- case PixelType_Gvsp_YUV422_YUYV_Packed:
- raw = cv::Mat(frame.height, frame.width, CV_8UC2,
- (void*)frame.data.constData());
- cv::cvtColor(raw, m_frame, cv::COLOR_YUV2RGBA_YUYV);
- break;
- default:
- return;
- }
- QVideoFrameFormat vfmt(
- QSize(m_frame.cols, m_frame.rows),
- QVideoFrameFormat::Format_RGBA8888
- );
- QVideoFrame vf(vfmt);
- if (!vf.map(QVideoFrame::WriteOnly))
- return;
- memcpy(vf.bits(0), m_frame.data,
- m_frame.total() * m_frame.elemSize());
- vf.unmap();
- // ✅ 投递回 UI 线程
- QMetaObject::invokeMethod(m_videoSink, [this, vf]() {
- if (m_videoSink) {
- m_videoSink->setVideoFrame(vf);
- }
- }, Qt::QueuedConnection);
- int tc = param::camera_tc;
- if(tc==1||tc==100){
- QVideoFrame snapshot = vf;
- QtConcurrent::run([=](){
- saveMatAsJpeg(snapshot);
- });
- param::camera_tc = 0; // 保存后立即重置,确保只保存一张
- if (tc == 100) {
- emit stopGrabbing(false);
- return;
- }
- }
- //});
- }
- void
- Frames::handleGrab(bool sta_cam){
- if (m_grabThread.isRunning()) return;
- if(m_grabThread.isFinished()){
- m_grabThread = QtConcurrent::run([=]() {
- // ch:获取数据包大小 | en:Get payload size
- MVCC_INTVALUE_EX stParam;
- memset(&stParam, 0, sizeof(MVCC_INTVALUE_EX));
- // cout << pUser << endl;
- if(sta_cam){
- nRet = MV_CC_GetIntValueEx(handle, "PayloadSize", &stParam);
- if (MV_OK != nRet)
- {
- ERROR("[MV_CC_GetIntValueEx Failed]:{:x}",nRet);
- return;
- }
- }
- if(!handle) return;
- const uint32_t payload = stParam.nCurValue;
- LOG("payload size:{}",payload);
- MV_FRAME_OUT stImageInfo = {0};
- bool flag_cam = sta_cam;
- std::vector<unsigned char> rgbBuf;
- while(flag_cam){
- nRet = MV_CC_GetImageBuffer(handle, &stImageInfo, 10000);
- if (nRet != MV_OK) {
- ERROR("GetOneFrameTimeout:{:x}",nRet);
- emit stopGrabbing(false);
- break;
- }
- RawFrame frame;
- frame.width = stImageInfo.stFrameInfo.nWidth;
- frame.height = stImageInfo.stFrameInfo.nHeight;
- frame.pixelType = stImageInfo.stFrameInfo.enPixelType;
- m_width = frame.width;
- m_height = frame.height;
- const int dataSize = stImageInfo.stFrameInfo.nFrameLen;
- frame.data = QByteArray(
- (const char*)stImageInfo.pBufAddr,
- dataSize
- );
- MV_CC_FreeImageBuffer(handle, &stImageInfo);
- // ✅ 像素处理放到新的 QFuture
- processFrameAsync(frame);
- // ----- FPS -----
- m_fps_timer->incrementFrame();
- #if 1
- if (param::camera_tc == -1) {
- emit stopGrabbing(false);
- flag_cam = false;
- break;
- }
- #endif
- }
- });
- }
- }
- QString
- Frames::cam_ExposureTime() const
- {
- return m_fExposureTime;
- }
- void
- Frames::registerQmlType()
- {
- qmlRegisterType< Qt6QCamera::Frames > ( "Frames", 0, 1, "Frames" );
- }
- int
- Frames::testJNI(){
- return QJniObject::callStaticMethod<jint>("GetUsbPermission",
- "testfunc",
- "()I");
- }
- void
- Frames::initCam()
- {
- int ret = testJNI();
- LOG("initCam:{}",ret);
- }
- QString
- Frames::formatString() const
- {
- return m_formatString;
- }
- QString
- Frames::fpsString() const
- {
- return m_fpsString;
- }
- QString
- Frames::qulityString() const
- {
- return m_qulityString;
- }
- bool
- Frames:: auto_clicked() const
- {
- return true;
- }
- bool
- Frames:: camera_sw() const
- {
- return camera_sta;
- }
- void
- Frames::onFPSUpdated(double fps){
- m_fpsString = QString( "%1x%2 at %3 %4 %5" ).arg(QString::number(m_width),
- QString::number(m_height),
- QString::number(param::ptlist.size()),
- QString::number(fps,'f',2) + " (FPS) ",
- cam_ExposureTime());
- emit fpsStringChanged();
- }
- void
- Frames::timer()
- {
- if(param::camera_tc == 10){
- emit signal_stitch();
- setCameraSw(false);
- }
- #ifdef focus_board
- emit serial_data(m_json.ImageFunc(m_qulityString.toDouble()));
- #endif
- }
- void
- Frames::update_qulstr(QString q_str)
- {
- LOG("update_qulstr:{}",q_str.toStdString());
- m_qulityString = q_str;
- emit qulityStringChanged();
- }
- void
- Frames::saveImage()
- {
- //停止清晰度发送,关闭定时器m1s
- LOG("saveImage start!");
- //灰度值检测,全黑则不再往下进行,上报预警消息
- if(m_frame.empty()) return;
- //QtConcurrent::run([=](){
- Mat image_gray;
- cv::cvtColor(m_frame,image_gray,cv::COLOR_RGBA2GRAY);
- double grayvalue = cv::mean(image_gray)[0];
- m_qulityString = m_opencvfunc.Tenengrad(m_frame);
- emit serial_data(m_json.ImageFunc(m_qulityString.toDouble()));
- emit qulityStringChanged();
- LOG("image_gray:{}",grayvalue);
- LOG("Tenengrad:{}",m_qulityString.toStdString());
- if(grayvalue<5.0){
- emit dataUpload(m_json.MakeJsonWarn("Photo ERROR",QString::number(grayvalue)));
- setCameraSw(false); //关闭相机
- emit signal_photoerr();
- return;
- }
- //});
- }
- void Frames::displayFrame(const QVideoFrame &frame)
- {
- if(m_videoSink){
- m_videoSink->setVideoFrame(frame);
- }else{
- ERROR("m_videoSink Error!");
- }
- }
- //*使用capture捕获照片*/
- void
- Frames::captureImage(){
- setCameraSw(true);
- // 延时10S后触发拍照
- QTimer::singleShot(10000, [](){
- LOG("立即拍照!");
- param::camera_tc = 100;
- //创建文件夹
- });
- }
- } /* namespace Qt6QCamera */
|