Qt调用海康相机实时显示

一、配置环境变量

这一步真的是翻烂了CSDN最终还是通过下载一位大佬的原码最终解决了,马上分享给大家

首先把海康的库目录和包含目录复制到Qt的工程文件下,自己新建的两个文件夹分别存放包含和库。

Qt调用海康相机实时显示_第1张图片

Qt调用海康相机实时显示_第2张图片

Qt调用海康相机实时显示_第3张图片

 Qt调用海康相机实时显示_第4张图片

 然后在pro文件中添加如下代码

LIBS += -L$$PWD/Hik_Libs/ -lMvCameraControl
INCLUDEPATH += $$PWD/Hik_Includes
DEPENDPATH += $$PWD/Hik_Includes

至此海康环境配置完成,Opencv的配置见我下面链接

https://mp.csdn.net/mp_blog/creation/editor/124462432

二、接下来上代码

Qt调用海康相机实时显示_第5张图片 

头文件:

#ifndef CAMERAINTERFACE_H
#define CAMERAINTERFACE_H
#include"opencv2/opencv.hpp"
#include"iostream"
class CameraInterface
{
public:
    CameraInterface();
    ~CameraInterface();

    // ch:连接设备
    virtual int connectCamera(std::string id)=0;

    //设置是否为触发模式
    virtual int setTriggerMode(unsigned int TriggerModeNum)=0;

    //开启相机采集
    virtual int startCamera()=0;

    //关闭相机采集
    virtual int stopCamera()=0;

    //关闭相机
    virtual int closeCamera()=0;

    //软触发
    virtual int softTrigger()=0;

    //读取buffer
    virtual int ReadBuffer(cv::Mat &image)=0;

    //设置图像高度
    virtual int setHeight(unsigned int height)=0;

    //设置图像ROI宽度
    virtual int setWidth(unsigned int width)=0;

    //获取图像高度值
    virtual int getHeight()=0;

    //获取图像宽度值
    virtual int getWidth()=0;

    //获取相机曝光时间
    virtual float getExposureTime()=0;

    //设置图像水平偏移OffsetX
    virtual int setOffsetX(unsigned int offsetX)=0;

    //设置图像竖直偏移OffsetY
    virtual int setOffsetY(unsigned int offsetY)=0;

    //设置触发源
    virtual int setTriggerSource(unsigned int TriggerSourceNum)=0;

    //设置帧率控制使能
    virtual int setFrameRateEnable(bool comm)=0;

    //设置心跳时间
    virtual int setHeartBeatTime(unsigned int time)=0;

    //设置曝光时间
    virtual int setExposureTime(float ExposureTimeNum)=0;

    //关闭自动曝光
    virtual int setExposureAuto(bool exposureAutoFlag)=0;

    //关闭自动增益
    virtual int setGainAuto(bool gainAutoFlag)=0;

    //清理相机缓存
    virtual void clearBuffer()=0;
};

#endif // CAMERAINTERFACE_H
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include"mycamera.h"


#include"QMessageBox"
#include 
#include
#include
#include"mythread.h"
#include 
using namespace cv;

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_btn_Connect_clicked();
    void on_btn_Trigger_clicked();


    //显示连续图像
    void display();

    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

private:
    Ui::MainWindow *ui;

    //用于显示单张图像
    void display(const Mat* image);

    //相机指针
    CameraInterface* camera=NULL;
    //线程对象
    MyThread* myThread=NULL;
    //用于保存图像的图像指针对象
    Mat* myImage=new Mat();
};
#endif // MAINWINDOW_H
#ifndef MYCAMERA_H
#define MYCAMERA_H
#include"camerainterface.h"
#include"MvCameraControl.h"

class Mycamera:public CameraInterface
{
public:
    Mycamera();
    ~Mycamera();
    // ch:连接设备
    int connectCamera(std::string id);

    //设置是否为触发模式
    int setTriggerMode(unsigned int TriggerModeNum);

    //开启相机采集
    int startCamera();

    //关闭相机采集
    int stopCamera();

    //关闭相机
    int closeCamera();

    //软触发
    int softTrigger();

    //读取buffer
    int ReadBuffer(cv::Mat &image);


    //设置图像高度
    int setHeight(unsigned int height);

    //设置图像ROI宽度
    int setWidth(unsigned int width);

