文章目录
- 前言:
- 基础夯实:
- 效果展示:
- 参考的资料:
- 遇到问题:
-
- [问题1:int64 does not](#问题1:int64 does not)
- 问题2:LNK2019
- 配置思路(这个很重要)
- 配置关键图片:
- 配置具体过程:
- 核心代码:
前言:
海康威视的教程里面,关于C++的教程,编译环境是VS,所以想使用QTcreate对于海康威视的相机进行使用,包括查找设备,打开设备,关闭设备,开始采集,停止采集,软触发,触发一次,保存bmp,保存jpg,保存tiff,保存png,调节曝光,增益,帧率。
基础夯实:
在MVS中海康威视的相关教程:MVS链接
下载完成之后按照这个目录(我是下载的的D盘),可以找到VS的教程:D:\MVS\Development\Samples\VC\VS
如果你需要QT上的教程,请继续向下观看。
效果展示:
图片展示:
视频展示:
HKshow
参考的资料:
在这个过程中,我参考了很多的资料,包括VS里面的例程代码,但是我水平有限,不能直接搬运VS中的代码。
简单对资料进行说明,介绍了环境的安装,包括opencv,sdk的头文件,库文件,二次封装的MvCamera.h和MvCamera.cpp文件。环境的安装是极其容易出错的过程,环境没问题,其他的才能正常的运行。
遇到问题:
问题1:int64 does not
这个是你mingw设置的opencv,但是你却用msvc打开了。这个编译环境必须一致。
问题2:LNK2019
你的opencv库没有连接好,路径问题或者camke问题,系统环境问题这都是有可能的。
配置思路(这个很重要)
首先你下载MVS之后,里面lib文件和头文件,头文件全要(参考配置图片),库文件只要一个(MvCameraControl.lib)。你需要把二次封装的函数导入你的QT下面里面,就是MvCamera.h和MvCamera.cpp这两个文件,如果你只进行导入也可以,因为你用到了opencv,不要纠结要不要使用opencv,直接用就行了,很方便,当时纠结了,想直接使用那两个文件,一直被卡。opencv按照教程按装就行了,按照mingw那个流程,在QT的pro文件中使用绝对路径,别使用相对路径(不使用导入库那个选项),因为我当时导入库就没成功。头文件直接包含,在直接的文件中导入一下,看一下有没有报错,没有保存说明导入成功。这里的MvCamera.cpp和MvCamera.h是不能直接使用的,需要在里面添加一些内容,直接使用也是会报错,原因就是你使用了opencv。最后,大佬使用的是导入.h文件,我需要ui文件,我就自己进行更改了,如果有需要ui文件的,评论区发qq邮箱,我源码或者ui可以私发你学习。基本上按照这个思路,成功搭建环境到运行应该是没有问题的。
配置关键图片:
配置具体过程:
海康威视相机在QTcreate上的环境配置教程(qt+opencv+海康SDK)
核心代码:
MvCamera.h
cpp
/************************************************************************/
/* 以C++接口为基础,对常用函数进行二次封装,方便用户使用 */
/************************************************************************/
#ifndef _MV_CAMERA_H_
#define _MV_CAMERA_H_
#include "MvCameraControl.h"
#include <string.h>
#include "opencv2/opencv.hpp"
//注意此处可能会跟系统函数定义冲突
using namespace cv;
#ifndef MV_NULL
#define MV_NULL 0
#endif
class CMvCamera
{
public:
CMvCamera();
~CMvCamera();
// ch:获取SDK版本号 | en:Get SDK Version
static int GetSDKVersion();
// ch:枚举设备 | en:Enumerate Device
static int EnumDevices(unsigned int nTLayerType, MV_CC_DEVICE_INFO_LIST* pstDevList);
// ch:判断设备是否可达 | en:Is the device accessible
static bool IsDeviceAccessible(MV_CC_DEVICE_INFO* pstDevInfo, unsigned int nAccessMode);
// ch:打开设备 | en:Open Device
int Open(MV_CC_DEVICE_INFO* pstDeviceInfo);
// ch:关闭设备 | en:Close Device
int Close();
// ch:判断相机是否处于连接状态 | en:Is The Device Connected
bool IsDeviceConnected();
// ch:注册图像数据回调 | en:Register Image Data CallBack
int RegisterImageCallBack(void(__stdcall* cbOutput)(unsigned char * pData, MV_FRAME_OUT_INFO_EX* pFrameInfo, void* pUser), void* pUser);
// ch:开启抓图 | en:Start Grabbing
int StartGrabbing();
// ch:停止抓图 | en:Stop Grabbing
int StopGrabbing();
// ch:主动获取一帧图像数据 | en:Get one frame initiatively
int GetImageBuffer(MV_FRAME_OUT* pFrame, int nMsec);
// ch:释放图像缓存 | en:Free image buffer
int FreeImageBuffer(MV_FRAME_OUT* pFrame);
// ch:显示一帧图像 | en:Display one frame image
int DisplayOneFrame(MV_DISPLAY_FRAME_INFO* pDisplayInfo);
// ch:设置SDK内部图像缓存节点个数 | en:Set the number of the internal image cache nodes in SDK
int SetImageNodeNum(unsigned int nNum);
// ch:获取设备信息 | en:Get device information
int GetDeviceInfo(MV_CC_DEVICE_INFO* pstDevInfo);
// ch:获取GEV相机的统计信息 | en:Get detect info of GEV camera
int GetGevAllMatchInfo(MV_MATCH_INFO_NET_DETECT* pMatchInfoNetDetect);
// ch:获取U3V相机的统计信息 | en:Get detect info of U3V camera
int GetU3VAllMatchInfo(MV_MATCH_INFO_USB_DETECT* pMatchInfoUSBDetect);
// ch:获取和设置Int型参数,如 Width和Height,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Int type parameters, such as Width and Height, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int GetIntValue(IN const char* strKey, OUT MVCC_INTVALUE_EX *pIntValue);
int SetIntValue(IN const char* strKey, IN int64_t nValue);
// ch:获取和设置Enum型参数,如 PixelFormat,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Enum type parameters, such as PixelFormat, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int GetEnumValue(IN const char* strKey, OUT MVCC_ENUMVALUE *pEnumValue);
int SetEnumValue(IN const char* strKey, IN unsigned int nValue);
int SetEnumValueByString(IN const char* strKey, IN const char* sValue);
int GetEnumEntrySymbolic(IN const char* strKey, IN MVCC_ENUMENTRY* pstEnumEntry);
// ch:获取和设置Float型参数,如 ExposureTime和Gain,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Float type parameters, such as ExposureTime and Gain, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int GetFloatValue(IN const char* strKey, OUT MVCC_FLOATVALUE *pFloatValue);
int SetFloatValue(IN const char* strKey, IN float fValue);
// ch:获取和设置Bool型参数,如 ReverseX,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Bool type parameters, such as ReverseX, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int GetBoolValue(IN const char* strKey, OUT bool *pbValue);
int SetBoolValue(IN const char* strKey, IN bool bValue);
// ch:获取和设置String型参数,如 DeviceUserID,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件UserSetSave
// en:Get String type parameters, such as DeviceUserID, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int GetStringValue(IN const char* strKey, MVCC_STRINGVALUE *pStringValue);
int SetStringValue(IN const char* strKey, IN const char * strValue);
// ch:执行一次Command型命令,如 UserSetSave,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Execute Command once, such as UserSetSave, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int CommandExecute(IN const char* strKey);
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
int GetOptimalPacketSize(unsigned int* pOptimalPacketSize);
// ch:注册消息异常回调 | en:Register Message Exception CallBack
int RegisterExceptionCallBack(void(__stdcall* cbException)(unsigned int nMsgType, void* pUser), void* pUser);
// ch:注册单个事件回调 | en:Register Event CallBack
int RegisterEventCallBack(const char* pEventName, void(__stdcall* cbEvent)(MV_EVENT_OUT_INFO * pEventInfo, void* pUser), void* pUser);
// ch:强制IP | en:Force IP
int ForceIp(unsigned int nIP, unsigned int nSubNetMask, unsigned int nDefaultGateWay);
// ch:配置IP方式 | en:IP configuration method
int SetIpConfig(unsigned int nType);
// ch:设置网络传输模式 | en:Set Net Transfer Mode
int SetNetTransMode(unsigned int nType);
// ch:像素格式转换 | en:Pixel format conversion
int ConvertPixelType(MV_CC_PIXEL_CONVERT_PARAM* pstCvtParam);
// ch:保存图片 | en:save image
int SaveImage(MV_SAVE_IMAGE_PARAM_EX* pstParam);
// ch:保存图片为文件 | en:Save the image as a file
int SaveImageToFile(MV_SAVE_IMG_TO_FILE_PARAM* pstParam);
// ch:绘制圆形辅助线 | en:Draw circle auxiliary line
int DrawCircle(MVCC_CIRCLE_INFO* pCircleInfo);
// ch:绘制线形辅助线 | en:Draw lines auxiliary line
int DrawLines(MVCC_LINES_INFO* pLinesInfo);
//读取buffer
int ReadBuffer(Mat &image);
private:
void *m_hDevHandle;
//用于保存图像的缓存
unsigned int m_nBufSizeForSaveImage;
};
#endif//_MV_CAMERA_H_
MvCamera.cpp
cpp
#include "mvcamera.h"
CMvCamera::CMvCamera()
{
m_hDevHandle = MV_NULL;
}
CMvCamera::~CMvCamera()
{
if (m_hDevHandle)
{
MV_CC_DestroyHandle(m_hDevHandle);
m_hDevHandle = MV_NULL;
}
}
// ch:获取SDK版本号 | en:Get SDK Version
int CMvCamera::GetSDKVersion()
{
return MV_CC_GetSDKVersion();
}
// ch:枚举设备 | en:Enumerate Device
int CMvCamera::EnumDevices(unsigned int nTLayerType, MV_CC_DEVICE_INFO_LIST* pstDevList)
{
return MV_CC_EnumDevices(nTLayerType, pstDevList);
}
// ch:判断设备是否可达 | en:Is the device accessible
bool CMvCamera::IsDeviceAccessible(MV_CC_DEVICE_INFO* pstDevInfo, unsigned int nAccessMode)
{
return MV_CC_IsDeviceAccessible(pstDevInfo, nAccessMode);
}
// ch:打开设备 | en:Open Device
int CMvCamera::Open(MV_CC_DEVICE_INFO* pstDeviceInfo)
{
if (MV_NULL == pstDeviceInfo)
{
return MV_E_PARAMETER;
}
if (m_hDevHandle)
{
return MV_E_CALLORDER;
}
int nRet = MV_CC_CreateHandle(&m_hDevHandle, pstDeviceInfo);
if (MV_OK != nRet)
{
return nRet;
}
nRet = MV_CC_OpenDevice(m_hDevHandle);
if (MV_OK != nRet)
{
MV_CC_DestroyHandle(m_hDevHandle);
m_hDevHandle = MV_NULL;
}
return nRet;
}
// ch:关闭设备 | en:Close Device
int CMvCamera::Close()
{
if (MV_NULL == m_hDevHandle)
{
return MV_E_HANDLE;
}
MV_CC_CloseDevice(m_hDevHandle);
int nRet = MV_CC_DestroyHandle(m_hDevHandle);
m_hDevHandle = MV_NULL;
return nRet;
}
// ch:判断相机是否处于连接状态 | en:Is The Device Connected
bool CMvCamera::IsDeviceConnected()
{
return MV_CC_IsDeviceConnected(m_hDevHandle);
}
// ch:注册图像数据回调 | en:Register Image Data CallBack
int CMvCamera::RegisterImageCallBack(void(__stdcall* cbOutput)(unsigned char * pData, MV_FRAME_OUT_INFO_EX* pFrameInfo, void* pUser), void* pUser)
{
return MV_CC_RegisterImageCallBackEx(m_hDevHandle, cbOutput, pUser);
}
// ch:开启抓图 | en:Start Grabbing
int CMvCamera::StartGrabbing()
{
return MV_CC_StartGrabbing(m_hDevHandle);
}
// ch:停止抓图 | en:Stop Grabbing
int CMvCamera::StopGrabbing()
{
return MV_CC_StopGrabbing(m_hDevHandle);
}
// ch:主动获取一帧图像数据 | en:Get one frame initiatively
int CMvCamera::GetImageBuffer(MV_FRAME_OUT* pFrame, int nMsec)
{
return MV_CC_GetImageBuffer(m_hDevHandle, pFrame, nMsec);
}
// ch:释放图像缓存 | en:Free image buffer
int CMvCamera::FreeImageBuffer(MV_FRAME_OUT* pFrame)
{
return MV_CC_FreeImageBuffer(m_hDevHandle, pFrame);
}
// ch:设置显示窗口句柄 | en:Set Display Window Handle
int CMvCamera::DisplayOneFrame(MV_DISPLAY_FRAME_INFO* pDisplayInfo)
{
return MV_CC_DisplayOneFrame(m_hDevHandle, pDisplayInfo);
}
// ch:设置SDK内部图像缓存节点个数 | en:Set the number of the internal image cache nodes in SDK
int CMvCamera::SetImageNodeNum(unsigned int nNum)
{
return MV_CC_SetImageNodeNum(m_hDevHandle, nNum);
}
// ch:获取设备信息 | en:Get device information
int CMvCamera::GetDeviceInfo(MV_CC_DEVICE_INFO* pstDevInfo)
{
return MV_CC_GetDeviceInfo(m_hDevHandle, pstDevInfo);
}
// ch:获取GEV相机的统计信息 | en:Get detect info of GEV camera
int CMvCamera::GetGevAllMatchInfo(MV_MATCH_INFO_NET_DETECT* pMatchInfoNetDetect)
{
if (MV_NULL == pMatchInfoNetDetect)
{
return MV_E_PARAMETER;
}
MV_CC_DEVICE_INFO stDevInfo = {0};
GetDeviceInfo(&stDevInfo);
if (stDevInfo.nTLayerType != MV_GIGE_DEVICE)
{
return MV_E_SUPPORT;
}
MV_ALL_MATCH_INFO struMatchInfo = {0};
struMatchInfo.nType = MV_MATCH_TYPE_NET_DETECT;
struMatchInfo.pInfo = pMatchInfoNetDetect;
struMatchInfo.nInfoSize = sizeof(MV_MATCH_INFO_NET_DETECT);
memset(struMatchInfo.pInfo, 0, sizeof(MV_MATCH_INFO_NET_DETECT));
return MV_CC_GetAllMatchInfo(m_hDevHandle, &struMatchInfo);
}
// ch:获取U3V相机的统计信息 | en:Get detect info of U3V camera
int CMvCamera::GetU3VAllMatchInfo(MV_MATCH_INFO_USB_DETECT* pMatchInfoUSBDetect)
{
if (MV_NULL == pMatchInfoUSBDetect)
{
return MV_E_PARAMETER;
}
MV_CC_DEVICE_INFO stDevInfo = {0};
GetDeviceInfo(&stDevInfo);
if (stDevInfo.nTLayerType != MV_USB_DEVICE)
{
return MV_E_SUPPORT;
}
MV_ALL_MATCH_INFO struMatchInfo = {0};
struMatchInfo.nType = MV_MATCH_TYPE_USB_DETECT;
struMatchInfo.pInfo = pMatchInfoUSBDetect;
struMatchInfo.nInfoSize = sizeof(MV_MATCH_INFO_USB_DETECT);
memset(struMatchInfo.pInfo, 0, sizeof(MV_MATCH_INFO_USB_DETECT));
return MV_CC_GetAllMatchInfo(m_hDevHandle, &struMatchInfo);
}
// ch:获取和设置Int型参数,如 Width和Height,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Int type parameters, such as Width and Height, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int CMvCamera::GetIntValue(IN const char* strKey, OUT MVCC_INTVALUE_EX *pIntValue)
{
return MV_CC_GetIntValueEx(m_hDevHandle, strKey, pIntValue);
}
int CMvCamera::SetIntValue(IN const char* strKey, IN int64_t nValue)
{
return MV_CC_SetIntValueEx(m_hDevHandle, strKey, nValue);
}
// ch:获取和设置Enum型参数,如 PixelFormat,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Enum type parameters, such as PixelFormat, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int CMvCamera::GetEnumValue(IN const char* strKey, OUT MVCC_ENUMVALUE *pEnumValue)
{
return MV_CC_GetEnumValue(m_hDevHandle, strKey, pEnumValue);
}
int CMvCamera::SetEnumValue(IN const char* strKey, IN unsigned int nValue)
{
return MV_CC_SetEnumValue(m_hDevHandle, strKey, nValue);
}
int CMvCamera::SetEnumValueByString(IN const char* strKey, IN const char* sValue)
{
return MV_CC_SetEnumValueByString(m_hDevHandle, strKey, sValue);
}
int CMvCamera::GetEnumEntrySymbolic(IN const char* strKey, IN MVCC_ENUMENTRY* pstEnumEntry)
{
return MV_CC_GetEnumEntrySymbolic(m_hDevHandle, strKey, pstEnumEntry);
}
// ch:获取和设置Float型参数,如 ExposureTime和Gain,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Float type parameters, such as ExposureTime and Gain, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int CMvCamera::GetFloatValue(IN const char* strKey, OUT MVCC_FLOATVALUE *pFloatValue)
{
return MV_CC_GetFloatValue(m_hDevHandle, strKey, pFloatValue);
}
int CMvCamera::SetFloatValue(IN const char* strKey, IN float fValue)
{
return MV_CC_SetFloatValue(m_hDevHandle, strKey, fValue);
}
// ch:获取和设置Bool型参数,如 ReverseX,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Get Bool type parameters, such as ReverseX, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int CMvCamera::GetBoolValue(IN const char* strKey, OUT bool *pbValue)
{
return MV_CC_GetBoolValue(m_hDevHandle, strKey, pbValue);
}
int CMvCamera::SetBoolValue(IN const char* strKey, IN bool bValue)
{
return MV_CC_SetBoolValue(m_hDevHandle, strKey, bValue);
}
// ch:获取和设置String型参数,如 DeviceUserID,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件UserSetSave
// en:Get String type parameters, such as DeviceUserID, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int CMvCamera::GetStringValue(IN const char* strKey, MVCC_STRINGVALUE *pStringValue)
{
return MV_CC_GetStringValue(m_hDevHandle, strKey, pStringValue);
}
int CMvCamera::SetStringValue(IN const char* strKey, IN const char* strValue)
{
return MV_CC_SetStringValue(m_hDevHandle, strKey, strValue);
}
// ch:执行一次Command型命令,如 UserSetSave,详细内容参考SDK安装目录下的 MvCameraNode.xlsx 文件
// en:Execute Command once, such as UserSetSave, for details please refer to MvCameraNode.xlsx file under SDK installation directory
int CMvCamera::CommandExecute(IN const char* strKey)
{
return MV_CC_SetCommandValue(m_hDevHandle, strKey);
}
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
int CMvCamera::GetOptimalPacketSize(unsigned int* pOptimalPacketSize)
{
if (MV_NULL == pOptimalPacketSize)
{
return MV_E_PARAMETER;
}
int nRet = MV_CC_GetOptimalPacketSize(m_hDevHandle);
if (nRet < MV_OK)
{
return nRet;
}
*pOptimalPacketSize = (unsigned int)nRet;
return MV_OK;
}
// ch:注册消息异常回调 | en:Register Message Exception CallBack
int CMvCamera::RegisterExceptionCallBack(void(__stdcall* cbException)(unsigned int nMsgType, void* pUser),void* pUser)
{
return MV_CC_RegisterExceptionCallBack(m_hDevHandle, cbException, pUser);
}
// ch:注册单个事件回调 | en:Register Event CallBack
int CMvCamera::RegisterEventCallBack(const char* pEventName, void(__stdcall* cbEvent)(MV_EVENT_OUT_INFO * pEventInfo, void* pUser), void* pUser)
{
return MV_CC_RegisterEventCallBackEx(m_hDevHandle, pEventName, cbEvent, pUser);
}
// ch:强制IP | en:Force IP
int CMvCamera::ForceIp(unsigned int nIP, unsigned int nSubNetMask, unsigned int nDefaultGateWay)
{
return MV_GIGE_ForceIpEx(m_hDevHandle, nIP, nSubNetMask, nDefaultGateWay);
}
// ch:配置IP方式 | en:IP configuration method
int CMvCamera::SetIpConfig(unsigned int nType)
{
return MV_GIGE_SetIpConfig(m_hDevHandle, nType);
}
// ch:设置网络传输模式 | en:Set Net Transfer Mode
int CMvCamera::SetNetTransMode(unsigned int nType)
{
return MV_GIGE_SetNetTransMode(m_hDevHandle, nType);
}
// ch:像素格式转换 | en:Pixel format conversion
int CMvCamera::ConvertPixelType(MV_CC_PIXEL_CONVERT_PARAM* pstCvtParam)
{
return MV_CC_ConvertPixelType(m_hDevHandle, pstCvtParam);
}
// ch:保存图片 | en:save image
int CMvCamera::SaveImage(MV_SAVE_IMAGE_PARAM_EX* pstParam)
{
return MV_CC_SaveImageEx2(m_hDevHandle, pstParam);
}
// ch:保存图片为文件 | en:Save the image as a file
int CMvCamera::SaveImageToFile(MV_SAVE_IMG_TO_FILE_PARAM* pstSaveFileParam)
{
return MV_CC_SaveImageToFile(m_hDevHandle, pstSaveFileParam);
}
// ch:绘制圆形辅助线 | en:Draw circle auxiliary line
int CMvCamera::DrawCircle(MVCC_CIRCLE_INFO* pCircleInfo)
{
return MV_CC_DrawCircle(m_hDevHandle, pCircleInfo);
}
// ch:绘制线形辅助线 | en:Draw lines auxiliary line
int CMvCamera::DrawLines(MVCC_LINES_INFO* pLinesInfo)
{
return MV_CC_DrawLines(m_hDevHandle, pLinesInfo);
}
//读取相机中的图像
int CMvCamera::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;
}
widget.cpp
cpp
#include "widget.h"
#include "ui_widget.h"
#include<QMessageBox>
#include<QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
,m_bOpenDevice(false)
,m_nDeviceCombo(0)
,m_nTriggerMode(MV_TRIGGER_MODE_OFF)
,m_bStartGrabbing(false)
,m_pcMyCamera(NULL)
,m_pSaveImageBuf(NULL)
,m_nSaveImageBufSize(0)
,m_bSoftWareTriggerCheck(false)
, m_nTriggerSource(MV_TRIGGER_SOURCE_SOFTWARE)
,m_dExposureEdit(0)
,m_dGainEdit(0)
,m_dFrameRateEdit(0)
,m_isDeviceReady(false)
{
m_WorkThread=new WorkThread(*this);
ui->setupUi(this);
setWindowTitle("海康相机");
InitUi();
connect(ui->searchDeviceBtn ,SIGNAL(clicked()),this,SLOT(slot_searchDevice()));
connect(ui->openDeviceBtn ,SIGNAL(clicked()),this,SLOT(slot_openDevice()));
connect(ui->closeDeviceBtn ,SIGNAL(clicked()),this,SLOT(slot_closeDevice()));
connect(ui->continusModeBtn ,SIGNAL(clicked()),this,SLOT(slot_continusModeBtn()));
connect(ui->triggerModeBtn ,SIGNAL(clicked()),this,SLOT(slot_triggerModeBtn()));
connect(ui->startGrabBtn ,SIGNAL(clicked()),this,SLOT(slot_grabbingBtn()));
connect(ui->softwareTriggerBtn,SIGNAL(stateChanged(int)),this,SLOT(slot_softwareTriggerBtn()));
connect(ui->softwareOnceBtn ,SIGNAL(clicked()),this,SLOT(slot_softwareoOnceBtn()));
connect(ui->saveBmpBtn ,SIGNAL(clicked()),this,SLOT(slot_saveBmpBtn()));
connect(ui->saveJpgBtn ,SIGNAL(clicked()),this,SLOT(slot_saveJpgBtn()));
connect(ui->saveTiffBtn ,SIGNAL(clicked()),this,SLOT(slot_saveTiffBtn()));
connect(ui->savePngBtn ,SIGNAL(clicked()),this,SLOT(slot_savePngBtn()));
connect(ui->GetParamterBtn ,SIGNAL(clicked()),this,SLOT(slot_getParameterBtn()));
connect(ui->SetParameterBtn ,SIGNAL(clicked()),this,SLOT(slot_setParameterBtn()));
connect(ui->stopGrabBtn ,SIGNAL(clicked()),this,SLOT(slot_stopGrbbingBtn()));
}
void Widget::slot_setParameterBtn()
{
bool bIsSetSucceed = true;
int nRet = SetExposureTime();
if (nRet != MV_OK)
{
bIsSetSucceed = false;
QMessageBox::critical(this,"Exposure","Set Exposure Time Fail");
}
nRet = SetGain();
if (nRet != MV_OK)
{
bIsSetSucceed = false;
QMessageBox::critical(this,"Gain","Set Gain Fail");
}
nRet = SetFrameRate();
if (nRet != MV_OK)
{
bIsSetSucceed = false;
QMessageBox::critical(this,"Frame","Set Frame Rate Fail");
}
if (true == bIsSetSucceed)
{
QMessageBox::critical(this,"Parameter","Set Parameter Succeed");
}
}
void Widget::slot_stopGrbbingBtn()
{
if (false == m_bOpenDevice || false == m_bStartGrabbing || NULL == m_pcMyCamera)
{
return;
}
m_WorkThread->SetRun(false);
bool f=m_WorkThread->isRun();
if(f)
{
m_WorkThread->quit();
m_WorkThread->wait();
m_WorkThread=NULL;
}
int nRet = m_pcMyCamera->StopGrabbing();
if(MV_OK != nRet)
{
QMessageBox::critical(this,"grabbing","Stop grabbing fail");
return;
}
m_bStartGrabbing = false;
}
int Widget::SetTriggerSource()
{
int nRet = MV_OK;
m_bSoftWareTriggerCheck=ui->softwareTriggerBtn->isChecked();
if (m_bSoftWareTriggerCheck)
{
m_nTriggerSource = MV_TRIGGER_SOURCE_SOFTWARE;
nRet = m_pcMyCamera->SetEnumValue("TriggerSource", m_nTriggerSource);
if (MV_OK != nRet)
{
QMessageBox::critical(this,"Trigger","Set Software Trigger Fail");
return nRet;
}
// GetDlgItem(IDC_SOFTWARE_ONCE_BUTTON )->EnableWindow(TRUE);
}
else
{
m_nTriggerSource = MV_TRIGGER_SOURCE_LINE0;
nRet = m_pcMyCamera->SetEnumValue("TriggerSource", m_nTriggerSource);
if (MV_OK != nRet)
{
QMessageBox::critical(this,"Hardware","Set Hardware Trigger Fail");
return nRet;
}
//GetDlgItem(IDC_SOFTWARE_ONCE_BUTTON )->EnableWindow(FALSE);
}
return nRet;
}
int Widget::SetFrameRate()
{
int nRet = m_pcMyCamera->SetBoolValue("AcquisitionFrameRateEnable", true);
if (MV_OK != nRet)
{
return nRet;
}
bool ok;
float frameRate = ui->FrameRateLineEdit->text().toDouble(&ok);
if (!ok) {
// 处理转换失败的情况,可能需要返回错误代码或显示错误消息
return -1; // 示例错误代码
}
return m_pcMyCamera->SetFloatValue("AcquisitionFrameRate", (float)frameRate);
}
int Widget::SetGain()
{
// 先尝试关闭自动增益
m_pcMyCamera->SetEnumValue("GainAuto", 0);
bool ok;
float gain = ui->GainLineEdit->text().toDouble(&ok);
if (!ok) {
// 处理转换失败的情况
return -1; // 示例错误代码
}
return m_pcMyCamera->SetFloatValue("Gain", (float)gain);
}
int Widget::SetExposureTime()
{
int nRet = m_pcMyCamera->SetEnumValue("ExposureMode", MV_EXPOSURE_MODE_TIMED);
if (MV_OK != nRet)
{
return nRet;
}
// 关闭自动曝光
m_pcMyCamera->SetEnumValue("ExposureAuto", MV_EXPOSURE_AUTO_MODE_OFF);
bool ok;
float exposureTime = ui->ExposureLineEdit->text().toDouble(&ok);
if (!ok) {
// 处理转换失败的情况
return -1; // 示例错误代码
}
return m_pcMyCamera->SetFloatValue("ExposureTime", (float)exposureTime);
}
int Widget::SetTriggerMode()
{
return m_pcMyCamera->SetEnumValue("TriggerMode", m_nTriggerMode);
}
void Widget::slot_getParameterBtn()
{
int nRet = GetTriggerMode();
if (nRet != MV_OK)
{
QMessageBox::critical(this,"Mode","Get Trigger Mode Fail");
}
nRet = GetExposureTime();
if (nRet != MV_OK)
{
QMessageBox::critical(this,"Mode","Get Exposure Time Fail");
}
ui->ExposureLineEdit->setText(QString("%1").arg(m_dExposureEdit));
nRet = GetGain();
if (nRet != MV_OK)
{
QMessageBox::critical(this,"Gain","Get Gain Fail");
}
ui->GainLineEdit->setText(QString("%1").arg(m_dGainEdit));
nRet = GetFrameRate();
if (nRet != MV_OK)
{
QMessageBox::critical(this,"Frame","Get Frame Rate Fail");
}
ui->FrameRateLineEdit->setText(QString("%1").arg(m_dFrameRateEdit));
nRet = GetTriggerSource();
if (nRet != MV_OK)
{
QMessageBox::critical(this,"Trigger","Get Trigger Source Fail");
}
}
int Widget::GetTriggerSource()
{
MVCC_ENUMVALUE stEnumValue = {0};
int nRet = m_pcMyCamera->GetEnumValue("TriggerSource", &stEnumValue);
if (MV_OK != nRet)
{
return nRet;
}
if ((unsigned int)MV_TRIGGER_SOURCE_SOFTWARE == stEnumValue.nCurValue)
{
m_bSoftWareTriggerCheck = true;
}
else
{
m_bSoftWareTriggerCheck = false;
}
return MV_OK;
}
int Widget::GetGain()
{
MVCC_FLOATVALUE stFloatValue = {0};
int nRet = m_pcMyCamera->GetFloatValue("Gain", &stFloatValue);
if (MV_OK != nRet)
{
return nRet;
}
m_dGainEdit = stFloatValue.fCurValue;
return MV_OK;
}
int Widget::GetFrameRate()
{
MVCC_FLOATVALUE stFloatValue = {0};
int nRet = m_pcMyCamera->GetFloatValue("ResultingFrameRate", &stFloatValue);
if (MV_OK != nRet)
{
return nRet;
}
m_dFrameRateEdit = stFloatValue.fCurValue;
return MV_OK;
}
int Widget::GetTriggerMode()
{
MVCC_ENUMVALUE stEnumValue = {0};
int nRet = m_pcMyCamera->GetEnumValue("TriggerMode", &stEnumValue);
if(MV_OK != nRet)
{
return nRet;
}
m_nTriggerMode = stEnumValue.nCurValue;
EnableControls();
return MV_OK;
}
int Widget::GetExposureTime()
{
MVCC_FLOATVALUE stFloatValue = {0};
int nRet = m_pcMyCamera->GetFloatValue("ExposureTime", &stFloatValue);
if(MV_OK != nRet)
{
return nRet;
}
m_dExposureEdit = stFloatValue.fCurValue;
return MV_OK;
}
void Widget::slot_savePngBtn()
{
int nRet = SaveImage(MV_Image_Png);
if (MV_OK != nRet)
{
QMessageBox::critical(this,"picture","Save Png fail");
return;
}
QMessageBox::critical(this,"picture","Save Png succeed!");
}
void Widget::slot_saveTiffBtn()
{
int nRet = SaveImage(MV_Image_Tif);
if (MV_OK != nRet)
{
QMessageBox::critical(this,"picture","Save jpg fail");
return;
}
QMessageBox::critical(this,"picture","Save jpg succeed!");
}
void Widget::slot_saveJpgBtn()
{
int nRet = SaveImage(MV_Image_Jpeg);
if (MV_OK != nRet)
{
QMessageBox::critical(this,"picture","Save jpg fail");
return;
}
QMessageBox::critical(this,"picture","Save jpg succeed!");
}
int Widget::SaveImage(MV_SAVE_IAMGE_TYPE enSaveImageType)
{
MV_SAVE_IMG_TO_FILE_PARAM stSaveFileParam;
memset(&stSaveFileParam, 0, sizeof(MV_SAVE_IMG_TO_FILE_PARAM));
m_mutex.lock();
if (m_pSaveImageBuf == NULL || m_stImageInfo.enPixelType == 0)
{
m_mutex.unlock();
return MV_E_NODATA;
}
if(RemoveCustomPixelFormats(m_stImageInfo.enPixelType))
{
m_mutex.unlock();
return MV_E_SUPPORT;
}
stSaveFileParam.enImageType = enSaveImageType; // ch:需要保存的图像类型 | en:Image format to save
stSaveFileParam.enPixelType = m_stImageInfo.enPixelType; // ch:相机对应的像素格式 | en:Camera pixel type
stSaveFileParam.nWidth = m_stImageInfo.nWidth; // ch:相机对应的宽 | en:Width
stSaveFileParam.nHeight = m_stImageInfo.nHeight; // ch:相机对应的高 | en:Height
stSaveFileParam.nDataLen = m_stImageInfo.nFrameLen;
stSaveFileParam.pData = m_pSaveImageBuf;
stSaveFileParam.iMethodValue = 0;
// ch:jpg图像质量范围为(50-99], png图像质量范围为[0-9] | en:jpg image nQuality range is (50-99], png image nQuality range is [0-9]
if (MV_Image_Bmp == stSaveFileParam.enImageType)
{
sprintf_s(stSaveFileParam.pImagePath, 256, "Image_w%d_h%d_fn%03d.bmp", stSaveFileParam.nWidth, stSaveFileParam.nHeight, m_stImageInfo.nFrameNum);
}
else if (MV_Image_Jpeg == stSaveFileParam.enImageType)
{
stSaveFileParam.nQuality = 80;
sprintf_s(stSaveFileParam.pImagePath, 256, "Image_w%d_h%d_fn%03d.jpg", stSaveFileParam.nWidth, stSaveFileParam.nHeight, m_stImageInfo.nFrameNum);
}
else if (MV_Image_Tif == stSaveFileParam.enImageType)
{
sprintf_s(stSaveFileParam.pImagePath, 256, "Image_w%d_h%d_fn%03d.tif", stSaveFileParam.nWidth, stSaveFileParam.nHeight, m_stImageInfo.nFrameNum);
}
else if (MV_Image_Png == stSaveFileParam.enImageType)
{
stSaveFileParam.nQuality = 8;
sprintf_s(stSaveFileParam.pImagePath, 256, "Image_w%d_h%d_fn%03d.png", stSaveFileParam.nWidth, stSaveFileParam.nHeight, m_stImageInfo.nFrameNum);
}
int nRet = m_pcMyCamera->SaveImageToFile(&stSaveFileParam);
m_mutex.unlock();
return nRet;
}
void Widget::slot_saveBmpBtn()
{
int nRet = SaveImage(MV_Image_Bmp);
if (MV_OK != nRet)
{
QMessageBox::critical(this,"picture","Save bmp fail");
return;
}
QMessageBox::critical(this,"picture","Save bmp succeed!");
}
void Widget::slot_closeDevice()
{
bool f=m_WorkThread->isRun();
if (f)
{
m_WorkThread->quit();
m_WorkThread->wait();
m_WorkThread->SetRun(false);
}
if(m_pcMyCamera)
{
m_pcMyCamera->Close();
delete m_pcMyCamera;
m_pcMyCamera = NULL;
}
m_bStartGrabbing=false;
m_bOpenDevice = false;
if(m_pSaveImageBuf)
{
free(m_pSaveImageBuf);
m_pSaveImageBuf=NULL;
}
m_nSaveImageBufSize=0;
EnableControls();
}
void Widget::slot_continusModeBtn()
{
m_nTriggerMode = MV_TRIGGER_MODE_OFF;
m_pcMyCamera->SetEnumValue("TriggerMode", m_nTriggerMode);
EnableControls();
}
void Widget::slot_triggerModeBtn()
{
m_nTriggerMode = MV_TRIGGER_MODE_ON;
m_pcMyCamera->SetEnumValue("TriggerMode", m_nTriggerMode);
EnableControls();
}
void Widget::slot_grabbingBtn()
{
if (false == m_bOpenDevice || true == m_bStartGrabbing || NULL == m_pcMyCamera)
{
return;
}
memset(&m_stImageInfo, 0, sizeof(MV_FRAME_OUT_INFO_EX));
m_WorkThread->SetRun(true);
m_WorkThread->start();
int nRet = m_pcMyCamera->StartGrabbing();
if (MV_OK != nRet)
{
m_WorkThread->SetRun(false);
QMessageBox::information(this,"Device","Start grabbing fail");
return;
}
m_bStartGrabbing = true;
EnableControls();
}
void Widget::slot_softwareTriggerBtn()
{
int nRet = MV_OK;
m_bSoftWareTriggerCheck=ui->softwareTriggerBtn->isChecked();
if (m_bSoftWareTriggerCheck)
{
m_nTriggerSource = MV_TRIGGER_SOURCE_SOFTWARE;
nRet = m_pcMyCamera->SetEnumValue("TriggerSource", m_nTriggerSource);
if (MV_OK != nRet)
{
QMessageBox::information(this,"Device","Set Software Trigger Fail");
return;
}
}
else
{
m_nTriggerSource = MV_TRIGGER_SOURCE_LINE0;
nRet = m_pcMyCamera->SetEnumValue("TriggerSource", m_nTriggerSource);
if (MV_OK != nRet)
{
QMessageBox::information(this,"Device","Set Hardware Trigger Fail");
return;
}
}
EnableControls();
return;
}
void Widget::slot_softwareoOnceBtn()
{
if(true != m_bStartGrabbing)
{
return;
}
m_pcMyCamera->CommandExecute("TriggerSoftware");
}
void Widget::InitUi()
{
memset(&m_stImageInfo, 0, sizeof(MV_FRAME_OUT_INFO_EX));
m_WorkThread->SetRun(false);
EnableControls();
}
void Widget::EnableControls()
{
//如果查询到设备,开启打开设备按钮
ui->openDeviceBtn->setEnabled(m_isDeviceReady?true:false);
ui->closeDeviceBtn->setEnabled(m_bOpenDevice?true:false);
ui->continusModeBtn->setEnabled(m_bOpenDevice?true:false);
ui->triggerModeBtn->setEnabled(m_bOpenDevice?true:false);
ui->startGrabBtn->setEnabled(m_bOpenDevice?true:false);
ui->stopGrabBtn->setEnabled(m_bOpenDevice?true:false);
//首先是否是在采集图像中,在采集图像的过程中,判断是否为触发模式,只有在触发模式下,才能开启软触发按钮。
ui->softwareTriggerBtn->setEnabled(m_bStartGrabbing?((MV_TRIGGER_MODE_ON == m_nTriggerMode)?true:false):false);
ui->softwareOnceBtn->setEnabled(
(MV_TRIGGER_MODE_OFF == m_nTriggerMode) ? false:
(m_bSoftWareTriggerCheck?true:false) );
ui->saveBmpBtn->setEnabled(m_bStartGrabbing?true:false);
ui->saveJpgBtn->setEnabled(m_bStartGrabbing?true:false);
ui->saveTiffBtn->setEnabled(m_bStartGrabbing?true:false);
ui->savePngBtn->setEnabled(m_bStartGrabbing?true:false);
ui->GetParamterBtn->setEnabled(m_bOpenDevice?true:false);
ui->SetParameterBtn ->setEnabled(m_bOpenDevice?true:false);
ui->ExposureLineEdit->setEnabled(m_bOpenDevice?true:false);
ui->GainLineEdit->setEnabled(m_bOpenDevice?true:false);
ui->FrameRateLineEdit->setEnabled(m_bOpenDevice?true:false);
}
bool Widget::RemoveCustomPixelFormats(MvGvspPixelType enPixelFormat)
{
int nResult = enPixelFormat & MV_GVSP_PIX_CUSTOM;
if(MV_GVSP_PIX_CUSTOM == nResult)
{
return true;
}
else
{
return false;
}
}
void Widget::slot_openDevice()
{
if (true == m_bOpenDevice || NULL != m_pcMyCamera)
{
return;
}
int nIndex = m_nDeviceCombo;
if ((nIndex < 0) | (nIndex >= MV_MAX_DEVICE_NUM))
{
QMessageBox::critical(this,"Device","Device index is error!");
return;
}
// ch:由设备信息创建设备实例 | en:Device instance created by device information
if (NULL == m_stDevList.pDeviceInfo[nIndex])
{
QMessageBox::critical(this,"Device","Device does not exist!");
return;
}
m_pcMyCamera = new CMvCamera;
if (NULL == m_pcMyCamera)
{
return;
}
int nRet = m_pcMyCamera->Open(m_stDevList.pDeviceInfo[nIndex]);
if (MV_OK != nRet)
{
delete m_pcMyCamera;
m_pcMyCamera = NULL;
QMessageBox::critical(this,"Device","Device Open error!");
return;
}
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
if (m_stDevList.pDeviceInfo[nIndex]->nTLayerType == MV_GIGE_DEVICE)
{
unsigned int nPacketSize = 0;
nRet = m_pcMyCamera->GetOptimalPacketSize(&nPacketSize);
if (nRet == MV_OK)
{
nRet = m_pcMyCamera->SetIntValue("GevSCPSPacketSize",nPacketSize);
if(nRet != MV_OK)
{
QMessageBox::critical(this,"Device","Warning: Set Packet Size fail!");
}
}
else
{
QMessageBox::critical(this,"Device","Warning: Get Packet Size fail!");
}
}
m_bOpenDevice = true;
EnableControls();
slot_getParameterBtn();
}
void Widget::slot_searchDevice()
{
QString strMsg;
ui->comboBox->clear();
memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST));
//ch:枚举子网内所有设备,将查询到的设备信息保存到m_stDevList列表中。
int nRet = CMvCamera::EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &m_stDevList);
if (MV_OK != nRet)
{
QMessageBox::critical(this,"device","No device!");
return;
}
// ch:将值加入到信息列表框中并显示出来 | en:Add value to the information list box and display
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)
{
char strUserName[256] = {0};
sprintf_s(strUserName, 256, "%s %s (%s)", pDeviceInfo->SpecialInfo.stUsb3VInfo.chModelName,
pDeviceInfo->SpecialInfo.stUsb3VInfo.chModelName,
pDeviceInfo->SpecialInfo.stUsb3VInfo.chSerialNumber);
QString UserName(strUserName);
QString strMsg = QString("USB %1").arg(QString::fromUtf8(reinterpret_cast<const char*>(pDeviceInfo->SpecialInfo.stUsb3VInfo.chSerialNumber)));
ui->comboBox->addItem(strMsg);
}
}
if (0 == m_stDevList.nDeviceNum)
{
QMessageBox::critical(this,"device","No device!");
return;
}
ui->comboBox->setCurrentIndex(0);
m_isDeviceReady=true; //设备已经打开
EnableControls();
}
Widget::~Widget()
{
delete ui;
slot_closeDevice();
}