SpireCV/video_io/sv_camera_def.cpp

138 lines
2.9 KiB
C++

#include "sv_camera_privately.h"
#include "iostream"
sv_p::CameraBase::CameraBase(int timeOut)
{
this->_timeOut = timeOut;
}
void sv_p::CameraBase::readThread(void)
{
int count = 0;
while (this->cap.isOpened())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (this->cap.grab())
{
std::lock_guard<std::mutex> locker(this->frameMutex);
this->cap.retrieve(this->imageBuff);
this->frameEmpty.notify_all();
isGot = true;
// 统计输入的瞬时帧率
this->fpsCurr = 1000.0f / count;
count = 0;
}
else
{
count++;
if (count > this->_timeOut)
{
// 超时则主动关闭相机
this->cap.release();
}
}
}
// 相机断开连接 记录事件后 退出线程
std::cout << "SpireCV (101) Camera has offline, check CAMERA!" << std::endl;
}
bool sv_p::CameraBase::read(cv::Mat &image)
{
bool ret = false;
std::lock_guard<std::mutex> locker(this->frameMutex);
if (this->frameEmpty.wait_for(this->frameMutex, std::chrono::milliseconds(this->_timeOut)) == std::cv_status::no_timeout)
{
// 获取图像
this->imageBuff.copyTo(image);
ret = true;
isGot = false;
}
return ret;
}
bool sv_p::CameraBase::readNoBlock(cv::Mat &image)
{
bool ret = false;
std::lock_guard<std::mutex> locker(this->frameMutex);
if (this->isGot)
{
// 该情况下read()不会阻塞
ret = this->read(image);
}
return ret;
}
#define PARAM_SET_CHECK(param, value) param = (value > 0 ? value : param)
void sv_p::CameraBase::setWH(int width, int height)
{
if (!this->cap.isOpened())
{
PARAM_SET_CHECK(this->_width, width);
PARAM_SET_CHECK(this->_height, height);
}
}
void sv_p::CameraBase::setFps(int fps)
{
PARAM_SET_CHECK(this->_fps, fps);
if (this->cap.isOpened())
{
this->cap.set(cv::CAP_PROP_FPS, fps);
}
}
void sv_p::CameraBase::setBrightness(float brightness)
{
PARAM_SET_CHECK(this->_brightness, brightness);
if (this->cap.isOpened())
{
this->cap.set(cv::CAP_PROP_BRIGHTNESS, brightness);
}
}
void sv_p::CameraBase::setContrast(float contrast)
{
PARAM_SET_CHECK(this->_contrast, contrast);
if (this->cap.isOpened())
{
this->cap.set(cv::CAP_PROP_CONTRAST, contrast);
}
}
void sv_p::CameraBase::setSaturation(float saturation)
{
PARAM_SET_CHECK(this->_saturation, saturation);
if (this->cap.isOpened())
{
this->cap.set(cv::CAP_PROP_SATURATION, saturation);
}
}
void sv_p::CameraBase::setHue(float hue)
{
PARAM_SET_CHECK(this->_hue, hue);
if (this->cap.isOpened())
{
this->cap.set(cv::CAP_PROP_HUE, hue);
}
}
void sv_p::CameraBase::setExposure(float exposure)
{
PARAM_SET_CHECK(this->_exposure, exposure);
if (this->cap.isOpened())
{
this->cap.set(cv::CAP_PROP_EXPOSURE, exposure);
}
}
void sv_p::CameraBase::release(void)
{
if (this->cap.isOpened())
{
this->cap.release();
}
}