    //获取图像高度值
    int getHeight();

    //获取图像宽度值
    int getWidth();

    //获取相机曝光时间
    float getExposureTime();

    //设置图像水平偏移OffsetX
    int setOffsetX(unsigned int offsetX);

    //设置图像竖直偏移OffsetY
    int setOffsetY(unsigned int offsetY);

    //设置触发源
    int setTriggerSource(unsigned int TriggerSourceNum);

    //设置帧率控制使能
    int setFrameRateEnable(bool comm);

    //设置心跳时间
    int setHeartBeatTime(unsigned int time);

    //设置曝光时间
    int setExposureTime(float ExposureTimeNum);

    //关闭自动曝光
    int setExposureAuto(bool exposureAutoFlag);

    //关闭自动增益
    int setGainAuto(bool gainAutoFlag);

    //清理相机缓存
    void clearBuffer();

private:
    void*               m_hDevHandle;
public:
    // 用于保存图像的缓存
    unsigned int    m_nBufSizeForSaveImage;
    // 用于从驱动获取图像的缓存
    unsigned int    m_nBufSizeForDriver;
};


#endif // MYCAMERA_H
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include"QThread"
#include"camerainterface.h"
#include 

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = nullptr);
     ~MyThread();
    void run();
    void getCameraPtr(CameraInterface* camera);
    void getImagePtr(cv::Mat* image);
signals:
    void mess();

private:
    CameraInterface* cameraPtr=NULL;
    cv::Mat* imagePtr=NULL;
};

#endif // MYTHREAD_H

cpp文件: 

#include "camerainterface.h"

CameraInterface::CameraInterface()
{

}

CameraInterface::~CameraInterface()
{

}

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //线程对象实例化
    myThread=new MyThread();
    //将线程中的信号与槽进行连接
    connect(myThread,SIGNAL(mess()),this,SLOT(display()));
}

MainWindow::~MainWindow()
{
    delete ui;
    if(camera!=NULL)
    {
        camera->closeCamera();
        delete camera;
    }
}
void MainWindow::on_btn_Connect_clicked()
{
    if(camera==NULL)
    {
        camera=new Mycamera();
        //连接相机
        std::cout<<"Connect:  "<connectCamera("00792760583")<setTriggerMode(1)<setTriggerSource(7)<setExposureTime(5000)<startCamera()<getCameraPtr(camera);
        myThread->getImagePtr(myImage);
    }

}

void MainWindow::on_btn_Trigger_clicked()
{
        Mat* image=new Mat();
        //发送软触发
        std::cout<<"SoftTrigger:  "<softTrigger()<ReadBuffer(*image);
        display(image);
        //释放指针
        delete image;
}

void MainWindow::display(const Mat* imagePtr)
{
    std::cout<<"so"<channels()>1)
    {
        *QmyImage=QImage((const unsigned char*)(imagePtr->data),imagePtr->cols, imagePtr->rows, QImage::Format_RGB888);
    }
    else
    {
        *QmyImage=QImage((const unsigned char*)(imagePtr->data),imagePtr->cols, imagePtr->rows, QImage::Format_Indexed8);
    }

    *QmyImage = (*QmyImage).scaled(ui->Image_Label->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    //显示图像
    ui->Image_Label->setPixmap(QPixmap::fromImage(*QmyImage));
    delete QmyImage;
}

void MainWindow::display()
{
    //判断是黑白、彩色图像
    QImage* QmyImage=new QImage();
    if(myImage->channels()>1)
    {
        *QmyImage=QImage((const unsigned char*)(myImage->data),myImage->cols, myImage->rows, QImage::Format_RGB888);
    }
    else
    {
        *QmyImage=QImage((const unsigned char*)(myImage->data),myImage->cols, myImage->rows, QImage::Format_Indexed8);
    }

    *QmyImage = (*QmyImage).scaled(ui->Image_Label->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    //显示图像
    ui->Image_Label->setPixmap(QPixmap::fromImage(*QmyImage));
    delete QmyImage;
}

void MainWindow::on_pushButton_clicked()
{
    if(!myThread->isRunning())
    {
        myThread->start();
    }
}

void MainWindow::on_pushButton_2_clicked()
{
    if(myThread->isRunning())
    {
        myThread->requestInterruption();
        myThread->wait();
       // camera->stopCamera();
       // camera->closeCamera();
    }
}
#include "mycamera.h"

using namespace cv;

MV_CC_DEVICE_INFO_LIST m_stDevList;         // ch:设备信息列表结构体变量,用来存储设备列表
MV_CC_DEVICE_INFO* m_Device=NULL;

Mycamera::Mycamera()
{
    m_hDevHandle = NULL;
}
Mycamera::~Mycamera()
{
    if (m_hDevHandle)
    {
        MV_CC_DestroyHandle(m_hDevHandle);
        m_hDevHandle = NULL;
    }
}

//连接相机
int  Mycamera::connectCamera(std::string id)
{
    //查询设备列表
    int tempValue=MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &m_stDevList);
    if(tempValue!=0)
        //设备更新成功接收命令的返回值为0,返回值不为0则为异常
        return -1;
    if(m_stDevList.nDeviceNum==0)
        //未找到任何相机
        return 2;
    for (unsigned int i = 0; i < m_stDevList.nDeviceNum; i++)
    {
        MV_CC_DEVICE_INFO* pDeviceInfo = m_stDevList.pDeviceInfo[i];

        if (NULL == pDeviceInfo)
        {
            continue;
        }
        if(pDeviceInfo->nTLayerType==MV_USB_DEVICE)
        {
            if(id== (char*)pDeviceInfo->SpecialInfo.stUsb3VInfo.chSerialNumber||id== (char*)pDeviceInfo->SpecialInfo.stUsb3VInfo.chUserDefinedName||id== (char*)pDeviceInfo->SpecialInfo.stUsb3VInfo.chSerialNumber||id=="PECVD")
            {
                m_Device= m_stDevList.pDeviceInfo[i];
                break;
            }
        }

        if(pDeviceInfo->nTLayerType==MV_GIGE_DEVICE)
        {
            if(id== (char*)pDeviceInfo->SpecialInfo.stUsb3VInfo.chSerialNumber||id== (char*)pDeviceInfo->SpecialInfo.stGigEInfo.chUserDefinedName||id== (char*)pDeviceInfo->SpecialInfo.stGigEInfo.chSerialNumber||id=="PECVD")
            {
                m_Device= m_stDevList.pDeviceInfo[i];
                break;
            }
        }
        continue;
    }
    if(m_Device==NULL)
    {
        //未找到指定名称的相机
        return 3;
    }

    tempValue  = MV_CC_CreateHandle(&m_hDevHandle, m_Device);
    if(tempValue!=0)
        return -1;

    tempValue = MV_CC_OpenDevice(m_hDevHandle);
    if (tempValue!=0)
    {
        MV_CC_DestroyHandle(m_hDevHandle);
        m_hDevHandle = NULL;
        return -1;
    }else
    {
        setTriggerMode(1);
        return 0;
    }
    if (m_Device->nTLayerType == MV_GIGE_DEVICE)
    {
    }
    if(m_Device->nTLayerType == MV_USB_DEVICE)
    {
        MV_CC_SetImageNodeNum(&m_hDevHandle,2);
    }
}

//启动相机采集
int Mycamera::startCamera()
{
    int tempValue=MV_CC_StartGrabbing(m_hDevHandle);
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return 0;
    }
}

//停止相机采集
int Mycamera::stopCamera()
{
    int tempValue=MV_CC_StopGrabbing(m_hDevHandle);
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return 0;
    }
}

//关闭相机
int Mycamera::closeCamera()
{
    if (NULL == m_hDevHandle)
    {
        return -1;
    }
    MV_CC_CloseDevice(m_hDevHandle);
    int tempValue = MV_CC_DestroyHandle(m_hDevHandle);
    m_hDevHandle = NULL;
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return 0;
    }
}

//发送软触发
int Mycamera::softTrigger()
{
    int tempValue= MV_CC_SetCommandValue(m_hDevHandle, "TriggerSoftware");
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return 0;
    }
}

//读取相机中的图像
int Mycamera::ReadBuffer(Mat &image)
{
    Mat* getImage=new Mat();
    unsigned int nRecvBufSize = 0;
    MVCC_INTVALUE stParam;
    memset(&stParam, 0, sizeof(MVCC_INTVALUE));
    int tempValue = MV_CC_GetIntValue(m_hDevHandle, "PayloadSize", &stParam);
    if (tempValue != 0)
    {
        return -1;
    }
    nRecvBufSize = stParam.nCurValue;
    unsigned char* pDate;
    pDate=(unsigned char *)malloc(nRecvBufSize);

    MV_FRAME_OUT_INFO_EX stImageInfo = {0};
    tempValue= MV_CC_GetOneFrameTimeout(m_hDevHandle, pDate, nRecvBufSize, &stImageInfo, 700);
    if(tempValue!=0)
    {
        return -1;
    }
    m_nBufSizeForSaveImage = stImageInfo.nWidth * stImageInfo.nHeight * 3 + 2048;
    unsigned char* m_pBufForSaveImage;
    m_pBufForSaveImage = (unsigned char*)malloc(m_nBufSizeForSaveImage);


    bool isMono;
    switch (stImageInfo.enPixelType)
    {
    case PixelType_Gvsp_Mono8:
    case PixelType_Gvsp_Mono10:
    case PixelType_Gvsp_Mono10_Packed:
    case PixelType_Gvsp_Mono12:
    case PixelType_Gvsp_Mono12_Packed:
        isMono=true;
        break;
    default:
        isMono=false;
        break;
    }
    if(isMono)
    {
        *getImage=Mat(stImageInfo.nHeight,stImageInfo.nWidth,CV_8UC1,pDate);
        //imwrite("d:\\测试opencv_Mono.tif", image);
    }
    else
    {
        //转换图像格式为BGR8
        MV_CC_PIXEL_CONVERT_PARAM stConvertParam = {0};
        memset(&stConvertParam, 0, sizeof(MV_CC_PIXEL_CONVERT_PARAM));
        stConvertParam.nWidth = stImageInfo.nWidth;                 //ch:图像宽 | en:image width
        stConvertParam.nHeight = stImageInfo.nHeight;               //ch:图像高 | en:image height
        //stConvertParam.pSrcData = m_pBufForDriver;                  //ch:输入数据缓存 | en:input data buffer
        stConvertParam.pSrcData = pDate;                  //ch:输入数据缓存 | en:input data buffer
        stConvertParam.nSrcDataLen = stImageInfo.nFrameLen;         //ch:输入数据大小 | en:input data size
        stConvertParam.enSrcPixelType = stImageInfo.enPixelType;    //ch:输入像素格式 | en:input pixel format
        stConvertParam.enDstPixelType = PixelType_Gvsp_BGR8_Packed; //ch:输出像素格式 | en:output pixel format  适用于OPENCV的图像格式
        //stConvertParam.enDstPixelType = PixelType_Gvsp_RGB8_Packed; //ch:输出像素格式 | en:output pixel format
        stConvertParam.pDstBuffer = m_pBufForSaveImage;                    //ch:输出数据缓存 | en:output data buffer
        stConvertParam.nDstBufferSize = m_nBufSizeForSaveImage;            //ch:输出缓存大小 | en:output buffer size
        MV_CC_ConvertPixelType(m_hDevHandle, &stConvertParam);

        *getImage=Mat(stImageInfo.nHeight,stImageInfo.nWidth,CV_8UC3,m_pBufForSaveImage);
        //imwrite("d:\\测试opencv_Color.tif", image);
    }
    (*getImage).copyTo(image);
    (*getImage).release();
    free(pDate);
    free(m_pBufForSaveImage);
    return 0;
}

//获取图像高度值
int Mycamera::getHeight()
{
    MVCC_INTVALUE stParam;
    memset(&stParam, 0, sizeof(MVCC_INTVALUE));
    int tempValue=MV_CC_GetIntValue(m_hDevHandle, "Height", &stParam);
    int value= stParam.nCurValue;
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return value;
    }
}

//获取图像宽度值
int Mycamera::getWidth()
{
    MVCC_INTVALUE stParam;
    memset(&stParam, 0, sizeof(MVCC_INTVALUE));
    int tempValue=MV_CC_GetIntValue(m_hDevHandle, "Width", &stParam);
    int value= stParam.nCurValue;
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return value;
    }
}

//获取相机曝光时间
float Mycamera::getExposureTime()
{
    MVCC_FLOATVALUE stParam;
    memset(&stParam, 0, sizeof(MVCC_INTVALUE));
    int tempValue=MV_CC_GetFloatValue(m_hDevHandle, "ExposureTime", &stParam);
    float value= stParam.fCurValue;
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return value;
    }
}

//设置图像ROI高度
int Mycamera::setHeight(unsigned int height)
{
    int tempValue=MV_CC_SetIntValue(m_hDevHandle, "Height", height);
    if(tempValue!=0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//设置图像ROI宽度
int Mycamera::setWidth(unsigned int width)
{
    int tempValue=MV_CC_SetIntValue(m_hDevHandle, "Width", width);
    if(tempValue!=0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//设置图像水平偏移OffsetX
int Mycamera::setOffsetX(unsigned int offsetX)
{
    int tempValue=MV_CC_SetIntValue(m_hDevHandle, "OffsetX", offsetX);
    if(tempValue!=0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//设置图像竖直偏移OffsetY
int Mycamera::setOffsetY(unsigned int offsetY)
{
    int tempValue=MV_CC_SetIntValue(m_hDevHandle, "OffsetY", offsetY);
    if(tempValue!=0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//设置是否为触发模式
int Mycamera::setTriggerMode(unsigned int TriggerModeNum)
{
     //0:Off  1:On
     int tempValue= MV_CC_SetEnumValue(m_hDevHandle,"TriggerMode", TriggerModeNum);
     if(tempValue!=0)
     {
         return -1;
     }else
     {
         return 0;
     }
}

//设置触发源
int Mycamera::setTriggerSource(unsigned int TriggerSourceNum)
{
    //0:Line0  1:Line1  7:Software
    int tempValue= MV_CC_SetEnumValue(m_hDevHandle,"TriggerSource", TriggerSourceNum);
    if(tempValue!=0)
    {
        return -1;
    }else
    {
        return 0;
    }
}

//设置帧率控制使能
int Mycamera::setFrameRateEnable(bool comm)
{
    int tempValue =MV_CC_SetBoolValue(m_hDevHandle, "AcquisitionFrameRateEnable", comm);
    if (tempValue != 0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//设置心跳时间
int Mycamera::setHeartBeatTime(unsigned int time)
{
    //心跳时间最小为500ms
    if(time<500)
        time=500;
    int tempValue=MV_CC_SetIntValue(m_hDevHandle, "GevHeartbeatTimeout", time);
    if(tempValue!=0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//设置曝光时间
int Mycamera::setExposureTime(float ExposureTimeNum)
{
    int tempValue= MV_CC_SetFloatValue(m_hDevHandle, "ExposureTime",ExposureTimeNum );
    if(tempValue!=0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}
//关闭自动曝光
int Mycamera::setExposureAuto(bool exposureAutoFlag)
{
    int tempValue= MV_CC_SetEnumValue(m_hDevHandle,"ExposureAuto", exposureAutoFlag);
    if (tempValue != 0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//关闭自动增益
int Mycamera::setGainAuto(bool gainAutoFlag)
{
    int tempValue= MV_CC_SetEnumValue(m_hDevHandle,"GainAuto", gainAutoFlag);
    if (tempValue != 0)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

//清理相机缓存
void Mycamera::clearBuffer()
{
    //stopCamera();
    //startCamera();
}
#include "mythread.h"
#include 
MyThread::MyThread(QObject *parent)
    : QThread{parent}
{

}
MyThread::~MyThread()
{
    if(cameraPtr==NULL)
    {
        delete cameraPtr;
    }
    if(imagePtr==NULL)
    {
        delete imagePtr;
    }
}
void MyThread::getCameraPtr(CameraInterface *camera)
{
    cameraPtr=camera;
}

void MyThread::getImagePtr(cv::Mat *image)
{
    imagePtr=image;
}

void MyThread::run()
{
    if(cameraPtr==NULL)
    {
        return;
    }

    if(imagePtr==NULL)
    {
        return;
    }

    while(!isInterruptionRequested())
    {
        std::cout<<"Thread_Trigger:"<softTrigger()<ReadBuffer(*imagePtr)<

UI界面:

Qt调用海康相机实时显示_第6张图片

 校园网一边写博客不能一边打相机,所以就不放实时图了,有需要原码的小伙伴可以在评论区留言,如果人多的话,我整个链接供大家下载。

你可能感兴趣的:(C++,OpenCV,环境配置,visual,studio,ide,visualstudio)