增加3399 板子g100 g200校正及参数配置功能

This commit is contained in:
lovelyyoung 2021-07-31 11:12:53 +08:00
parent ed041c441c
commit ecb70b82ad
124 changed files with 48480 additions and 17462 deletions

View File

@ -4,3 +4,6 @@
3软件打开时自动查找已有设备打开然后将打开的型号显示在型号选择框中也可以通过型号选择框更换型号
4界面整合幅面页面等设置统一在扫描框中
5CIS的通道阀值以及畸变检测中目标值偏差值等参数自动加载和保存
2021年7月31日
1.增加3399 板子g100 g200 校正及配置功能

View File

@ -5,6 +5,7 @@
#include "HuaGoCorrect.h"
#include "A3.h"
#include "afxdialogex.h"
#include "HuaGoCorrectDlg.h"
// CA3 对话框
@ -28,6 +29,14 @@ void CA3::DoDataExchange(CDataExchange* pDX)
BEGIN_MESSAGE_MAP(CA3, CDialog)
ON_BN_CLICKED(IDC_BTNGETGRAYSP, &CA3::OnBnClickedBtngetgraysp)
ON_BN_CLICKED(IDC_BTNSETGRAYSP, &CA3::OnBnClickedBtnsetgraysp)
ON_BN_CLICKED(IDC_BTNGETUVSP, &CA3::OnBnClickedBtngetuvsp)
ON_BN_CLICKED(IDC_BTNSETUVSP, &CA3::OnBnClickedBtnsetuvsp)
ON_BN_CLICKED(IDC_BTNGETCOLORSP, &CA3::OnBnClickedBtngetcolorsp)
ON_BN_CLICKED(IDC_BTNSETCOLORSP, &CA3::OnBnClickedBtnsetcolorsp)
ON_BN_CLICKED(IDC_BTNGETSLEEPTIME, &CA3::OnBnClickedBtngetsleeptime)
ON_BN_CLICKED(IDC_BTNSETSLEEPTIME, &CA3::OnBnClickedBtnsetsleeptime)
END_MESSAGE_MAP()
@ -43,3 +52,130 @@ BOOL CA3::OnInitDialog()
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
void CA3::OnBnClickedBtngetsp()
{
// TODO: 在此添加控件通知处理程序代码
}
void CA3::OnBnClickedBtnsetsp()
{
// TODO: 在此添加控件通知处理程序代码
}
void CA3::OnBnClickedBtngetgraysp()
{
// TODO: 在此添加控件通知处理程序代码
OnGetOrSetSp(true, 0);
}
void CA3::OnBnClickedBtnsetgraysp()
{
// TODO: 在此添加控件通知处理程序代码
OnGetOrSetSp(false, 0);
}
void CA3::OnBnClickedBtngetuvsp()
{
// TODO: 在此添加控件通知处理程序代码
OnGetOrSetSp(true, 2);
}
void CA3::OnBnClickedBtnsetuvsp()
{
// TODO: 在此添加控件通知处理程序代码
OnGetOrSetSp(false, 2);
}
void CA3::OnBnClickedBtngetcolorsp()
{
// TODO: 在此添加控件通知处理程序代码
OnGetOrSetSp(true, 1);
}
void CA3::OnBnClickedBtnsetcolorsp()
{
OnGetOrSetSp(false, 1);
}
void CA3::OnGetOrSetSp(bool get,int type)
{
int sp;
CString str_sp;
auto parent = (CHuaGoCorrectDlg*)GetParent();
int itemid = type == 0 ? IDC_LBGRAYSP : (type == 1 ? IDC_LBCOLORSP : IDC_LBGUVSP); //IDC_LBCOLORSP
if (get)
{
parent->m_drv->GetSptime(type, sp);
str_sp.Format("%d", sp);
SetDlgItemText(itemid, str_sp);
}
else
{
GetDlgItemText(itemid, str_sp);
int value= atoi(str_sp);
parent->m_drv->SetSptime(type, value);
}
}
void CA3::OnGetOrSetSleepTime(bool get, int type)
{
int sp;
CString str_sp;
auto parent = (CHuaGoCorrectDlg*)GetParent();
int itemid = type == 0 ? IDC_LBGRAYSP : (type == 1 ? IDC_LBCOLORSP : IDC_LBGUVSP); //IDC_LBCOLORSP
if (get)
{
parent->m_drv->GetSptime(type, sp);
str_sp.Format("%d", sp);
SetDlgItemText(itemid, str_sp);
}
else
{
GetDlgItemText(itemid, str_sp);
int value = atoi(str_sp);
parent->m_drv->SetSptime(type, value);
}
}
void CA3::UpdateSleepTime(bool get)
{
int sp;
CString str_sp;
auto parent = (CHuaGoCorrectDlg*)GetParent();
if (get)
{
parent->m_drv->GetSleepTime(sp);
str_sp.Format("%d", sp);
SetDlgItemText(IDC_LBSLEEPTIME, str_sp);
}
else
{
GetDlgItemText(IDC_LBSLEEPTIME, str_sp);
int value = atoi(str_sp);
if (value <= 0) value = 60;
parent->m_drv->SetSleepTime(value);
}
}
void CA3::OnBnClickedBtngetsleeptime()
{
UpdateSleepTime(true);
}
void CA3::OnBnClickedBtnsetsleeptime()
{
UpdateSleepTime(false);
}

View File

@ -20,4 +20,23 @@ protected:
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
afx_msg void OnBnClickedBtngetsp();
afx_msg void OnBnClickedBtnsetsp();
afx_msg void OnBnClickedBtngetgraysp();
afx_msg void OnBnClickedBtnsetgraysp();
afx_msg void OnBnClickedBtngetuvsp();
afx_msg void OnBnClickedBtnsetuvsp();
afx_msg void OnBnClickedBtngetcolorsp();
afx_msg void OnBnClickedBtnsetcolorsp();
private:
void OnGetOrSetSp(bool get, int type);
public:
afx_msg
void OnGetOrSetSleepTime(bool get, int type);
void UpdateSleepTime(bool get);
void OnBnClickedBtngetsleeptime();
afx_msg void OnBnClickedBtnsetsleeptime();
afx_msg void OnBnClickedBtngetcolorsp2();
afx_msg void OnBnClickedBtnsetcolorsp2();
};

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,10 @@
#include "Config.h"
#include "DefHSStructure.h"
#include "afxwin.h"
#include "PublicFunc.h"
#include <vector>
#include "JsonConfig.h"
#include <functional>
// CA4 对话框
#define INI_FILE_NAME "./HuaGoScan.ini"
@ -13,19 +17,8 @@ class CA4 : public CDialog
public:
CA4(CWnd* pParent = NULL); // 标准构造函数
virtual ~CA4();
CConfig m_Cfg;
void default0param();
void default1param();
void default2param();
void default3param();
void updateA4Config(int *pValues);
void updateA4Config(CaptureParams& pValues);
void LoadCfg();
void SaveNewParam(int iIndex);
void WriteParamFile();
// 对话框数据
enum { IDD = IDD_A4_DIALOG };
@ -36,56 +29,49 @@ protected:
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
void SetCallBack(std::function<void(int option, void* data)> t_call);
void EnableItem(bool enable);
void SendCorrectParam();
CorrectParam params;
CaptureParams jsonparams;
std::vector<int> Exposures = { IDC_tbxFRExposure ,IDC_tbxFGExposure ,IDC_tbxFBExposure ,IDC_tbxBRExposure ,IDC_tbxBGExposure ,IDC_tbxBBExposure };
std::vector<int> Gains = { IDC_tbxF1Gain ,IDC_tbxF2Gain ,IDC_tbxF3Gain ,IDC_tbxF4Gain ,IDC_tbxF5Gain ,IDC_tbxF6Gain ,IDC_tbxB1Gain ,IDC_tbxB2Gain ,IDC_tbxB3Gain ,IDC_tbxB4Gain ,IDC_tbxB5Gain ,IDC_tbxB6Gain };
//std::vector<int> Gains = { IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain ,IDC_tbxF3Gain };
FlatCorrection m_sFlatCorrection;
std::vector<int> Offsets = { IDC_tbxF1Offset ,IDC_tbxF2Offset ,IDC_tbxF3Offset ,IDC_tbxF4Offset ,IDC_tbxF5Offset ,IDC_tbxF6Offset ,IDC_tbxB1Offset ,IDC_tbxB2Offset ,IDC_tbxB3Offset ,IDC_tbxB4Offset ,IDC_tbxB5Offset ,IDC_tbxB6Offset };
int m_iLastIndex;
int m_iSelIndex;
UINT m_tbxFRExposure;
UINT m_tbxFGExposure;
UINT m_tbxFBExposure;
UINT m_tbxF1Gain;
UINT m_tbxF2Gain;
UINT m_tbxF3Gain;
UINT m_tbxF4Gain;
UINT m_tbxF5Gain;
UINT m_tbxF6Gain;
UINT m_tbxF1Offset;
UINT m_tbxF2Offset;
UINT m_tbxF3Offset;
UINT m_tbxF4Offset;
UINT m_tbxF5Offset;
UINT m_tbxF6Offset;
UINT m_tbxBRExposure;
UINT m_tbxBGExposure;
UINT m_tbxBBExposure;
UINT m_tbxB1Gain;
UINT m_tbxB2Gain;
UINT m_tbxB3Gain;
UINT m_tbxB4Gain;
UINT m_tbxB5Gain;
UINT m_tbxB6Gain;
UINT m_tbxB1Offset;
UINT m_tbxB2Offset;
UINT m_tbxB3Offset;
UINT m_tbxB4Offset;
UINT m_tbxB5Offset;
UINT m_tbxB6Offset;
afx_msg void OnCbnSelChangeA4FlatModel();
CComboBox m_A4FlatModel;
UINT m_tbxAGain;
UINT m_tbxBGain;
UINT m_tbxAOffset;
UINT m_tbxBOffset;
afx_msg void OnDeltaposSpinAgain(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDeltaposSpinAoffset(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDeltaposSpinBgain(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDeltaposSpinBoffset(NMHDR *pNMHDR, LRESULT *pResult);
void ADownGain();
void AUpGain();
void BDownGain();
void BUpGain();
void ADownOffset();
void AUpOffset();
void BDownOffset();
void BUpOffset();
CButton m_GetSerial;
CButton m_SetSerial;
CButton m_AutoGenSerial;
CButton m_GetVid;
CButton m_SetVid;
CButton m_Reboot;
JsonConfig jsonConfig;
private:
std::function<void(int option, void* data)> m_func;
private:
afx_msg void OnCbnSelChangeA4FlatModel();
afx_msg void OnBnClickedBtnReboot();
afx_msg void OnBnClickedBtnSetvidpid();
afx_msg void OnBnClickedBtnGetvidpid();
afx_msg void OnBnClickedBtngetSerial();
afx_msg void OnBnClickedBtnGenserial();
afx_msg void OnBnClickedBtnSetSerial();
public:
afx_msg void OnBnClickedBtnGethor();
afx_msg void OnBnClickedBtnGetver();
afx_msg void OnBnClickedBtnSethor();
afx_msg void OnBnClickedBtnSetver();
afx_msg void OnBnClickedBtngetVersion();
afx_msg void OnBnClickedBtnSetVersion();
afx_msg void OnEnChangetbxserial();
afx_msg void OnBnClickedBtnGetexpos();
afx_msg void OnBnClickedBtnSetexpos();
afx_msg void OnBnClickedBtnaup();
afx_msg void OnBnClickedBtnadown();
afx_msg void OnBnClickedBtnbup();
afx_msg void OnBnClickedBtnbdown();
void UpdateGains(int id, bool get);
};

View File

@ -2,38 +2,31 @@
#include <mutex>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <exception>
template <typename T>
class BlockingQueue
{
private:
BlockingQueue(const BlockingQueue& rhs);
BlockingQueue& operator =(const BlockingQueue& rhs);
BlockingQueue(const BlockingQueue &rhs);
BlockingQueue &operator=(const BlockingQueue &rhs);
mutable std::mutex _mutex;
std::condition_variable _condvar;
std::deque<T> _queue;
volatile bool isShutDown = false;
bool isShutDown = false;
T tRet;
public:
BlockingQueue()
: _mutex()
, _condvar()
, _queue()
: _mutex(), _condvar(), _queue()
{
}
~BlockingQueue()
{
ShutDown();
}
void Clear()
{
std::lock_guard<std::mutex> lock(_mutex);
_condvar.notify_all();
_queue.clear();
std::cout << "blocking queue release" << std::endl;
}
void ShutDown()
@ -51,8 +44,11 @@ public:
void Put(const T task)
{
std::lock_guard<std::mutex> lock(_mutex);
if (!isShutDown) {
_queue.push_back(task);
if (!isShutDown)
{
{
_queue.push_back(task);
}
_condvar.notify_all();
}
}
@ -64,7 +60,9 @@ public:
_condvar.wait(lock);
if (isShutDown || _queue.empty())
{
return tRet;
}
T front(_queue.front());
_queue.pop_front();
@ -79,15 +77,28 @@ public:
_condvar.wait(lock);
if (isShutDown || _queue.empty())
{
return tRet;
}
T front(_queue.front());
return front;
}
size_t Size() const
{
std::lock_guard<std::mutex> lock(_mutex);
return _queue.size();
}
void Clear()
{
std::unique_lock<std::mutex> lock(_mutex);
if (_queue.size() <= 0)
return;
if (_queue.size()>0)
{
_queue.clear();
}
}
};

View File

@ -2,20 +2,53 @@
#include "CVISON.h"
#include "HuaGoCorrect.h"
#include "afxdialogex.h"
#include "HuaGoCorrectDlg.h"
// CA3 对话框
using namespace cv;
IMPLEMENT_DYNAMIC(CVISON, CDialog)
CVISON::CVISON(CWnd* pParent /*=NULL*/)
: CDialog(CVISON::IDD, pParent)
{
m_run = true;
m_auireable = false;
m_updateimgshow = std::thread(&CVISON::showfun, this);
}
CVISON::~CVISON()
{
if (m_updateimgshow.joinable())
{
m_auireable = false;
m_run = false;
m_updateimgshow.join();
}
}
void CVISON::DrawPicture(CString path)
{
CImage img;
img.Load(path);
CRect rectf;
int cx = img.GetWidth();
int cy = img.GetHeight();
if (cx == 0 || cy == 0)
return;
CWnd* pWnd = GetDlgItem(IDC_PIC);
pWnd->GetClientRect(&rectf);
CDC* pDC = pWnd->GetDC();
SetStretchBltMode(pDC->m_hDC, STRETCH_HALFTONE);
CPoint pos = rectf.TopLeft();
rectf = CRect(pos, CSize(630,535));
img.Draw(pDC->m_hDC, rectf);
ReleaseDC(pDC);
img.Destroy();
}
void CVISON::SetCallBack(std::function<void(bool stoped, int num)> onstop)
{
m_onStop = onstop;
}
void CVISON::DoDataExchange(CDataExchange* pDX)
@ -25,6 +58,8 @@ void CVISON::DoDataExchange(CDataExchange* pDX)
BEGIN_MESSAGE_MAP(CVISON, CDialog)
ON_BN_CLICKED(IDC_BTN_PREPAGE, &CVISON::OnBnClickedBtnPrepage)
ON_BN_CLICKED(IDC_BTN_NEXT, &CVISON::OnBnClickedBtnNext)
END_MESSAGE_MAP()
@ -41,3 +76,122 @@ BOOL CVISON::OnInitDialog()
// 异常: OCX 属性页应返回 FALSE
}
void CVISON::MatToCImage(cv::Mat& mat, CImage& cimage)
{
if (0 == mat.total())
{
return;
}
int nChannels = mat.channels();
if ((1 != nChannels) && (3 != nChannels))
{
return;
}
int nWidth = mat.cols;
int nHeight = mat.rows;
//重建cimage
cimage.Destroy();
cimage.Create(nWidth, nHeight, 8 * nChannels);
//拷贝数据
uchar* pucRow;//指向数据区的行指针
uchar* pucImage = (uchar*)cimage.GetBits();//指向数据区的指针
int nStep = cimage.GetPitch();//每行的字节数,注意这个返回值有正有负
if (1 == nChannels)//对于单通道的图像需要初始化调色板
{
RGBQUAD* rgbquadColorTable;
int nMaxColors = 256;
rgbquadColorTable = new RGBQUAD[nMaxColors];
cimage.GetColorTable(0, nMaxColors, rgbquadColorTable);
for (int nColor = 0; nColor < nMaxColors; nColor++)
{
rgbquadColorTable[nColor].rgbBlue = (uchar)nColor;
rgbquadColorTable[nColor].rgbGreen = (uchar)nColor;
rgbquadColorTable[nColor].rgbRed = (uchar)nColor;
}
cimage.SetColorTable(0, nMaxColors, rgbquadColorTable);
delete[]rgbquadColorTable;
}
for (int nRow = 0; nRow < nHeight; nRow++)
{
pucRow = (mat.ptr<uchar>(nRow));
for (int nCol = 0; nCol < nWidth; nCol++)
{
if (1 == nChannels)
{
*(pucImage + nRow * nStep + nCol) = pucRow[nCol];
}
else if (3 == nChannels)
{
for (int nCha = 0; nCha < 3; nCha++)
{
*(pucImage + nRow * nStep + nCol * 3 + nCha) = pucRow[nCol * 3 + nCha];
}
}
}
}
}
void CVISON::OnBnClickedBtnPrepage()
{
// TODO: 在此添加控件通知处理程序代码
imageindex--;
if (imageindex < 0)
imageindex = 0;
if (m_path.size() > 0)
{
DrawPicture(m_path[imageindex]);
}
}
void CVISON::OnBnClickedBtnNext()
{
// TODO: 在此添加控件通知处理程序代码
imageindex++;
if (imageindex >= m_path.size())
imageindex = m_path.size() - 1;
if (m_path.size() > 0)
{
DrawPicture(m_path[imageindex]);
}
}
void CVISON::SetEnableShow(bool show)
{
m_auireable = show;
aquiredimgindx = 0;
parent = (CHuaGoCorrectDlg*)GetParent();
}
void CVISON::showfun()
{
while (m_run)
{
if (m_auireable)
{
if (parent)
{
std::string path;
auto ret = ((CHuaGoCorrectDlg*)parent)->m_drv->aquire_image(path, 0);
if (ret != -1)
{
imageindex++;
aquiredimgindx++;
CString cPath(path.c_str());
m_path.push_back(cPath);
m_onStop(false, aquiredimgindx);
DrawPicture(cPath);
}
else
{
m_auireable = false;
m_onStop(true,0);
}
}
}
else
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}

View File

@ -1,5 +1,9 @@
#pragma once
#include "resource.h"
#include <opencv2\opencv.hpp>
#include <vector>
#include <thread>
#include <functional>
//cvision对话框
@ -12,10 +16,27 @@ public:
// 对话框数据
enum { IDD = IDD_VISION_DIALOG };
void DrawPicture(CString path);
void SetCallBack(std::function<void(bool stoped, int num)> onstop);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
virtual BOOL OnInitDialog();
virtual BOOL OnInitDialog();
void MatToCImage(cv::Mat& mat, CImage& cimage);
public:
afx_msg void OnBnClickedBtnPrepage();
afx_msg void OnBnClickedBtnNext();
void SetEnableShow(bool show);
private:
void showfun();
private:
std::vector<CString> m_path;
volatile int imageindex = 0;
volatile int aquiredimgindx = 0;
volatile bool m_auireable;
volatile bool m_run;
std::thread m_updateimgshow;
void* parent;
std::function<void(bool stoped,int num)> m_onStop;
};

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30621.155
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HuaGoCorrect_V3.0", "HuaGoCorrect.vcxproj", "{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Debug|x64.ActiveCfg = Debug|x64
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Debug|x64.Build.0 = Debug|x64
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Debug|x86.ActiveCfg = Debug|Win32
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Debug|x86.Build.0 = Debug|Win32
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Release|x64.ActiveCfg = Release|x64
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Release|x64.Build.0 = Release|x64
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Release|x86.ActiveCfg = Release|Win32
{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B764F5EE-C301-4B09-84ED-7E482F7F1D0F}
EndGlobalSection
EndGlobal

View File

@ -22,7 +22,7 @@
<ProjectGuid>{988CC4D3-44EC-4A9D-AC05-B2AF0EA48E75}</ProjectGuid>
<RootNamespace>HuaGoCorrect</RootNamespace>
<Keyword>MFCProj</Keyword>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformVersion>10.0.19041.0</WindowsTargetPlatformVersion>
<ProjectName>HuaGoCorrect_V3.0</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
@ -31,7 +31,7 @@
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
<PlatformToolset>v141</PlatformToolset>
<PlatformToolset>v142</PlatformToolset>
<VCToolsVersion>
</VCToolsVersion>
</PropertyGroup>
@ -41,7 +41,7 @@
<CharacterSet>MultiByte</CharacterSet>
<UseOfMfc>Dynamic</UseOfMfc>
<PlatformToolset>v142</PlatformToolset>
<VCToolsVersion>14.20.27508</VCToolsVersion>
<VCToolsVersion>14.28.29910</VCToolsVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
@ -77,13 +77,14 @@
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>./pub/opencv/include;$(IncludePath)</IncludePath>
<TargetName>HGScannerTool</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<TargetName>HGScannerTool</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
@ -93,14 +94,15 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>.\pub\opencv\bin;.\pub\external\bin;.\pub\opencv\include;.\pub\external\include;.\pub\ddk;.\pub\json;D:\local\boost_1_71_0_b1_rc1;D:\OpenCV2.4.10\opencv\build\include\opencv;D:\OpenCV2.4.10\opencv\build\include\opencv2</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>.\pub\external\lib;.\pub\opencv\lib;D:\local\boost_1_71_0_b1_rc1\lib32-msvc-14.1</AdditionalLibraryDirectories>
<AdditionalDependencies>./pub/external/lib/turbojpeg.lib;./pub/opencv/lib/opencv_world346d.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>turbojpeg.lib;opencv_core2410d.lib;opencv_highgui2410d.lib;
opencv_imgproc2410d.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
@ -146,7 +148,7 @@ opencv_imgproc2410d.lib;%(AdditionalDependencies)</AdditionalDependencies>
<FunctionLevelLinking>
</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>.\pub\opencv\bin;.\pub\external\bin;.\pub\opencv\include;.\pub\external\include;.\pub\ddk;.\pub\json;D:\local\boost_1_71_0_b1_rc1;D:\OpenCV2.4.10\opencv\build\include\opencv;D:\OpenCV2.4.10\opencv\build\include\opencv2</AdditionalIncludeDirectories>
<WholeProgramOptimization>false</WholeProgramOptimization>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
@ -214,76 +216,50 @@ opencv_imgproc2410.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ClInclude Include="A3.h" />
<ClInclude Include="A4.h" />
<ClInclude Include="BlockingQueue.h" />
<ClInclude Include="CIS.h" />
<ClInclude Include="commondef.h" />
<ClInclude Include="Config.h" />
<ClInclude Include="ConfigParam.h" />
<ClInclude Include="CVISON.h" />
<ClInclude Include="DefHSCommon.h" />
<ClInclude Include="DefHSStructure.h" />
<ClInclude Include="filetools.h" />
<ClInclude Include="gscan3399.h" />
<ClInclude Include="gscn_drv.h" />
<ClInclude Include="HuaGoCorrect.h" />
<ClInclude Include="HuaGoCorrectDlg.h" />
<ClInclude Include="ImageApply.h" />
<ClInclude Include="ImageApplyAdjustColors.h" />
<ClInclude Include="ImageApplyAutoCrop.h" />
<ClInclude Include="ImageApplyBWBinaray.h" />
<ClInclude Include="ImageApplyChannel.h" />
<ClInclude Include="ImageApplyCrop.h" />
<ClInclude Include="ImageApplyDiscardBlank.h" />
<ClInclude Include="ImageApplyHeaders.h" />
<ClInclude Include="ImageApplyResize.h" />
<ClInclude Include="ImageApplyRotation.h" />
<ClInclude Include="ImageApplySharpen.h" />
<ClInclude Include="ImageApplyTextureRemoval.h" />
<ClInclude Include="ImageApplyThreshold.h" />
<ClInclude Include="ImageMatQueue.h" />
<ClInclude Include="imageprocess.h" />
<ClInclude Include="ImageProcess_Public.h" />
<ClInclude Include="imgprocdefs.h" />
<ClInclude Include="IScanner.h" />
<ClInclude Include="IUsb.h" />
<ClInclude Include="JpegBuffer.h" />
<ClInclude Include="jpeglib.h" />
<ClInclude Include="json.h" />
<ClInclude Include="json.hpp" />
<ClInclude Include="JsonConfig.h" />
<ClInclude Include="localTime.h" />
<ClInclude Include="MutexEx.h" />
<ClInclude Include="m_Dis.h" />
<ClInclude Include="PublicFunc.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="scn_config.h" />
<ClInclude Include="scn_usb.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
<ClInclude Include="ThreadPool.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="A3.cpp" />
<ClCompile Include="A4.cpp" />
<ClCompile Include="CIS.cpp" />
<ClCompile Include="Config.cpp" />
<ClCompile Include="ConfigParam.cpp" />
<ClCompile Include="CVISON.cpp" />
<ClCompile Include="gscan3399.cpp" />
<ClCompile Include="gscn_drv.cpp" />
<ClCompile Include="HuaGoCorrect.cpp" />
<ClCompile Include="HuaGoCorrectDlg.cpp" />
<ClCompile Include="ImageApply.cpp" />
<ClCompile Include="ImageApplyAdjustColors.cpp" />
<ClCompile Include="ImageApplyAutoCrop.cpp" />
<ClCompile Include="ImageApplyBWBinaray.cpp" />
<ClCompile Include="ImageApplyChannel.cpp" />
<ClCompile Include="ImageApplyCrop.cpp" />
<ClCompile Include="ImageApplyDiscardBlank.cpp" />
<ClCompile Include="ImageApplyResize.cpp" />
<ClCompile Include="ImageApplyRotation.cpp" />
<ClCompile Include="ImageApplySharpen.cpp" />
<ClCompile Include="ImageApplyTextureRemoval.cpp" />
<ClCompile Include="ImageApplyThreshold.cpp" />
<ClCompile Include="ImageMatQueue.cpp" />
<ClCompile Include="imageprocess.cpp" />
<ClCompile Include="ImageProcess_Public.cpp" />
<ClCompile Include="JpegBuffer.cpp" />
<ClCompile Include="jpeglib.cpp" />
<ClCompile Include="JsonConfig.cpp" />
<ClCompile Include="m_Dis.cpp" />
<ClCompile Include="PublicFunc.cpp" />
<ClCompile Include="scn_config.cpp" />
<ClCompile Include="scn_usb.cpp" />
@ -297,9 +273,6 @@ opencv_imgproc2410.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ItemGroup>
<ResourceCompile Include="HuaGoCorrect.rc" />
</ItemGroup>
<ItemGroup>
<Text Include="imgprc.txt" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>

View File

@ -22,9 +22,6 @@
<Filter Include="源文件\USB通信">
<UniqueIdentifier>{4947e7b4-3e27-433f-a80c-23bc7a009204}</UniqueIdentifier>
</Filter>
<Filter Include="头文件\文件处理">
<UniqueIdentifier>{c3c1bbc0-cb36-414d-bab7-7d40e277918e}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
@ -105,65 +102,29 @@
<ClInclude Include="CVISON.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BlockingQueue.h">
<Filter>头文件</Filter>
<ClInclude Include="IUsb.h">
<Filter>源文件\USB通信</Filter>
</ClInclude>
<ClInclude Include="CIS.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="m_Dis.h">
<ClInclude Include="json.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="JsonConfig.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="json.h">
<ClInclude Include="BlockingQueue.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ImageApply.h">
<Filter>头文件\文件处理</Filter>
<ClInclude Include="IScanner.h">
<Filter>头文件\USB通信</Filter>
</ClInclude>
<ClInclude Include="ImageApplyAdjustColors.h">
<Filter>头文件\文件处理</Filter>
<ClInclude Include="commondef.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ImageApplyAutoCrop.h">
<Filter>头文件\文件处理</Filter>
<ClInclude Include="gscan3399.h">
<Filter>头文件\USB通信</Filter>
</ClInclude>
<ClInclude Include="ImageApplyBWBinaray.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyChannel.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyCrop.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyDiscardBlank.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyHeaders.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyResize.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyRotation.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplySharpen.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyTextureRemoval.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageApplyThreshold.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="ImageProcess_Public.h">
<Filter>头文件\文件处理</Filter>
</ClInclude>
<ClInclude Include="imgprocdefs.h">
<Filter>头文件\文件处理</Filter>
<ClInclude Include="ThreadPool.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
@ -215,53 +176,11 @@
<ClCompile Include="CVISON.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="CIS.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="m_Dis.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="JsonConfig.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="ImageApply.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="ImageApplyAdjustColors.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyAutoCrop.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyBWBinaray.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyChannel.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyCrop.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyDiscardBlank.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyResize.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyRotation.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplySharpen.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyTextureRemoval.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageApplyThreshold.cpp">
<Filter>头文件\文件处理</Filter>
</ClCompile>
<ClCompile Include="ImageProcess_Public.cpp">
<Filter>头文件\文件处理</Filter>
<ClCompile Include="gscan3399.cpp">
<Filter>源文件\USB通信</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
@ -269,9 +188,4 @@
<Filter>资源文件</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<Text Include="imgprc.txt">
<Filter>头文件\文件处理</Filter>
</Text>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@ -6,42 +6,41 @@
#include "afxcmn.h"
#include "HuaGoCorrect.h"
#include "DefHSCommon.h"
#include "gscn_drv.h"
#include "IScanner.h"
#include "Config.h"
#include "twain.h"
#include "A3.h"
#include "A4.h"
#include "CIS.h"
#include "m_Dis.h"
#include "ConfigParam.h"
#include "afxwin.h"
#include "CVISON.h"
#include <memory>
#include "ImageApply.h"
#include "ImageApplyAdjustColors.h"
#include "ImageApplyAutoCrop.h"
#include "ImageApplyBWBinaray.h"
#include "ImageApplyChannel.h"
#include "ImageApplyCrop.h"
#include "ImageApplyDiscardBlank.h"
#include "ImageApplyResize.h"
#include "ImageApplyRotation.h"
#include "ImageApplySharpen.h"
using namespace std;
#include "scn_usb.h"
#include "JsonConfig.h"
#define WM_MYMESSAGE (WM_USER+100)
enum TwSS : ushort
union HG_ScanConfiguration
{
A4 = 1,
A3 = 11,
USStatement = 52
struct
{
unsigned int pageSize : 5;
unsigned int isColor : 1;
unsigned int dpi : 2;
unsigned int doubleFeeded : 1;
unsigned int enableUV : 1;
unsigned int enableLed : 1;
unsigned int reversed1 : 6;
unsigned int isCorrect : 1;
unsigned int dstHeight : 8;
unsigned int reversed2 : 6;
} params;
unsigned int value;
};
// CHuaGoCorrectDlg 对话框
class CHuaGoCorrectDlg : public CDialogEx
{
// ¹¹Ôì
// ¹¹Ôì
public:
CHuaGoCorrectDlg(CWnd* pParent = NULL); // 标准构造函数
@ -52,158 +51,68 @@ public:
bool ls_flat;
int papercount;
int m_iPicIndex;
int m_iflatIndex;
int m_iDpiIndex;
int m_iColorIndex;
int iAMaxStep;
int iAMiddleStep;
int iAMinStep;
int iBMaxStep;
int iBMiddleStep;
int iBMinStep;
int iAERMaxStep;
int iAERMiddleStep;
int iAERMinStep;
int iAEGMaxStep;
int iAEGMiddleStep;
int iAEGMinStep;
int iAEBMaxStep;
int iAEBMiddleStep;
int iAEBMinStep;
int iBERMaxStep;
int iBERMiddleStep;
int iBERMinStep;
int iBEGMaxStep;
int iBEGMiddleStep;
int iBEGMinStep;
int iBEBMaxStep;
int iBEBMiddleStep;
int iBEBMinStep;
int iGainStep;
int n_hour;
int n_minute;
int n_second;
int usb_vid;
int usb_pid;
BOOL b_review;
BOOL b_suspend;
CConfig m_Cfg;
CA3 m_A3Dlg;
CA4 m_A4Dlg;
CIS m_CISDlg;
m_Dis m_dis;
CVISON m_VisonDlg;
CA3 m_A3dlg;
CConfigParam m_ConfigParam;
shared_ptr<GScn_Drv> m_drv;
std::shared_ptr<IScanner> m_drv;
CRect tabRect; // 标签控件客户区的位置和大小
void Scan();
void RefreshTabChange();
int Mat2CImage(Mat *mat, CImage &img);
cv::Mat m_matFImage;
cv::Mat m_matBImage;
int Version_id[5][2] = { {0x064b,0x7823},{0x3072,0x0100},{0x3072 ,0x0200},{0x3072 ,0x0300},{0x3072 ,0x0400} };
void ShowFrontImage(int index);
void ShowBackImage(int index);
void A3ParamSet();
void A4ParamSet();
void intToByte(UINT *src,byte *bytes,int iLength);
void bytesToInt(byte* bytes,UINT *des, int iLength);
void CorrectBlackImage();
void CorrectWhiteImage();
void CorrectWhiteGain();
void CorrectFinish();
void WriteLog(CString msg);
void CyclePro();
void CorrectCMDUpdate();
void CorrectEndUpdate();
void ConfigParamUpdate();
void InitButton();
void FSongleCorrect();
bool bABlackImage;
bool bBBlackImage;
bool bAGrayWhiteImage;
bool bBGrayWhiteImage;
bool bAColorWhiteImage;
bool bAcolr;
bool bAcolg;
bool bAcolb;
bool bBColorWhiteImage;
bool bBcolr;
bool bBcolg;
bool bBcolb;
bool bAGrayWhiteGain;
bool bBGrayWhiteGain;
bool bAColorWhiteGain;
bool bBColorWhiteGain;
std::vector<std::shared_ptr<CImageApply>> m_iaList;
protected:
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
HANDLE m_hThread;
BOOL m_bExit;
void CorrectThreadFunc();
static unsigned WINAPI CorrectThread(void* pCorrect);
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void EnableUIItem(bool enbale);
bool RefreshUSBList();
void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CTabCtrl m_tab;
afx_msg BOOL PreCreateWindow(CREATESTRUCT& cs);
afx_msg void OnTcnSelChangeTab(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedCheckparamset();
afx_msg void OnTcnSelChangeTab(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnBnClickedCheckparamset();
afx_msg void OnBnClickedCheckparamread();
void UpdateList(CONFIGPARAMS configParams, bool canUpdate);
afx_msg void OnBnClickedBtnFlat();
CButton m_pBlack;
CButton m_pWExposure;
CButton m_pWGain;
afx_msg void OnBnClickedBtnFlatm();
CCriticalSection m_deviceLock;
virtual void OnCancel();
BOOL m_bPause;
BOOL m_bParamError;
afx_msg void OnBnClickedBtnBlackflat();
afx_msg void OnBnClickedBtnExflat();
afx_msg void OnBnClickedBtnGainflat();
afx_msg void OnBnClickedBtnContinue();
afx_msg void OnBnClickedBtnPause();
CComboBox m_ComboxDpi;
CComboBox m_ComboxColor;
CComboBox m_Usbs;
afx_msg void OnCbnSelChangeDpi();
afx_msg void OnCbnSelChangeColor();
afx_msg void OnBnClickedConfirm();
afx_msg void OnBnClickedBtnParamcfg();
CButton m_check_FpgaFlat;
CButton m_A4Scanner;
CString s_hour;
CString s_minute;
CString s_second;
afx_msg void OnBnClickedStopScan();
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg LRESULT OnMyMessage(/*HWND hWnd, UINT Msg,*/ WPARAM w,LPARAM l);
CButton close_butten;
CComboBox twss;
CComboBox duplex;
CComboBox Version;
afx_msg void OnCbnSelchangeCombo1();
//afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnBnClickedBtnSelectfile();
afx_msg void OnBnClickedBtnUpdate();
afx_msg void OnBnClickedBtnRefresh();
afx_msg void OnCbnSelchangeCmbUsbs();
afx_msg void OnBnClickedBtnstart();
afx_msg void OnBnClickedBtnstop();
private:
std::string updateFilePath;
std::thread m_updateThread;
void updatefunc();
};

View File

@ -1,131 +1,131 @@
[ColorCorrection]
;²ÊɫУÕýģʽ
FRExposure=442
FGExposure=629
FBExposure=998
F1Gain=45
F2Gain=45
F3Gain=45
F4Gain=45
F5Gain=45
F6Gain=45
F1Offset=122
F2Offset=122
F3Offset=122
F4Offset=122
F5Offset=122
F6Offset=122
BRExposure=416
BGExposure=682
BBExposure=792
B1Gain=45
B2Gain=45
B3Gain=45
B4Gain=45
B5Gain=45
B6Gain=45
B1Offset=120
B2Offset=120
B3Offset=120
B4Offset=120
B5Offset=120
B6Offset=120
[ColorFlat]
;彩色
FRExposure=402
FGExposure=649
FBExposure=958
F1Gain=60
F2Gain=60
F3Gain=60
F4Gain=60
F5Gain=60
F6Gain=60
F1Offset=122
F2Offset=122
F3Offset=122
F4Offset=122
F5Offset=122
F6Offset=122
BRExposure=376
BGExposure=702
BBExposure=752
B1Gain=60
B2Gain=60
B3Gain=60
B4Gain=60
B5Gain=60
B6Gain=60
B1Offset=120
B2Offset=120
B3Offset=120
B4Offset=120
B5Offset=120
B6Offset=120
[GrayCorrection]
;灰度校正模式
FRExposure=271
FGExposure=271
FBExposure=271
F1Gain=30
F2Gain=30
F3Gain=30
FRExposure=524
FGExposure=812
FBExposure=1100
F1Gain=444
F2Gain=754
F3Gain=990
F4Gain=30
F5Gain=30
F6Gain=30
F1Offset=122
F2Offset=122
F3Offset=122
F4Offset=122
F5Offset=122
F6Offset=122
BRExposure=256
BGExposure=256
BBExposure=256
B1Gain=30
B2Gain=30
B3Gain=30
B4Gain=30
B5Gain=30
B6Gain=30
B1Offset=120
B2Offset=120
B3Offset=120
B4Offset=120
B5Offset=120
B6Offset=120
[GrayFlat]
;灰度
FRExposure=271
FGExposure=271
FBExposure=271
F1Gain=47
F2Gain=47
F3Gain=47
F1Offset=30
F2Offset=30
F3Offset=30
F4Offset=30
F5Offset=30
F6Offset=30
BRExposure=30
BGExposure=30
BBExposure=30
B1Gain=123
B2Gain=123
B3Gain=123
B4Gain=123
B5Gain=123
B6Gain=123
B1Offset=118
B2Offset=118
B3Offset=118
B4Offset=118
B5Offset=118
B6Offset=118
[ColorFlat]
;²ÊÉ«
FRExposure=289
FGExposure=289
FBExposure=289
F1Gain=257
F2Gain=257
F3Gain=257
F4Gain=30
F5Gain=30
F6Gain=30
F1Offset=30
F2Offset=30
F3Offset=30
F4Offset=30
F5Offset=30
F6Offset=30
BRExposure=30
BGExposure=30
BBExposure=30
B1Gain=120
B2Gain=120
B3Gain=120
B4Gain=120
B5Gain=120
B6Gain=120
B1Offset=115
B2Offset=115
B3Offset=115
B4Offset=115
B5Offset=115
B6Offset=115
[GrayCorrection]
;»Ò¶ÈУÕýģʽ
FRExposure=524
FGExposure=812
FBExposure=1100
F1Gain=444
F2Gain=754
F3Gain=990
F4Gain=47
F5Gain=47
F6Gain=47
F1Offset=122
F2Offset=122
F3Offset=122
F4Offset=122
F5Offset=122
F6Offset=122
BRExposure=256
BGExposure=256
BBExposure=256
B1Gain=47
B2Gain=47
B3Gain=47
B4Gain=47
B5Gain=47
B6Gain=47
B1Offset=120
B2Offset=120
B3Offset=120
B4Offset=120
B5Offset=120
B6Offset=120
F1Offset=47
F2Offset=47
F3Offset=47
F4Offset=47
F5Offset=47
F6Offset=47
BRExposure=47
BGExposure=47
BBExposure=47
B1Gain=123
B2Gain=123
B3Gain=123
B4Gain=123
B5Gain=123
B6Gain=123
B1Offset=118
B2Offset=118
B3Offset=118
B4Offset=118
B5Offset=118
B6Offset=118
[GrayFlat]
;»Ò¶È
FRExposure=289
FGExposure=289
FBExposure=289
F1Gain=257
F2Gain=257
F3Gain=257
F4Gain=47
F5Gain=47
F6Gain=47
F1Offset=47
F2Offset=47
F3Offset=47
F4Offset=47
F5Offset=47
F6Offset=47
BRExposure=47
BGExposure=47
BBExposure=47
B1Gain=120
B2Gain=120
B3Gain=120
B4Gain=120
B5Gain=120
B6Gain=120
B1Offset=115
B2Offset=115
B3Offset=115
B4Offset=115
B5Offset=115
B6Offset=115
[GrayBlack]
;»Ò¶È°µ³¡
AGMaxStep=255
@ -149,33 +149,6 @@ BCBMinStep=0
[GainStep]
;ÔöÒæ²½³¤
ABGainStep=24
[ObjValue]
;目标值
objvalue_x1=0
objvalue_x2=0
objvalue_x3=0
objvalue_y1=0
objvalue_y2=0
objvalue_y3=0
[LimitOffset]
;偏差值
limitoffset_x1=0
limitoffset_x2=0
limitoffset_x3=0
limitoffset_y1=0
limitoffset_y2=0
limitoffset_y3=0
[CIS]
;cis检测设置
channle=1
total_up=28
total_low=10
total_area_up=298
total_area_low=300
[USB]
;USB设备VIDPID
VID=0x064b
PID=0x7823
Version_num=1

63
HuaGoCorrect/IScanner.h Normal file
View File

@ -0,0 +1,63 @@
#pragma once
#include "ImageMatQueue.h"
#include "IUsb.h"
#include "commondef.h"
#include <functional>
class IScanner
{
public:
virtual ~IScanner() {};
virtual void open(int vid, int pid, int index)=0;
virtual int aquire_image(std::string& image, int num)=0;
virtual bool IsConnected() = 0;
virtual std::string GetFWVersion() = 0;
virtual void SetFWVersion() = 0;
virtual std::string GetSerialNum() = 0;
virtual void SetSerialNum(std::string serial) = 0;
virtual void SetRatio(int tyepe, int ration) = 0;
virtual void GetRatio(int type, int& ratio) = 0;
virtual void Reboot() = 0;
virtual void PowerOff() = 0;
virtual bool is_scan() = 0;
virtual bool Get_Scanner_PaperOn() = 0;
virtual void Config_Scanner(HGScanConfig config) = 0;
virtual void Scanner_StartScan(unsigned short count) = 0;
virtual void Stop_scan() = 0;
virtual void ResetScanner() = 0;
virtual bool Get_IsImageQueueEmpty() = 0;
virtual void reset() = 0;
virtual void run() = 0;
virtual void ActiveteUSB() = 0;
virtual int GetScanNum() = 0;
virtual void ClrRollerNum() = 0;
virtual void ClrScanNum() = 0;
virtual void SendFlatData(CorrectParam param, int index) = 0;
virtual CaptureParams GetFlatData() = 0;
virtual void StartFlat(bool iscolor) = 0;
virtual void DevStateChange() = 0;
virtual int getMatSum() = 0;
virtual void close() = 0;
virtual void GetExpose(int& Aside, int& Bside) = 0;
virtual void SetExpose(int aside, int bside) = 0;
virtual void GetSptime(int type, int& time) = 0;
virtual void SetSptime(int type, int time) = 0;
virtual void GetSleepTime(int& sleeptime) = 0;
virtual void SetSleepTime(int sleeptime) = 0;
virtual bool Updata(std::string filename, std::function<void(long, long)> func) = 0;
void SetPath(std::string csFilePath)
{
csPath = csFilePath;
}
std::string GetPath()
{
return csPath;
}
std::shared_ptr<IUsb> m_usb;
//protected:
ImageMatQueue m_pImages;
HWND h;
std::string csPath;
};

18
HuaGoCorrect/IUsb.h Normal file
View File

@ -0,0 +1,18 @@
#pragma once
typedef void(*usbhotplug_callback)(bool isleft, void* userdata);
class IUsb
{
public:
virtual ~IUsb() {}
virtual bool open() = 0;
virtual void set_usbhotplug_callback(usbhotplug_callback callback = nullptr, void* userdata = nullptr) = 0;
virtual bool close() = 0;
virtual bool is_open() = 0;
virtual bool is_connected() = 0;
virtual void set_timeout(int timeout) = 0;
virtual int read_bulk(void* data, int len) = 0;
virtual int write_bulk(void* data, int len) = 0;
virtual int read_int(void* data, int len) = 0;
virtual int control_msg(int rtype, int req, int value, int index, int len, void* data) = 0;
};

View File

@ -4,134 +4,85 @@
#include "filetools.h"
#include "imageprocess.h"
#include <atlconv.h>
#include <queue>
//using namespace std::this_thread;
using namespace std;
ImageMatQueue::ImageMatQueue(void) :b_save_origin(false),
b_save_fixed_origin(false)
static int imgindex = 0;
ImageMatQueue::ImageMatQueue(void)
{
pixType=-1;
DevModel=-1;
if(!bRun)
{
m_threadProc = std::thread(&ImageMatQueue::proc, this);
bRun = true;
}
pixType = -1;
DevModel = -1;
bScanning = false;
imageremain = 0;
}
void ImageMatQueue::run()
{
if(m_threadProc.joinable())
if (m_threadProc.joinable())
{
bRun = false;
m_threadProc.join();
}
bRun = true;
imgindex = 0;
m_threadProc = std::thread(&ImageMatQueue::proc, this);
}
void ImageMatQueue::setmultioutputR(bool canoutput/*=false*/)
{
can_multi_outputR=canoutput;
can_multi_outputR = canoutput;
}
void ImageMatQueue::SetDevModel(int dev/*=-1*/)
{
DevModel=dev;
DevModel = dev;
}
ImageMatQueue::~ImageMatQueue(void)
{
if (m_threadProc.joinable())
{
bRun = false;
m_threadProc.join();
XdPrint("m_threadProc Released True 111111111111111111111111111\n");
}
if (m_images.Size() > 0)
{
m_images.Clear();
m_images.ShutDown();
}
if (m_pImages.Size() > 0)
{
m_pImages.Clear();
m_pImages.ShutDown();
}
if (m_threadProc.joinable())
{
bRun = false;
m_threadProc.join();
}
}
void ImageMatQueue::pushMat(JpegBuffer& data)
{
imageremain++;
m_pImages.Put(data);
int k = 0;
}
void ImageMatQueue::UpdateSaveConfig(bool saveOrigin, bool saveFixedOrigin)
std::string ImageMatQueue::popMat(int num)
{
b_save_origin= saveOrigin;
b_save_fixed_origin=saveFixedOrigin ;
}
cv::Mat ImageMatQueue::popMat(int num)
{
return _popMat(num);
}
cv::Mat ImageMatQueue::popMat()
{
return m_images.Take();
return m_images.Take();
}
bool ImageMatQueue::valid()
{
bool bIsEmpty = m_images.Size()==0;
return !bIsEmpty;
return m_images.Size();
}
void ImageMatQueue::clear()
{
m_images.Clear();
m_pImages.Clear();
}
cv::Mat ImageMatQueue::_popMat(int num)
{
std::queue<cv::Mat> m_Tempimages; // 临时队列
cv::Mat Tempimage;
cv::Mat image;
int i = 0;
int iSize = m_images.Size();
for(i = 0;i < iSize;i++)
while (m_images.Size()>0)
{
image = m_images.Front();
m_Tempimages.push(image);
image.release();
m_images.Take();
}
for(i = 0;i < iSize;i++)
while (m_pImages.Size()>0)
{
Tempimage = m_Tempimages.front();
if(i == num)
{
return Tempimage;
}
m_Tempimages.pop();
m_pImages.Clear();
}
return Tempimage;
}
void ImageMatQueue::saveimg(std::string csImage,cv::Mat& mat)
{
imwrite(csImage, mat);
}
int ImageMatQueue::getMatSum()
{
@ -140,123 +91,68 @@ int ImageMatQueue::getMatSum()
return iSum;
}
bool ImageMatQueue::isScanning()
{
return (imageremain != 0 )|| (m_pImages.Size() != 0);
}
bool ImageMatQueue::empty()
{
return m_images.Size()==0 && m_pImages.Size()==0;
return m_images.Size()==0 && imageremain ==0 && !bScanning;
}
void ImageMatQueue::proc()
{
while(bRun)
while (bRun)
{
this_thread::sleep_for(std::chrono::milliseconds(5));
{
if(m_pImages.Size()>0)//m_images.empty() &&
if (m_pImages.Size()>0)//m_images.empty() &&
{
if (pixType!=-1)
if (pixType != -1)
{
std::string csName;
SYSTEMTIME st = { 0 };
GetLocalTime(&st); //»ñÈ¡µ±Ç°Ê±¼ä ¿É¾«È·µ½ms
//csName.Format("%02d%02d%02d-%d.bmp", st.wHour, st.wMinute, st.wSecond,++imgindex);
cv::Mat matPicImage;
cv::Mat matFront,matBack;
vector<cv::Mat> mats;
switch(DevModel)
cv::Mat matFront, matBack;
//vector<cv::Mat> mats;
switch (DevModel)
{
case 0://G100
case 1://G200//正反面图像分开的
{
if (m_pImages.Size() >= 2)
{
if (m_pImages.Size()>=2)
{
matFront=m_pImages.Take().getMat(pixType);
matBack=m_pImages.Take().getMat(pixType);
mats.push_back(matFront);
if (duplexFlag)
{
mats.push_back(matBack);
}
if (b_save_origin)
{
CString csName;
SYSTEMTIME st = { 0 };
GetLocalTime(&st); //获取当前时间 可精确到ms
csName.Format("%02d%02d%02d.jpg", st.wHour, st.wMinute, st.wSecond);
CString csImage;
csImage = csPath + "\\G200-Origin" + csName;
saveimg(std::string(csImage.GetBuffer()), matBack);
}
for (int j = 0; j < m_iaList.size(); j++)
{
m_iaList[j]->apply(mats, duplexFlag);//需要在每个图像处理apply的部分 增加判断里边的mat是否为空 目前还没加
}
}
matFront = m_pImages.Take().getMat(pixType);
matBack = m_pImages.Take().getMat(pixType);
//mats.push_back(matFront);
//mats.push_back(matBack);
}
break;
}
break;
case 2://G300
case 3://G400
case 4://G500 正反面图像在一副图上,需要均分图像
{
cv::Mat mat=m_pImages.Take().getMat(pixType);
matFront=mat(cv::Rect(0,0,mat.cols/2,mat.rows));
matBack=mat(cv::Rect(mat.cols/2,0,mat.cols/2,mat.rows));
if (duplexFlag)
{
mats.push_back(matBack);
}
if (b_save_origin)
{
CString csName;
SYSTEMTIME st = { 0 };
GetLocalTime(&st); //获取当前时间 可精确到ms
csName.Format("%02d%02d%02d.jpg", st.wHour, st.wMinute, st.wSecond);
CString csImage;
csImage = csPath + "\\G500-Origin" + csName;
saveimg(std::string(csImage.GetBuffer()), matBack);
}
for (int j = 0; j < m_iaList.size(); j++)
{
m_iaList[j]->apply(mats, duplexFlag);//需要在每个图像处理apply的部分 增加判断里边的mat是否为空 目前还没加
}
mats.push_back(matFront);
XdPrint("m_pImages取完当前正反面==========================\n");
}
break;
{
std::string csImage;
csImage = csPath + "\\G300" + csName;
//cv::Mat mat = m_pImages.Take().getMat(pixType);
//matPicImage = mat(cv::Rect(0, 0, mat.cols, mat.rows));
////mats.push_back(matPicImage);
//IplImage qqImg;
//qqImg = IplImage(matPicImage); // cv::Mat -> IplImage
//cvSaveImage(csImage, &qqImg);
m_images.Put(csImage);
}
break;
default:
break;
}
static int index = 0;
if (b_save_fixed_origin)
{
for (int i = 0; i < mats.size(); i++)
{
//CString outinfo;
//outinfo.Format("Tring to save image index of %d \n", ++index);
//XdPrint(outinfo.GetBuffer());
if (!mats[i].empty())
{
CString csName;
SYSTEMTIME st = { 0 };
GetLocalTime(&st); //获取当前时间 可精确到ms
csName.Format("%02d%02d%02d.jpg", st.wHour, st.wMinute, st.wSecond);
CString csImage;
csImage = csPath + "\\G300-" + csName;
saveimg(std::string(csImage.GetBuffer()), mats[i]);
//outinfo.Format("Saved image index of %d \n", index);
//XdPrint(outinfo.GetBuffer());
}
}
}
//if (!mats[0].empty()&&!mats[1].empty())
if (!mats[0].empty())
{
for (int i=0,length=mats.size();i<length;i++)
{
if (!mats[i].empty())
{
m_images.Put(mats[i]);
}
}
}//end if !mats[0].empty()&&!mats[1].empty()
}
imageremain--;
}
}
}

View File

@ -3,9 +3,9 @@
#include <mutex>
#include <opencv2\opencv.hpp>
#include "JpegBuffer.h"
#include "BlockingQueue.h"
#include <queue>
#include "PublicFunc.h"
#include "ImageApplyHeaders.h"
#include "BlockingQueue.h"
class ImageMatQueue
{
@ -14,49 +14,40 @@ public:
virtual ~ImageMatQueue(void);
void pushMat(JpegBuffer& data);
void UpdateSaveConfig(bool saveOrigin, bool saveFixedOrigin);
cv::Mat popMat(int num);
cv::Mat popMat();
std::string popMat(int num);
bool empty();
bool valid();
void clear();
void run();
int getMatSum();
bool b_save_origin;
bool b_save_fixed_origin;
volatile BOOL duplexFlag;
void SetFilePath(CString csFilePath)
bool isScanning();
void SetScanFlag(bool scannning) { bScanning = bScanning; }
void SetFilePath(std::string csFilePath)
{
csPath = csFilePath;
}
void ImageMatQueue::setduplexflag(BOOL value)
{
duplexFlag = value;
}
CString GetFilePath()
std::string GetFilePath()
{
return csPath;
}
void ImageMatQueue::setlist(std::vector<std::shared_ptr<CImageApply>> list)
{
m_iaList = list;
}
public:
int pixType;
void setmultioutputR(bool canoutput=false);
void SetDevModel(int dev=-1);
std::vector<std::shared_ptr<CImageApply>> m_iaList;
CString csPath;
std::string csPath;
private:
void proc();
cv::Mat _popMat(int num);
void saveimg(std::string csImage,cv::Mat &mat);
BlockingQueue<cv::Mat> m_images; //!< ÒÑ´¦ÀíͼÏñ¶ÓÁÐ
BlockingQueue<std::string> m_images; //!< 已处理图像队列
BlockingQueue<JpegBuffer> m_pImages;
std::thread m_threadProc;
volatile bool bRun;
bool can_multi_outputR;
int DevModel;
volatile bool bScanning;
volatile int imageremain;
};

View File

@ -7,6 +7,10 @@
using namespace std;
JpegBuffer::JpegBuffer()
{
}
JpegBuffer::JpegBuffer(cv::Mat buffer, int color_type,int side,int mFilter)
{
this->m_buffer = buffer;
@ -42,11 +46,10 @@ cv::Mat JpegBuffer::getMat( int pixType)
JpegLib jl;
//cv::Mat image = jl.decode(m_buffer, 6);//oixtype
StopWatch sw;
sw.start();
//XdPrint("buffer size is :%d ==========================\n",getSize());
cv::Mat image = jl.decode(m_buffer, pixType);//oixtype
sw.stop();
//XdPrint("Decode Image time epleased :%lf ==========================\n",sw.time_run());
XdPrint("Decode Image time epleased :%lf ==========================\n",sw.elapsed_ms());
//XdPrint("==image col is :%d, image row is :%d, image size is :%d===\n",image.cols, image.rows, image.size);
//FileTools::write_log("D:/1.txt",)

View File

@ -5,7 +5,7 @@
class JpegBuffer
{
public:
JpegBuffer() {}
JpegBuffer();
JpegBuffer(cv::Mat buffer,int color_type=2,int side=0,int mFilter=0);
virtual ~JpegBuffer(void);

View File

@ -1,552 +1,107 @@
#include "StdAfx.h"
#include "stdafx.h"
#include "JsonConfig.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <sstream>
#include "CJsonObject.hpp"
#include <fstream>
#include <iomanip>
#ifdef WIN32
#include <corecrt_io.h>
#else
#include <unistd.h>
#endif
JsonConfig::JsonConfig(void)
#define JSON_FILE "config.json"
#define SCAN_INFO_TITLE "ScanInfo"
#define SCAN_TOTAL "TotalScanned"
#define SCAN_CUONUM "CuoNum"
#define SCAN_JAMINNUM "JamInNum"
#define SCAN_JAMOUTNUM "JamOutNum"
#define SCAN_DOUNUM "DoubleNum"
#define SCAN_ERRORNUM "ErrorNum"
#define SCAN_SERIALNUM "SerialNum"
#define SCAN_FWVERSION "FWVersion"
JsonConfig::JsonConfig()
{
//if (access(SCANNER_SCAN_INFO_PATH, F_OK) == -1) //不存在
//{
// ScannerScanInfo defaultinfo = CreateDefaultScanInfo();
// SaveScanInfo(defaultinfo);
//}
}
JsonConfig::JsonConfig(ConfigType type) : m_cfgType(type)
{
}
JsonConfig::~JsonConfig(void)
JsonConfig::~JsonConfig()
{
}
/************************************************************************/
/* ±£´æÅäÖòÎÊý */
/************************************************************************/
void JsonConfig::WriteToJson(PCONFIGPARAMS pConfigItem,const std::string fileNames,bool isConfigItem)
bool JsonConfig::ReadParam(CaptureParams& param)
{
//neb::CJsonObject outJson;
//outJson.AddEmptySubObject("Config");//header
//outJson["Config"].Add(PIXTYPE,(int)(pConfigItem->Pixtype));
//outJson["Config"].Add(PAPARSIZE,(int)(pConfigItem->PaperSize));
//outJson["Config"].Add(RESOLUTION,(int)(pConfigItem->Resolution));
//outJson["Config"].Add(DUPLEX,(int)(pConfigItem->Duplex));
if(_access(JSON_FILE,0)!=0)
{
CaptureParams t_param = { 0 };
CreateDefault(t_param);
WriteParam(t_param);
param = t_param;
return false;
}
std::ifstream i(JSON_FILE);
json j;
i >> j;
auto &jobject = j["Config"];
//std::ofstream os;
//os.open(fileNames.c_str());
//os<<outJson.ToFormattedString();
//os.close();
jobject["CorrectColorExposure"].get_to(param.correctColorExposure);
jobject["CorrectColorGain"].get_to(param.correctColorGain);
jobject["CorrectColorOffset"].get_to(param.correctColorOffset);
jobject["ColorExposure"].get_to(param.colorExposure);
jobject["ColorGain"].get_to(param.colorGain);
jobject["ColorOffset"].get_to(param.colorOffset);
jobject["CorrectGrayExposure"].get_to(param.correctGrayExposure);
jobject["CorrectGrayGain"].get_to(param.correctGrayGain);
jobject["CorrectGrayOffset"].get_to(param.correctGrayOffset);
jobject["GrayExposure"].get_to(param.grayExposure);
jobject["GrayGain"].get_to(param.grayGain);
jobject["GrayOffset"].get_to(param.grayOffset);
return true;
}
void JsonConfig::WriteJsonData(const std::string fileName)
void JsonConfig::WriteParam(CaptureParams& t_param)
{
json m_json;
auto &jobject = m_json["Config"];
jobject["CorrectColorExposure"] = t_param.correctColorExposure;
jobject["CorrectColorGain"] = t_param.correctColorGain;
jobject["CorrectColorOffset"] = t_param.correctColorOffset;
jobject["ColorExposure"] = t_param.colorExposure;
jobject["ColorGain"] = t_param.colorGain;
jobject["ColorOffset"] = t_param.colorOffset;
jobject["CorrectGrayExposure"] = t_param.correctGrayExposure;
jobject["CorrectGrayGain"] = t_param.correctGrayGain;
jobject["CorrectGrayOffset"] = t_param.correctGrayOffset;
jobject["GrayExposure"] = t_param.grayExposure;
jobject["GrayGain"] = t_param.grayGain;
jobject["GrayOffset"] = t_param.grayOffset;
std::ofstream o(JSON_FILE);
o << std::setw(4) << m_json << std::endl;
}
void JsonConfig::WriteJsonArrayToFile(CONFIGPARAMS cfgConfig,const std::string filename)
void JsonConfig::CreateDefault(CaptureParams& param)
{
//neb::CJsonObject root;
//
//root.AddEmptySubObject("Config");
//root["Config"].AddEmptySubArray(PIXTYPE);
//root["Config"].AddEmptySubArray(PAPARSIZE);
//root["Config"].AddEmptySubArray(RESOLUTION);
//root["Config"].AddEmptySubArray(DUPLEX);
//root["Config"].AddEmptySubArray(TABINDEX);
//
//root["Config"][PIXTYPE].Add(cfgConfig.Pixtype);
//root["Config"][PAPARSIZE].Add(cfgConfig.PaperSize);
//root["Config"][RESOLUTION].Add(cfgConfig.Resolution);
//root["Config"][DUPLEX].Add(cfgConfig.Duplex);
//root["Config"][TABINDEX].Add(cfgConfig.TabIndex);
for (size_t i = 0; i <6; i++)
{
param.colorExposure[i] = 259;
param.correctColorExposure[i] = 238;
param.correctGrayExposure[i] = 259;
param.grayExposure[i] = 238;
}
//std::ofstream os;
//os.open(filename.c_str());
//os<<root.ToFormattedString();
//os.close();
}
void JsonConfig::WriteDistorJsonToFile(std::vector<DISTORTIONPARAMS> cfgArray,const std::string filename)
{
/*neb::CJsonObject root;
root.AddEmptySubObject("Distor");
root["Distor"].AddEmptySubArray(OBJVALUE1);
root["Distor"].AddEmptySubArray(OBJVALUE2);
root["Distor"].AddEmptySubArray(OBJVALUE3);
root["Distor"].AddEmptySubArray(OBJVALUE4);
root["Distor"].AddEmptySubArray(OBJVALUE5);
root["Distor"].AddEmptySubArray(OBJVALUE6);
root["Distor"].AddEmptySubArray(LIMITOFFSET1);
root["Distor"].AddEmptySubArray(LIMITOFFSET2);
root["Distor"].AddEmptySubArray(LIMITOFFSET3);
root["Distor"].AddEmptySubArray(LIMITOFFSET4);
root["Distor"].AddEmptySubArray(LIMITOFFSET5);
root["Distor"].AddEmptySubArray(LIMITOFFSET6);
for (int i=0;i<cfgArray.size();i++)
{
root["Distor"][OBJVALUE1].Add(cfgArray[i].ObjValues[0]);
root["Distor"][OBJVALUE2].Add(cfgArray[i].ObjValues[1]);
root["Distor"][OBJVALUE3].Add(cfgArray[i].ObjValues[2]);
root["Distor"][OBJVALUE4].Add(cfgArray[i].ObjValues[3]);
root["Distor"][OBJVALUE5].Add(cfgArray[i].ObjValues[4]);
root["Distor"][OBJVALUE6].Add(cfgArray[i].ObjValues[5]);
root["Distor"][LIMITOFFSET1].Add(cfgArray[i].LimitOffset[0]);
root["Distor"][LIMITOFFSET2].Add(cfgArray[i].LimitOffset[1]);
root["Distor"][LIMITOFFSET3].Add(cfgArray[i].LimitOffset[2]);
root["Distor"][LIMITOFFSET4].Add(cfgArray[i].LimitOffset[3]);
root["Distor"][LIMITOFFSET5].Add(cfgArray[i].LimitOffset[4]);
root["Distor"][LIMITOFFSET6].Add(cfgArray[i].LimitOffset[5]);
}
std::ofstream os;
os.open(filename.c_str());
os<<root.ToFormattedString();
os.close();*/
}
void JsonConfig::WriteMacthJsonToFile(std::vector<MATCHPARAMS> cfgArray,const std::string filename)
{
/*neb::CJsonObject root;
root.AddEmptySubObject("Match");
root["Match"].AddEmptySubArray(LOADNUM);
root["Match"].AddEmptySubArray(XPOINT);
root["Match"].AddEmptySubArray(YPOINT);
root["Match"].AddEmptySubArray(PWIGHT);
root["Match"].AddEmptySubArray(PHEIGHT);
root["Match"].AddEmptySubArray(MATCHPATH);
for (int i=0;i<cfgArray.size();i++)
{
root["Match"][LOADNUM].Add(cfgArray[i].LoadNum);
root["Match"][XPOINT].Add(cfgArray[i].XPoint);
root["Match"][YPOINT].Add(cfgArray[i].YPoint);
root["Match"][PWIGHT].Add(cfgArray[i].PWight);
root["Match"][PHEIGHT].Add(cfgArray[i].PHeight);
if (cfgArray[i].MatchPath.c_str()!=NULL)
{
root["Match"][MATCHPATH].Add(cfgArray[i].MatchPath);
}
}
std::ofstream os;
os.open(filename.c_str());
os<<root.ToFormattedString();
os.close();*/
}
CONFIGPARAMS JsonConfig::ReadDefaultConfig()
{
/*TCHAR szIniFile[MAX_PATH] = { 0 };
SHGetSpecialFolderPath(NULL, szIniFile, CSIDL_LOCAL_APPDATA, TRUE);
_tcscat(szIniFile, HUAGAO_SCAN);
_tcscat(szIniFile, PAPER_TEST);
_tcscat(szIniFile, TEXT("\\"));
_tcscat(szIniFile, PAPER_JSON_NAME);
std::string s_default(szIniFile);
vector<CONFIGPARAMS> vc;
vc=ReadJsonArrayFromFile(s_default.c_str());
if (vc.size()!=0)
{
return vc[0];
}
return GetDefaultConfigParams();*/
return CONFIGPARAMS();
}
DISTORTIONPARAMS JsonConfig::ReadDistorConfig()
{
//TCHAR szIniFile[MAX_PATH] = { 0 };
//SHGetSpecialFolderPath(NULL, szIniFile, CSIDL_LOCAL_APPDATA, TRUE);
//_tcscat(szIniFile, HUAGAO_SCAN);
//_tcscat(szIniFile, PAPER_TEST);
//_tcscat(szIniFile, TEXT("\\"));
//_tcscat(szIniFile, DISTOR_JSON_NAME);
//std::string s_default(szIniFile);
//vector<DISTORTIONPARAMS> vc;
//vc=ReadDistorJsonFromFile(s_default.c_str());
//if (vc.size()!=0)
//{
// return vc[0];
//}
//return GetDistorConfigParams();
return GetDistorConfigParams();
}
MATCHPARAMS JsonConfig::ReadMacthConfig()
{
//TCHAR szIniFile[MAX_PATH] = { 0 };
//SHGetSpecialFolderPath(NULL, szIniFile, CSIDL_LOCAL_APPDATA, TRUE);
//_tcscat(szIniFile, HUAGAO_SCAN);
//_tcscat(szIniFile, PAPER_TEST);
//_tcscat(szIniFile, TEXT("\\"));
//_tcscat(szIniFile, MATCH_JSON_NAME);
//std::string s_default(szIniFile);
//vector<MATCHPARAMS> vc;
//vc=ReadMacthJsonFromFile(s_default.c_str());
//if (vc.size()!=0)
//{
// return vc[0];
//}
//return GetMacthConfigParams();
return MATCHPARAMS();
}
bool JsonConfig::DeleteJsonFile(std::string path)
{
return (remove(path.c_str()));
}
std::vector<CONFIGPARAMS> JsonConfig::ReadJsonArrayFromFile(const std::string filename)
{
std::vector<CONFIGPARAMS> re;
/*FILE* file=fopen(filename.c_str(),"rb");
if (!file)
{
return re;
}
fseek(file,0,SEEK_END);
long size=ftell(file);
fseek(file,0,SEEK_SET);
std::string text;
char* buffer=new char[size+1];
buffer[size]=0;
if (!fread(buffer,1,size,file)==(unsigned long)size)
{
return re;
}
text=buffer;
fclose(file);
delete []buffer;
re=parseJsonFromString(text);*/
return re;
}
std::vector<DISTORTIONPARAMS> JsonConfig::ReadDistorJsonFromFile(const std::string filename)
{
std::vector<DISTORTIONPARAMS> re;
//FILE* file=fopen(filename.c_str(),"rb");
//if (!file)
//{
// return re;
//}
//fseek(file,0,SEEK_END);
//long size=ftell(file);
//fseek(file,0,SEEK_SET);
//std::string text;
//char* buffer=new char[size+1];
//buffer[size]=0;
//if (!fread(buffer,1,size,file)==(unsigned long)size)
//{
// return re;
//}
//text=buffer;
//fclose(file);
//delete []buffer;
//re=parseDistorFromString(text);
return re;
}
std::vector<MATCHPARAMS> JsonConfig::ReadMacthJsonFromFile(const std::string filename)
{
std::vector<MATCHPARAMS> re;
/*FILE* file=fopen(filename.c_str(),"rb");
if (!file)
{
return re;
}
fseek(file,0,SEEK_END);
long size=ftell(file);
fseek(file,0,SEEK_SET);
std::string text;
char* buffer=new char[size+1];
buffer[size]=0;
if (!fread(buffer,1,size,file)==(unsigned long)size)
{
return re;
}
text=buffer;
fclose(file);
delete []buffer;
re=parseMacthFromString(text);*/
return re;
}
CONFIGPARAMS JsonConfig::GetDefaultConfigParams()
{
CONFIGPARAMS params;
params.Pixtype=1;//»Ò¶È
params.PaperSize=11;//A3
params.Resolution=200;//200dpi
params.Duplex=1;//Ë«Ãæ
params.TabIndex = 1;
return params;
}
DISTORTIONPARAMS JsonConfig::GetDistorConfigParams()
{
DISTORTIONPARAMS params;
for(int i = 0;i < 6;i++)
{
params.ObjValues[i] = 10;
params.LimitOffset[i] = 2;
}
return params;
}
MATCHPARAMS JsonConfig::GetMacthConfigParams()
{
MATCHPARAMS params;
params.LoadNum = 4;
params.XPoint = 10;
params.YPoint = 10;
params.PWight = 100;
params.PHeight = 100;
return params;
}
std::vector<CONFIGPARAMS> JsonConfig::parseJsonFromString(const std::string str)
{
//neb::CJsonObject root(str);
vector<CONFIGPARAMS> vcConfig;
/*int size=0;
neb::CJsonObject itmPaparSize;
root["Config"].Get(PAPARSIZE,itmPaparSize);
size=itmPaparSize.GetArraySize();
if (size>0)
{
neb::CJsonObject itmPixType;
root["Config"].Get(PIXTYPE,itmPixType);
neb::CJsonObject itmRes;
root["Config"].Get(RESOLUTION,itmRes);
neb::CJsonObject itmDulpex;
root["Config"].Get(DUPLEX,itmDulpex);
neb::CJsonObject itmTabIndex;
root["Config"].Get(TABINDEX,itmTabIndex);
for (int i=0;i<size;i++)
{
CONFIGPARAMS cfp;
int i_value;
itmPixType.Get(i,i_value);
cfp.Pixtype=i_value;
itmPaparSize.Get(i,i_value);
cfp.PaperSize=i_value;
itmRes.Get(i,i_value);
cfp.Resolution=i_value;
itmDulpex.Get(i,i_value);
cfp.Duplex=i_value;
itmTabIndex.Get(i,i_value);
cfp.TabIndex=i_value;
vcConfig.push_back(cfp);
}
}
else
{
CONFIGPARAMS cfp;
int index;
root["Config"].Get(PIXTYPE,index);
cfp.Pixtype=index;
root["Config"].Get(PAPARSIZE,index);
cfp.PaperSize=index;
root["Config"].Get(RESOLUTION,index);
cfp.Resolution=index;
root["Config"].Get(DUPLEX,index);
cfp.Duplex=index;
root["Config"].Get(TABINDEX,index);
cfp.TabIndex=index;
vcConfig.push_back(cfp);
}*/
return vcConfig;
}
std::vector<DISTORTIONPARAMS> JsonConfig::parseDistorFromString(const std::string str)
{
//neb::CJsonObject root(str);
vector<DISTORTIONPARAMS> vcConfig;
//int size=0;
//neb::CJsonObject itmObjValue1;
//root["Distor"].Get(OBJVALUE1,itmObjValue1);
//size = itmObjValue1.GetArraySize();
//if (size>0)
//{
// neb::CJsonObject itmObjValue2;
// root["Distor"].Get(OBJVALUE2,itmObjValue2);
// neb::CJsonObject itmObjValue3;
// root["Distor"].Get(OBJVALUE3,itmObjValue3);
// neb::CJsonObject itmObjValue4;
// root["Distor"].Get(OBJVALUE4,itmObjValue4);
// neb::CJsonObject itmObjValue5;
// root["Distor"].Get(OBJVALUE5,itmObjValue5);
// neb::CJsonObject itmObjValue6;
// root["Distor"].Get(OBJVALUE6,itmObjValue6);
// neb::CJsonObject itmLimitOffset1;
// root["Distor"].Get(LIMITOFFSET1,itmLimitOffset1);
// neb::CJsonObject itmLimitOffset2;
// root["Distor"].Get(LIMITOFFSET2,itmLimitOffset2);
// neb::CJsonObject itmLimitOffset3;
// root["Distor"].Get(LIMITOFFSET3,itmLimitOffset3);
// neb::CJsonObject itmLimitOffset4;
// root["Distor"].Get(LIMITOFFSET4,itmLimitOffset4);
// neb::CJsonObject itmLimitOffset5;
// root["Distor"].Get(LIMITOFFSET5,itmLimitOffset5);
// neb::CJsonObject itmLimitOffset6;
// root["Distor"].Get(LIMITOFFSET6,itmLimitOffset6);
// for (int i=0;i<size;i++)
// {
// DISTORTIONPARAMS cfp;
// //float f_value;
// int i_value;
// itmObjValue1.Get(i,i_value);
// cfp.ObjValues[0]=i_value;
// itmObjValue2.Get(i,i_value);
// cfp.ObjValues[1]=i_value;
// itmObjValue3.Get(i,i_value);
// cfp.ObjValues[2]=i_value;
// itmObjValue4.Get(i,i_value);
// cfp.ObjValues[3]=i_value;
// itmObjValue5.Get(i,i_value);
// cfp.ObjValues[4]=i_value;
// itmObjValue6.Get(i,i_value);
// cfp.ObjValues[5]=i_value;
// itmLimitOffset1.Get(i,i_value);
// cfp.LimitOffset[0]=i_value;
// itmLimitOffset2.Get(i,i_value);
// cfp.LimitOffset[1]=i_value;
// itmLimitOffset3.Get(i,i_value);
// cfp.LimitOffset[2]=i_value;
// itmLimitOffset4.Get(i,i_value);
// cfp.LimitOffset[3]=i_value;
// itmLimitOffset5.Get(i,i_value);
// cfp.LimitOffset[4]=i_value;
// itmLimitOffset6.Get(i,i_value);
// cfp.LimitOffset[5]=i_value;
// vcConfig.push_back(cfp);
// }
//}
//else
//{
// DISTORTIONPARAMS cfp;
// int index;
// //float fndex;
// root["Distor"].Get(OBJVALUE1,index);
// cfp.ObjValues[0]=index;
// root["Distor"].Get(OBJVALUE2,index);
// cfp.ObjValues[1]=index;
// root["Distor"].Get(OBJVALUE3,index);
// cfp.ObjValues[2]=index;
// root["Distor"].Get(OBJVALUE4,index);
// cfp.ObjValues[3]=index;
// root["Distor"].Get(OBJVALUE5,index);
// cfp.ObjValues[4]=index;
// root["Distor"].Get(OBJVALUE6,index);
// cfp.ObjValues[5]=index;
// root["Distor"].Get(LIMITOFFSET1,index);
// cfp.LimitOffset[0]=index;
// root["Distor"].Get(LIMITOFFSET2,index);
// cfp.LimitOffset[1]=index;
// root["Distor"].Get(LIMITOFFSET3,index);
// cfp.LimitOffset[2]=index;
// root["Distor"].Get(LIMITOFFSET4,index);
// cfp.LimitOffset[3]=index;
// root["Distor"].Get(LIMITOFFSET5,index);
// cfp.LimitOffset[4]=index;
// root["Distor"].Get(LIMITOFFSET6,index);
// cfp.LimitOffset[5]=index;
// vcConfig.push_back(cfp);
//}
return vcConfig;
}
std::vector<MATCHPARAMS> JsonConfig::parseMacthFromString(const std::string str)
{
//neb::CJsonObject root(str);
vector<MATCHPARAMS> vcConfig;
/*int size=0;
neb::CJsonObject itmLoadNum;
root["Match"].Get(LOADNUM,itmLoadNum);
size=itmLoadNum.GetArraySize();
if (size>0)
{
neb::CJsonObject itmXPoint;
root["Match"].Get(XPOINT,itmXPoint);
neb::CJsonObject itmYPoint;
root["Match"].Get(YPOINT,itmYPoint);
neb::CJsonObject itmPWight;
root["Match"].Get(PWIGHT,itmPWight);
neb::CJsonObject itmPHeight;
root["Match"].Get(PHEIGHT,itmPHeight);
neb::CJsonObject itmMatchPath;
if (!root["Match"][MATCHPATH].IsEmpty())
{
root["Match"].Get(MATCHPATH,itmMatchPath);
}
for (int i=0;i<size;i++)
{
MATCHPARAMS cfp;
int i_value;
std::string s_value;
itmLoadNum.Get(i,i_value);
cfp.LoadNum=i_value;
itmXPoint.Get(i,i_value);
cfp.XPoint=i_value;
itmYPoint.Get(i,i_value);
cfp.YPoint=i_value;
itmPWight.Get(i,i_value);
cfp.PWight=i_value;
itmPHeight.Get(i,i_value);
cfp.PHeight=i_value;
if (!root["Match"][MATCHPATH].IsEmpty())
{
itmMatchPath.Get(i,s_value);
cfp.MatchPath=s_value;
}
vcConfig.push_back(cfp);
}
}
else
{
MATCHPARAMS cfp;
int index;
std::string svalue;
root["Match"].Get(LOADNUM,index);
cfp.LoadNum=index;
root["Match"].Get(XPOINT,index);
cfp.XPoint=index;
root["Match"].Get(YPOINT,index);
cfp.YPoint=index;
root["Match"].Get(PWIGHT,index);
cfp.PWight=index;
root["Match"].Get(PHEIGHT,index);
cfp.PHeight=index;
if (!root["Match"][MATCHPATH].IsEmpty())
{
root["Match"].Get(MATCHPATH,svalue);
cfp.MatchPath=svalue;
}
vcConfig.push_back(cfp);
}*/
return vcConfig;
for (size_t i = 0; i <12; i++)
{
param.correctGrayGain[i] = param.grayGain[i] = 47;
param.colorGain[i] = param.correctColorGain[i] = 30;
param.correctColorOffset[i] = param.correctGrayOffset[i] = 119;
param.colorOffset[i] = param.grayOffset[i] = 119;
}
}

View File

@ -1,41 +1,52 @@
#pragma once
#include "json.hpp"
#include <string>
#include <map>
#include "PublicFunc.h"
#include <vector>
#include <json.h>
#define SCANNER_SCAN_INFO_PATH "/usr/local/huago/jsonconfig.json"
using namespace std;
struct DISTORTIONPARAMS
{
/*Ö÷½çÃæ²ÎÊý*/
INT ObjValues[6];
INT LimitOffset[6];
};
using json = nlohmann::json;
class JsonConfig
{
public:
JsonConfig(void);
~JsonConfig(void);
public:
void WriteToJson(PCONFIGPARAMS pConfigItem,const std::string fileName,bool isConfigItem=true);
//PCONFIGPARAMS ReadJsonFromFile(const char* fileNames);
void WriteJsonData(const std::string fileName);
void WriteJsonArrayToFile(CONFIGPARAMS cfgConfig,const std::string filename);
void WriteDistorJsonToFile(std::vector<DISTORTIONPARAMS> cfgArray,const std::string filename);
void WriteMacthJsonToFile(std::vector<MATCHPARAMS> cfgArray,const std::string filename);
CONFIGPARAMS ReadDefaultConfig();
DISTORTIONPARAMS ReadDistorConfig();
MATCHPARAMS ReadMacthConfig();
bool DeleteJsonFile(std::string path);
std::vector<CONFIGPARAMS> ReadJsonArrayFromFile(const std::string filename);
std::vector<DISTORTIONPARAMS> ReadDistorJsonFromFile(const std::string filename);
std::vector<MATCHPARAMS> ReadMacthJsonFromFile(const std::string filename);
CONFIGPARAMS GetDefaultConfigParams();
DISTORTIONPARAMS GetDistorConfigParams();
MATCHPARAMS GetMacthConfigParams();
private:
std::vector<CONFIGPARAMS> parseJsonFromString(const std::string str) ;
std::vector<DISTORTIONPARAMS> parseDistorFromString(const std::string str) ;
std::vector<MATCHPARAMS> parseMacthFromString(const std::string str) ;
enum class ConfigType
{
Color_Flat,
Color_Correct,
Gray_Flat,
Gray_Correct
};
private:
map<ConfigType,string> cfgPaths={
{ConfigType::Color_Flat,"/usr/local/etc/huago/Color_Flat.json"},
{ConfigType::Color_Correct,"/usr/local/etc/huago/Color_Correct.json"},
{ConfigType::Gray_Flat,"/usr/local/etc/huago/Gray_Flat.json"},
{ConfigType::Gray_Correct,"/usr/local/etc/huago/Gray_Correct.json"}
};
map<ConfigType,string> cfgPrefix={
{ConfigType::Color_Flat,"Color_Flat"},
{ConfigType::Color_Correct,"Color_Correct"},
{ConfigType::Gray_Flat,"Gray_Flat"},
{ConfigType::Gray_Correct,"Gray_Correct"}
};
ConfigType m_cfgType;
public:
JsonConfig();
JsonConfig(ConfigType type);
~JsonConfig();
/*
*false
*/
bool ReadParam(CaptureParams& param);
void WriteParam(CaptureParams& t_param);
// ScannerScanInfo GetScanInfo();
//
// void SaveScanInfo(const ScannerScanInfo& info);
private:
void CreateDefault(CaptureParams& param);
// ScannerScanInfo CreateDefaultScanInfo();
};

View File

@ -4,86 +4,9 @@
#include "stdafx.h"
#include <string>
//#include "UI_INI.h"
//#include "DirectshowCaptureVideo.h"
//#include "DirectshowCaptureVideoUvc.h"
using namespace std;
#define PIXTYPE "iPixType"
#define PAPARSIZE "iPaparSize"
#define RESOLUTION "iResolution"
#define DUPLEX "iDuplex"
#define TABINDEX "iTabIndex"
#define OBJVALUE1 "fObjValue1"
#define OBJVALUE2 "fObjValue2"
#define OBJVALUE3 "fObjValue3"
#define OBJVALUE4 "fObjValue4"
#define OBJVALUE5 "fObjValue5"
#define OBJVALUE6 "fObjValue6"
#define LIMITOFFSET1 "iLimitOffset1"
#define LIMITOFFSET2 "iLimitOffset2"
#define LIMITOFFSET3 "iLimitOffset3"
#define LIMITOFFSET4 "iLimitOffset4"
#define LIMITOFFSET5 "iLimitOffset5"
#define LIMITOFFSET6 "iLimitOffset6"
#define LOADNUM "iLoadNum"
#define XPOINT "iXPonit"
#define YPOINT "iYPoint"
#define PWIGHT "iWight"
#define PHEIGHT "iHeight"
#define MATCHPATH "MacthPath"
/************************************
**json格式保存参数名称**
*************************************/
/*
#define PIXTYPE "iPixType"
#define PAPARSIZE "iPaparSize"
#define AUTOCROP "bAuotCrop"
#define RESOLUTION "iResolution"
#define DUPLEX "iDuplex"
#define DISCARBLANK "bDiscardBlank"
#define DISCARBLANKVINCE "bDiscardBlankVince"
#define FLOD "bFlod"
#define BRIGHTNESS "iBrightness"
#define AUTOCONTRAST "bAutoContrast"
#define CONTRAST "iContrast"
#define GAMMA "dGamma"
#define FILTERTYPE "iFilter"
#define FILLBLACK "bFillBlcak"
#define AUTODESCREW "bAutoDescrew"
#define ULTRADETECT "bUltrasonicDetect"
#define BINDINGDETECT "bBindingDetect"
#define SCANCOUNT "ScanCount"
#define DOCORIENTATION "bOrientation"
#define BACKROTATE180 "iBackRotate180"
#define SCREWDETECT "bScrewDetect"
#define SCREWLEVEL "iScrewLevel"
#define ITEMCAPTION "Caption"
#define SAVEPATH "SavePath"
#define MULTIOUTPUT "iMultiOutPut"
#define OUTHOLE "bOutHole"
#define OUTHOLERATIO "iOutHoleRatio"
*/
/******************
****
*******************/
struct tagMATCHPARAMS
{
/*主界面参数*/
INT LoadNum;
INT XPoint;
INT YPoint;
INT PWight;
INT PHeight;
std::string MatchPath;
};
typedef tagMATCHPARAMS MATCHPARAMS, *PMATCHPARAMS;
struct tagCONFIGPARAMS_1
struct tagCONFIGPARAMS
{
/*基本选项卡参数*/
@ -124,6 +47,7 @@ struct tagCONFIGPARAMS_1
std::string SavePath;
};
typedef tagCONFIGPARAMS CONFIGPARAMS,*PCONFIGPARAMS;
struct tagCONFIGINFO
{
@ -131,105 +55,65 @@ struct tagCONFIGINFO
std::string SavePath;
};
struct SPSET
{
unsigned int FSP;
unsigned int BSP;
};
typedef struct tagCONFIGINFO CONFIGINFO,*PCONFIGINFO;
struct tagCONFIGPARAMS
typedef unsigned int u32;
typedef struct
{
/*主界面参数*/
INT Pixtype;
INT PaperSize;
INT Resolution;
INT Duplex;
INT TabIndex;
};
typedef tagCONFIGPARAMS CONFIGPARAMS, *PCONFIGPARAMS;
/*除穿孔*/
/*
struct tagOutHole
u32 gainF[6];
u32 gainB[6];
u32 offsetsF[6];
u32 offsetsB[6];
u32 expF[3];
u32 expB[3];
u32 sp;
}HGCISConfig;
typedef struct
{
BOOL EnOutHole;
INT OutHoleRatio;
};
HGCISConfig colorCorrect;
HGCISConfig color;
HGCISConfig grayCorrect;
HGCISConfig gray;
}HGCorrectConfigs;
typedef tagOutHole OutHole,*pOutHole;
typedef struct Correct_Param {
unsigned int Exposures[6];
unsigned int Gain[12];
unsigned int Offset[12];
}CorrectParam;
#define CAPTION_LEN 256
#define TWAIN_IMAGE_FILE_LIST_NAME TEXT(".dat")
typedef struct CaptureParams
{
#ifndef malloc_my
#define malloc_my malloc
#endif
*/
//#define TWSS_A4R 60
//enum TwSS
//{
// None = 0,
// A4Letter = 1,
// A4 = 1,
// B5Letter = 2,
// JISB5 = 2,
// B5 = 2,
// USLetter = 3,
// USLegal = 4,
// A5 = 5,
// B4 = 6,
// ISOB4 = 6,
// B6 = 7,
// ISOB6 = 7,
// USLedger = 9,
// USExecutive = 10,
// A3 = 11,
// B3 = 12,
// ISOB3 = 12,
// A6 = 13,
// C4 = 14,
// C5 = 15,
// C6 = 16,
// _4A0 = 17,
// _2A0 = 18,
// A0 = 19,
// A1 = 20,
// A2 = 21,
// A7 = 22,
// A8 = 23,
// A9 = 24,
// A10 = 25,
// ISOB0 = 26,
// ISOB1 = 27,
// ISOB2 = 28,
// ISOB5 = 29,
// ISOB7 = 30,
// ISOB8 = 31,
// ISOB9 = 32,
// ISOB10 = 33,
// JISB0 = 34,
// JISB1 = 35,
// JISB2 = 36,
// JISB3 = 37,
// JISB4 = 38,
// JISB6 = 39,
// JISB7 = 40,
// JISB8 = 41,
// JISB9 = 42,
// JISB10 = 43,
// C0 = 44,
// C1 = 45,
// C2 = 46,
// C3 = 47,
// C7 = 48,
// C8 = 49,
// C9 = 50,
// C10 = 51,
// USStatement = 52,
// BusinessCard = 53,
// A4R = 60,
// A5R = 61,
// A6R = 62,
// B5R = 70,
// B6R = 71,
// USLetterR = 80,
// DOUBLELetter = 81,
// AUTO = 90
//};
int correctColorExposure[6];
int correctColorGain[12];
int correctColorOffset[12];
int correctGrayExposure[6];
int correctGrayGain[12];
int correctGrayOffset[12];
int colorExposure[6];
int colorGain[12];
int colorOffset[12];
int grayExposure[6];
int grayGain[12];
int grayOffset[12];
int uvCorrectColorExposure[2];
int uvCorrectGrayExposure[2];
int uvColorExposure[2];
int uvGrayExposure[2];
} CaptureParams;
typedef struct tagTWAIN_IMAGE_FILE_LIST
{

Binary file not shown.

98
HuaGoCorrect/ThreadPool.h Normal file
View File

@ -0,0 +1,98 @@
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
class ThreadPool {
public:
ThreadPool(size_t);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
#endif

399
HuaGoCorrect/commondef.h Normal file
View File

@ -0,0 +1,399 @@
#pragma once
#include <rpcndr.h>
typedef struct tag_USBCB {
int u32_CMD;
int u32_Data;
int u32_Count;
}USBCB, * PUSBCB;
typedef struct tag_USBCBA4
{
unsigned int u32_Command; /* command to execute */
unsigned int u32_Data; /* generic data field */
unsigned int u32_Count; /* number of bytes to transfer */
byte buffer[512]; //=new byte[1024];
}USBCBA4, * PUSBCBA4;
//u32_CMD
enum tagUsbKeyWords :unsigned int
{
NO_COMMAND = 0,
//获取dsp 状态
GET_DSP_STATUS = 1,
//取图
GET_IMAGE = 2,
//销毁DSP中驻存的图
POP_IMAGE = 3,
//开始扫描命令
START_COMMAND = 4,
//停止扫描命令
STOP = 5,
//获取扫描仪扫描模式
GET_SCAN_MODE = 6,
//获取固件版本号
GET_FW_VERSION = 7,
//返回PC端的状态
SEND_STATUS_PC = 8,
//下发扫描配置参数
CONFIGURED_DATA = 9,
//下发固件信息
SEND_FW = 10,
//获取扫描参数
GET_CONFIG_DATA = 11,
//获取扫描总张数
GET_SCANN_NUM = 12,
//获取有无纸的状态
GET_PAPERFEEDER_STATUS = 13,
//DSP初始化
INIT_HARDWARE_SYS = 14,
//下发元器件配置参数灰度LED R曝光时间
SEND_COMPONENTS_GR = 15,
//下发元器件配置参数LED G/B曝光时间
SEND_COMPONENTS_GB = 16,
//下发扫描模式
SEND_SCAN_MODE = 17,
//开始进行平场矫正
START_FLAT = 18,
//停止平场矫正
STOP_FLAT = 19,
//下发200dpi彩色平场矫正参数
SEND_200_COLOR_FLAT_DATA = 20,
//下发300dpi彩色平场矫正参数
SEND_300_COLOR_FLAT_DATA = 21,
//获取200dpi彩色平场矫正参数
GET_200_COLOR_FLAT_DATA = 22,
//获取300dpi彩色平场矫正参数
GET_300_COLOR_FLAT_DATA = 23,
//下发200dpi灰度平场校正参数
SEND_200_GRAY_FLAT_DATA = 24,
//下发300dpi灰度平场校正参数
SEND_300_GRAY_FLAT_DATA = 25,
//获取200DPI灰度平场校正参数
GET_200_GRAY_FLAT_DATA = 26,
//获取300DPI灰度平场校正参数
GET_300_GRAY_FLAT_DATA = 27,
//下发序列号命令
SEND_SERIAL = 28,
//获取序列号命令
GET_SERIAL = 29,
//获取滚轴数
GET_ROLLER_NUM = 0x1e,
//清零滚轴数
CLR_ROLLER_NUM = 0x1f,
//清除扫描总张数
CLR_SCAN_NUM = 0x20,
//准备更新固件
PRE_UPGRADE = 0X21,
//开始更新固件
START_UPGRADE = 0x22,
//彩色的AD参数
RGB_ADI_PARA = 0x23,
//灰度的AD参数
ADI_PARA = 0x24,
//获取CIS参数曝光时间ad参数)
GET_CIS_PARA = 0x25,
//扫描张数
START_COMMAND_COUNT = 0x26,
//下发休眠时间
SET_SLEEP_TIME = 0x27,
//获取休眠时间
GET_SLEEP_TIME = 0x28,
//清除缓存
CLR_CACHE = 0x29,
//下发速度模式
SET_SPEED_MODE = 0x2a,
//获取扫描速度模式
GET_SPEED_MODE = 0X2b,
//设置固件版本一共8个字节
SET_FW_VERSION = 0X2c,
//获取DSP版本
GET_DSP_VERSION = 0X2d,
//采集板FPGA固件版本
GET_SCANFPGA_VERSION = 0x2e,
//电机板FPGA固件版本
GET_MOTORFPGA_VERSION = 0X2f,
//设置制造商信息
SET_USB_INFOR_MANUFACTURE = 0X30,
//获取制造商信息
GET_USB_INFOR_MANUFACTURE = 0X31,
//设置产品型号信息
SET_USB_INFOR_MODEL_NAME = 0X32,
//获取产品型号信息
GET_USB_INFOR_MODEL_NAME = 0X33,
//设置USB PID / VID信息
SET_USB_INFOR_VIDPID = 0X34,
GET_USB_INFOR_VIDPID = 0X35,
//设置卡纸急停检测灵敏度
SET_JAM_DETECT_SENSITIVE = 0X36,
//获取卡纸急停检测灵敏度
GET_JAM_DETECT_SENSITIVE = 0X37,
//设置横向畸变系数
SET_JUST_COF_H = 0x38,
//读取横向畸变系数
GET_JUST_COF_H = 0x39,
//G400 清除硬件异常
CLEAR_HWERROR = 0x40,
//设置纵向畸变系数
SET_JUST_COF_V = 0x41,
//读取纵向畸变系数
GET_JUST_COF_V = 0x42,
//设置彩色校正参数
SEND_COLOR_FLAT = 0x43,
//设置彩色平场校正参数
SEND_COLORCORRECT_FLAT = 0x44,
//设置灰度校正参数
SEND_GRAY_FLAT = 0x45,
//设置灰度平场校正参数
SEND_GRAYCORRECT_FLAT = 0x46,
//设置平场校正参数
GET_FLAT_DATA = 0x47,
//更新完成
UPDATE_FINISHED = 0x48,
//
REBOOT = 0x49,
GET_LOG_FILES_INFO = 0x50,
//发送log文件完成
GET_UPDATE_RESULT = 0x51,
//清空日志
CLEAR_LOG_FILES = 0x52,
//获取搓纸失败
GET_CUO_ERROR,
//获取双张失败次数
GET_DOU_ERROR,
//获取卡纸次数
GET_JAM_ERROR,
GET_UV_EXPOSA = 0x100,
GET_UV_EXPOSB = 0x101,
SET_UV_EXPOSA = 0x102,
SET_UV_EXPOSB = 0x103
};
typedef enum tagUsbKeyWords UsbKeyWords, * PUsbKeyWords;
//u32_Data
enum tagUsbSupported
{
//停止扫描
SCAN_STOP = -2,
//异常
HAVE_ERROR = -1,
//正常状态
NORMAL = 0,
//开盖
OPEN_COVER = 1,
// 无纸
NO_FEED = 2,
// 搓纸失败
FEED_IN_ERROR = 4,
// 卡纸
PAPER_JAM = 8,
// 检测到双张
DETECT_DOUBLE_FEED = 16,
// 检测到订书钉
DETECT_STAPLE = 32,
// 纸张倾斜
PAPER_SKEW = 64,
// 自动模式
AUTO_SCAN_MODE = 65,
// 手动模式
MANAUL_SCAN_MODE = 66,
// 计数模式
COUNT_MODE = 67,
// 硬件错误
HARDWARE_ERROR = 68,
// FPGA崩溃
FPGA_ERROR = 68,
// 开始
START_SCAN = 69,
//停止
STOP_SCAN = 70,
//有图
HAVE_IMAGE = 71,
// 更新扫描参数
UPDATE_SCAN_PARAMETER = 72,
// PC繁忙或出错
PC_SCAN_BUSY_or_ERROR = 73,
// 更新完成
STS_UPDATE_FINISHED = 74,//confilict whit DOG_EAR
//幅面检测错误
SIZE_ERROR = 75,
//取图超时
AQUIRE_IMAGE_TIMEOUT = 76,
//获取图片与扫描张数不匹配
LOSE_IMAGE = 77,
//usb读取数据错误
USB_BULK_ERROR = 78,
//v4l2取图失败
V4L2_AQULRE_ERROR = 79,
//扫描仪内部图片丢失
V4L2_IMAGE_EMPTY = 80,
//USB 未连接
USB_DISCONNECTED = 200,
//用户点击停止
USER_STOP = 201,
//自动平场校正完成
AUTO_FLAT_FINISHED = 202
};
typedef enum tagUsbSupported UsbSupported, * PUsbSupported;
enum tagDevState
{
DEV_STOP = -1,
DEV_ISRUNNING,
DEV_WRONG
};
typedef enum tagDevState DevState, PDevState;
enum tagEventIndex
{
EVENT_IMAGE,
EVENT_NUM
};
enum tagDEVMODEL
{
G100 = 0,
G200,
G300,
G400,
G500
};
#define USB_REQ_GET_FPGA_REGS 0x40
#define USB_REQ_SET_FPGA_REGS 0x41
#define USB_REQ_GET_MOTOR_REGS 0x42
#define USB_REQ_SET_MOTOR_REGS 0x43
#define USB_REQ_GET_DEV_STATUS 0x60
#define USB_REQ_GET_DEV_CONFIGURATION 0x61
#define USB_REQ_SET_DEV_CONFIGURATION 0x62
#define USB_REQ_GET_DEV_REGS 0x63
#define USB_REQ_SET_DEV_REGS 0x64
enum Scanner_Reg_Defs
{
SR_CMD,
SR_STATUS,
SR_SCAN_COUNT,
SR_OS,
SR_SENSORS,
SR_MOTOR,
SR_IM_TYPE,
SR_IM_COUNT,
SR_IM_TX,
SR_IM_FRONT_SIZE,
SR_IM_CLEAR,
SR_IM_TXING,
SR_IM_POP,
SR_IM_ABORT,
SR_COUNT,
SR_CONFIG_SCAN_PARAM,
SR_GET_FWVERSION,
SR_SET_FWERSION,
SR_GET_SERIALNUM,
SR_SET_SERIALNUM,
SR_CONFIF_IMGPROCPARAM,
SC_AUTOCORRECT,
SC_GET_CORRECT_PARAM,
SC_SET_CORRECT_PARAM,
SR_GET_H_RATIO,
SR_SET_H_RATIO,
SR_GET_V_RATIO,
SR_SET_V_RATIO,
SR_GET_SERIAL_LEN,
SR_GET_GRAY_SP,
SR_GET_COLOR_SP,
SR_SET_GRAY_SP,
SR_SET_COLOR_SP,
SR_SET_SLEEPTIME,
SR_GET_SLEEPTIME,
SR_GET_SLEEP_STAUTUS,
SR_GET_CUO_ERROR = 0x50,
SR_GET_DOU_ERROR,
SR_GET_JAM_ERROR,
SR_GET_SCANN_NUM,
SR_CLR_ROLLER_NUM,
SR_GET_ROLLER_NUM,
SR_CLR_SCANN_NUM,
SR_UPDATA_START = 0x100,
SR_UPDATA_STAUTUS = 0x101,
SR_UPDATA_MD5_RELUST = 0x102,
SR_UPDATA_RECOVERY = 0x103,
SR_UPDATA_REBOOT = 0x104,
SR_POWEROFF = 0x105,
SR_REBOOT = 0x106
};
enum Scanner_Cmd_Defs
{
SC_START,
SC_STOP,
SC_CLEAR,
SC_COUNT
};
enum Updata_Stautus {
Start_updata,
Download_file,
Download_file_error,
Download_file_finish,
MD5_Reovery,
MD5_Rboot,
MD5_Error,
Reboot
};
enum HGType
{
MtBoard = 1,
FPGA,
V4L2,
IMG,
STOPSCAN,
};
typedef union HG_ScanConfig
{
unsigned int value;
struct
{
unsigned int paper : 5;
unsigned int color : 1;
unsigned int dpi : 2;
unsigned int double_feed_enbale : 1;
unsigned int stable_enbale : 1;
unsigned int screw_detect_enable : 1;
unsigned int screw_detect_level : 3;//第十四位
unsigned int iscorrect_mode : 1;
unsigned int unused_one : 5;
unsigned int pc_correct : 1;
unsigned int enable_sizecheck : 1;
unsigned int enabledsp_cache : 1;
unsigned int sizeerror_errorratio : 9;
}g200params;
struct
{
unsigned int pageSize : 5;
unsigned int isColor : 1;
unsigned int dpi : 2;
unsigned int doubleFeeded : 1;
unsigned int enableStable : 1;
unsigned int enableLed : 1;
unsigned int reversed1 : 6;
unsigned int isCorrect : 1;
unsigned int dstHeight : 8;
unsigned int reversed2 : 6;
}g400params;
}HGScanConfig;
struct HGEIntInfo
{
HGType From;
unsigned int Code;
};

148
HuaGoCorrect/config.json Normal file
View File

@ -0,0 +1,148 @@
{
"Config": {
"ColorExposure": [
259,
259,
259,
259,
259,
259
],
"ColorGain": [
30,
30,
30,
30,
30,
30,
30,
30,
30,
30,
30,
30
],
"ColorOffset": [
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119
],
"CorrectColorExposure": [
238,
238,
238,
238,
238,
238
],
"CorrectColorGain": [
30,
30,
30,
30,
30,
30,
30,
30,
30,
30,
30,
30
],
"CorrectColorOffset": [
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119
],
"CorrectGrayExposure": [
259,
259,
259,
259,
259,
259
],
"CorrectGrayGain": [
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47
],
"CorrectGrayOffset": [
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119
],
"GrayExposure": [
238,
238,
238,
238,
238,
238
],
"GrayGain": [
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47,
47
],
"GrayOffset": [
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119,
119
]
}
}

View File

@ -3,6 +3,7 @@
#include <Windows.h>
#include <io.h>
#include <fstream>
#include <chrono>
class FileTools
{
@ -54,13 +55,31 @@ private:
class StopWatch
{
public:
StopWatch() { valEnd = valStart = clock(); }
void start() { valStart = clock(); }
void stop() { valEnd =clock(); }
double time_run() { return (double)(valEnd - valStart)/CLOCKS_PER_SEC; }
StopWatch() {
_start = std::chrono::steady_clock::now();
}
void reset() {
_start = std::chrono::steady_clock::now();
}
double elapsed_s() {
return std::chrono::duration<double>(std::chrono::steady_clock::now() - _start).count();
}
double elapsed_ms() {
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - _start).count();
}
double elapsed_us() {
return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - _start).count();
}
double elapsed_ns() {
return std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - _start).count();
}
private:
clock_t valStart;
clock_t valEnd;
std::chrono::steady_clock::time_point _start;
};

638
HuaGoCorrect/gscan3399.cpp Normal file
View File

@ -0,0 +1,638 @@
#include "stdafx.h"
#include "gscan3399.h"
#include "scn_usb.h"
#include "filetools.h"
#include <opencv2/opencv.hpp>
using namespace cv;
static std::mutex mx_ctrl;
void DoEvents() {
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
DispatchMessage(&msg);
TranslateMessage(&msg);
}
}
static int scanner_read_reg(std::shared_ptr<IUsb>& usb, int addr)
{
int val = 0;
std::lock_guard<std::mutex> lck(mx_ctrl);
usb->control_msg(0xc0, USB_REQ_GET_DEV_REGS, addr, 0, 4, &val);
return val;
}
static void scanner_write_reg(std::shared_ptr<IUsb>& usb, int addr, int val)
{
std::lock_guard<std::mutex> lck(mx_ctrl);
usb->control_msg(0x40, USB_REQ_SET_DEV_REGS, addr, 0, 4, &val);
}
static void scanner_cmd(std::shared_ptr<IUsb>& usb, int cmd)
{
scanner_write_reg(usb, 0, cmd);
}
gscan3399::gscan3399() :
m_imgthread(1)
{
im_data.reset(new std::vector<char>());
}
gscan3399::~gscan3399()
{
if (m_usbthread.get() && m_usbthread->joinable())
{
b_usbthread = false;
m_usbthread->join();
m_usbthread.reset();
}
if (m_usb.get())
m_usb.reset();
}
void gscan3399::open(int vid, int pid, int index)
{
if (m_usb.get() && m_usb->is_connected())
return;
auto usbs = UsbScan_List::find_vid_pid(vid, pid);
if (!usbs.empty())
{
m_usb = *usbs.begin();
m_usb->open();
if (m_usb->is_connected())
{
m_usb->set_usbhotplug_callback(gscan3399::usbcallback, this);
}
}
}
int gscan3399::aquire_image(std::string& image, int num)
{
StopWatch sw;
while (true)
{
if ((imgremains == 0) && (!is_runing()))
{
DoEvents();
this_thread::sleep_for(chrono::milliseconds(1));
if (!is_runing())
{
if (devState == DEV_WRONG)
return Error_Code;
return -1;
}
if (sw.elapsed_s() > 30.0)
{
devState = DEV_STOP;
Stop_scan();
ResetScanner();
return AQUIRE_IMAGE_TIMEOUT;
}
}
else
{
if ((m_imagespath.Size() > 0))
{
image = m_imagespath.Take();
imgremains--;
return 0;
}
DoEvents();
this_thread::sleep_for(chrono::milliseconds(2));
}
}
}
bool gscan3399::IsConnected()
{
return true;
}
std::string gscan3399::GetFWVersion()
{
std::string fw = "0123456789";
if (m_usb.get() && m_usb->is_connected())
{
scanner_write_reg(m_usb, SR_GET_FWVERSION, 0);
fw.resize(10);
read_data(&fw[0], fw.length(), 200);
}
return fw;
}
void gscan3399::SetFWVersion()
{
}
std::string gscan3399::GetSerialNum()
{
std::string sr = "01234567890123";
if (m_usb.get() && m_usb->is_connected())
{
int length = scanner_read_reg(m_usb, SR_GET_SERIAL_LEN);
sr.resize(length);
scanner_write_reg(m_usb, SR_GET_SERIALNUM, 0);
read_data(&sr[0], sr.length(), 200);
}
return sr;
}
void gscan3399::SetSerialNum(std::string serial)
{
if (m_usb.get() && m_usb->is_connected())
{
scanner_write_reg(m_usb, SR_SET_SERIALNUM, serial.length());
m_usb->write_bulk(&serial[0], serial.length());
}
}
void gscan3399::SetRatio(int tyepe, int ration)
{
scanner_write_reg(m_usb, tyepe == 0 ? SR_SET_H_RATIO : SR_SET_V_RATIO, ration);
}
void gscan3399::GetRatio(int type, int& ratio)
{
ratio = scanner_read_reg(m_usb, type == 0 ? SR_GET_H_RATIO : SR_GET_V_RATIO);
}
void gscan3399::Reboot()
{
scanner_write_reg(m_usb, SR_REBOOT, 0);
}
void gscan3399::PowerOff()
{
scanner_write_reg(m_usb, SR_POWEROFF, 0);
}
bool gscan3399::is_scan()
{
return 0;
}
bool gscan3399::Get_Scanner_PaperOn()
{
return true;
}
void gscan3399::Config_Scanner(HGScanConfig config)
{
m_config = config;
scanner_write_reg(m_usb, SR_CONFIG_SCAN_PARAM, config.value);
}
void gscan3399::Scanner_StartScan(UINT16 count)
{
scanner_cmd(m_usb, SC_START);
if (m_usbthread.get())
{
b_usbthread = false;
if (m_usbthread->joinable())
{
m_usbthread->join();
m_usbthread.reset();
}
}
b_usbthread = true;
m_usbthread.reset(new thread(&gscan3399::usb_run, this));
}
void gscan3399::Stop_scan()
{
scanner_cmd(m_usb, SC_STOP);
}
void gscan3399::ResetScanner()
{
}
bool gscan3399::Get_IsImageQueueEmpty()
{
return true;
}
void gscan3399::reset()
{
}
void gscan3399::run()
{
}
int gscan3399::get_decompress_pix_type()
{
return 0;
}
void gscan3399::set_decompress_pix_type(int pixtype)
{
}
bool gscan3399::Updata(std::string filename, std::function<void(long, long)> func)
{
std::ifstream updatefile;
updatefile.open(filename, std::ios_base::in | std::ios_base::binary);
if (!updatefile.is_open())
{
return false;
}
updatefile.seekg(0, std::ios::end);
size_t length = updatefile.tellg();
func(0, length);
updatefile.seekg(0, std::ios::beg);
scanner_write_reg(m_usb, 0x100, length);
size_t nreaded = 0;
size_t nleft = length;
int buffersize = 512 * 1024;
if (length <= buffersize)//小于1MB
{
char* uotstream = new char[length];
updatefile.read(uotstream, length);
m_usb->write_bulk(uotstream, length);
delete[] uotstream;
}
else
{
while (true)
{
int ntotransfer;
if (nleft < buffersize)
ntotransfer = nleft;
else
ntotransfer = buffersize;
std::vector<char> data;
data.resize(ntotransfer);
updatefile.read(data.data(), ntotransfer);
m_usb->write_bulk(data.data(), ntotransfer);
nreaded += ntotransfer;
nleft -= ntotransfer;
func(nreaded, length);
if (nreaded >= length)
break;
this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
this_thread::sleep_for(std::chrono::milliseconds(200));
if (!scanner_read_reg(m_usb, 0x101))
return false;
auto now = std::chrono::steady_clock::now();
while (std::chrono::duration<double>(std::chrono::steady_clock::now() - now).count() < 60)
{
int status= scanner_read_reg(m_usb, 0x102);
if (status == 2)
{
scanner_read_reg(m_usb, 0x104);
return true;
}
if (status == 3)
{
scanner_read_reg(m_usb, 0x103);
return true;
}
if (status == 6)
{
return false;
}
this_thread::sleep_for(std::chrono::milliseconds(20));
}
return false;
}
void gscan3399::SetIsDuplex(bool value)
{
}
void gscan3399::ActiveteUSB()
{
}
int gscan3399::GetScanNum()
{
return scanner_read_reg(m_usb, SR_SCAN_COUNT);
}
void gscan3399::ClrRollerNum()
{
}
void gscan3399::ClrScanNum()
{
}
void gscan3399::SendFlatData(CorrectParam param, int index)
{
if (m_usb.get() && m_usb->is_connected())
{
scanner_write_reg(m_usb, SC_SET_CORRECT_PARAM, index);
HGCISConfig cisconfig = { 0 };
int t_index = index;
memcpy(cisconfig.expF, param.Exposures, sizeof(u32) * 3);
memcpy(cisconfig.expB, &param.Exposures[0] + 3, sizeof(u32) * 3);
memcpy(cisconfig.gainF, param.Gain, sizeof(u32) * 6);
memcpy(cisconfig.gainB, &param.Gain[0] + 6, sizeof(u32) * 6);
memcpy(cisconfig.offsetsF, param.Offset, sizeof(u32) * 6);
memcpy(cisconfig.offsetsB, &param.Offset[0] + 6, sizeof(u32) * 6);
m_usb->write_bulk(&cisconfig, sizeof(HGCISConfig));
}
}
CaptureParams gscan3399::GetFlatData()
{
CaptureParams param;
HGCorrectConfigs cisconfigs = { 0 };
scanner_write_reg(m_usb, SC_GET_CORRECT_PARAM, 0);
m_usb->read_bulk(&cisconfigs, sizeof(HGCorrectConfigs));
for (size_t i = 0; i < 2; i++)
{
memcpy(&param.correctColorExposure[0] + i * 3, i == 0 ? &cisconfigs.colorCorrect.expF[0] : &cisconfigs.colorCorrect.expB[0], sizeof(u32) * 3);
memcpy(&param.colorExposure[0] + i * 3, i == 0 ? &cisconfigs.color.expF[0] : &cisconfigs.color.expB[0], sizeof(u32) * 3);
memcpy(&param.correctGrayExposure[0] + i * 3, i == 0 ? &cisconfigs.grayCorrect.expF[0] : &cisconfigs.grayCorrect.expB[0], sizeof(u32) * 3);
memcpy(&param.grayExposure[0] + i * 3, i == 0 ? &cisconfigs.gray.expF[0] : &cisconfigs.gray.expB[0], sizeof(u32) * 3);
memcpy(&param.correctColorGain[0] + i * 6, i == 0 ? &cisconfigs.colorCorrect.gainF[0] : &cisconfigs.colorCorrect.gainB[0], sizeof(u32) * 6);
memcpy(&param.colorGain[0] + i * 6, i == 0 ? &cisconfigs.color.gainF[0] : &cisconfigs.color.gainB[0], sizeof(u32) * 6);
memcpy(&param.correctGrayGain[0] + i * 6, i == 0 ? &cisconfigs.grayCorrect.gainF[0] : &cisconfigs.grayCorrect.gainB[0], sizeof(u32) * 6);
memcpy(&param.grayGain[0] + i * 6, i == 0 ? &cisconfigs.gray.gainF[0] : &cisconfigs.gray.gainB[0], sizeof(u32) * 6);
memcpy(&param.correctColorOffset[0] + i * 6, i == 0 ? &cisconfigs.colorCorrect.offsetsF[0] : &cisconfigs.colorCorrect.offsetsB[0], sizeof(u32) * 6);
memcpy(&param.colorOffset[0] + i * 6, i == 0 ? &cisconfigs.color.offsetsF[0] : &cisconfigs.color.offsetsB[0], sizeof(u32) * 6);
memcpy(&param.correctGrayOffset[0] + i * 6, i == 0 ? &cisconfigs.grayCorrect.offsetsF[0] : &cisconfigs.grayCorrect.offsetsB[0], sizeof(u32) * 6);
memcpy(&param.grayOffset[0] + i * 6, i == 0 ? &cisconfigs.gray.offsetsF[0] : &cisconfigs.gray.offsetsB[0], sizeof(u32) * 6);
}
return param;
}
void gscan3399::StartFlat(bool iscolor)
{
int color = iscolor ? 1 : 0;
scanner_write_reg(m_usb, SC_AUTOCORRECT, color);
unsigned char buff[64] = { 0 };
StopWatch sw;
while (sw.elapsed_s() < 120)
{
auto lenght = m_usb->read_int(buff, sizeof(buff));
if (lenght == sizeof(buff))
{
HGEIntInfo info = *(HGEIntInfo*)&buff;
if (info.From == 5 && info.Code == 6)
break;
}
this_thread::sleep_for(chrono::milliseconds(30));
DoEvents();
}
if(sw.elapsed_s()<120)
MessageBox(NULL, TEXT(iscolor?"彩色自动校正已完成!":"灰度自动校正已完成!"), TEXT("提示"), MB_OK);
else
MessageBox(NULL, TEXT(iscolor ? "彩色自动校正失败!" : "彩色自动校正失败!"), TEXT("提示"), MB_OK);
}
void gscan3399::DevStateChange()
{
}
int gscan3399::getMatSum()
{
return 0;
}
void gscan3399::close()
{
if (m_usb.get())
m_usb->close();
}
void gscan3399::GetExpose(int& Aside, int& Bside)
{
}
void gscan3399::SetExpose(int aside, int bside)
{
}
void gscan3399::GetSptime(int type, int& time)
{
if (type == 0)
time = scanner_read_reg(m_usb, SR_GET_GRAY_SP);
if (type == 1)
time = scanner_read_reg(m_usb, SR_GET_COLOR_SP);
}
void gscan3399::SetSptime(int type, int time)
{
if (type == 0)
scanner_write_reg(m_usb, SR_SET_GRAY_SP, time);
if (type == 1)
scanner_write_reg(m_usb, SR_SET_COLOR_SP, time);
}
void gscan3399::GetSleepTime(int& sleeptime)
{
sleeptime = scanner_read_reg(m_usb, SR_GET_SLEEPTIME);
}
void gscan3399::SetSleepTime(int sleeptime)
{
scanner_write_reg(m_usb, SR_SET_SLEEPTIME, sleeptime);
}
void gscan3399::usbcallback(bool isleft, void* usrdata)
{
gscan3399* This = (gscan3399*)usrdata;
This->OnUsbHotplug(isleft);
}
int gscan3399::read_data(void* data, int length, int timeout)
{
int nread = 0;
int reading = 0;
const int buffer_size = 2 * 1024 * 1024;
StopWatch sw;
while (nread < length && sw.elapsed_ms() < timeout) {
reading = std::max(0, std::min(length - nread, buffer_size));
reading = m_usb->read_bulk((unsigned char*)data + nread, reading);
if (reading > 0) {
nread += reading;
}
}
return nread;
}
void gscan3399::get_imgdata()
{
m_imgthread.enqueue([this] {
while (get_imgremains())
{
if (is_bulktransferring())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
imgremains++;
auto& buffi = im_data;
int count = front_datasize();
buffi->resize(count);
bulk_starttransfer();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
count = read_data(buffi->data(), count, count / (0.01 * 1024 * 1024));
popimg();
imgproce(buffi);
}
});
}
bool gscan3399::is_runing()
{
return scanner_read_reg(m_usb, SR_STATUS) & 0x01;
}
bool gscan3399::bulk_starttransfer()
{
scanner_write_reg(m_usb, SR_IM_TX, 1);
return true;
}
bool gscan3399::is_bulktransferring()
{
return scanner_read_reg(m_usb, SR_IM_TXING);
}
void gscan3399::popimg()
{
scanner_write_reg(m_usb, SR_IM_POP, 1); //!< to-list
}
int gscan3399::front_datasize()
{
return scanner_read_reg(m_usb, SR_IM_FRONT_SIZE);
}
int gscan3399::get_imgremains()
{
return scanner_read_reg(m_usb, SR_IM_COUNT); //!< to-list ;
}
void gscan3399::imgproce(std::shared_ptr<std::vector<char>>& buffs)
{
vector<cv::Mat> mats;
bool isbwimg = false;
auto rmc = m_config.g200params.color? cv::IMREAD_COLOR:cv::IMREAD_GRAYSCALE;
if (buffs->at(0) == -119 && buffs->at(1) == 0x50 && buffs->at(2) == 0x4e && buffs->at(3) == 0x47)//blackwhite
{
isbwimg = true;
rmc = cv::IMREAD_GRAYSCALE;
}
cv::Mat mat = cv::imdecode(*buffs, rmc);
time_t timp;
tm* p;
time(&timp);
p = localtime(&timp);
std::string filename = std::to_string(p->tm_hour) + "_" + std::to_string(p->tm_min) + "_" + std::to_string(p->tm_sec);
static int indeximg = 0;
std::string path = csPath+"\\"+filename + ".png";
if (!mat.empty()) {
cv::imwrite(path, mat);
m_imagespath.Put(path);
}
}
void gscan3399::OnUsbHotplug(bool isleft)
{
}
void gscan3399::usb_run()
{
unsigned char buff[64];
while (b_usbthread)
{
if (!m_usb.get() || !m_usb->is_connected())
{
this_thread::sleep_for(chrono::milliseconds(20));
continue;
}
memset(buff, 0, sizeof(buff));
auto length = m_usb->read_int(buff, sizeof(buff));
if (((length) == sizeof(buff)) || is_bulktransferring())
{
HGEIntInfo info = *(HGEIntInfo*)&buff;
switch (info.From)
{
case IMG:
if (is_runing())
get_imgdata();
break;
default:
break;
}
Error_Code = codeconvter(info);
if (Error_Code != 0)
{
devState = Error_Code == -1 ? DEV_STOP : DEV_WRONG;
}
this_thread::sleep_for(chrono::microseconds(2));
}
}
}
int gscan3399::codeconvter(HGEIntInfo code)
{
if (code.From == HGType::FPGA)
{
switch (code.Code)
{
default:
break;
}
}
if (code.From == HGType::MtBoard)
{
switch (code.Code)
{
case 0x00002:
return NO_FEED;
case 0x00004:
return OPEN_COVER;
case 0x00008:
return FEED_IN_ERROR;
case 0x00010:
return PAPER_JAM;
case 0x00020:
return DETECT_DOUBLE_FEED;
case 0x00040:
return DETECT_STAPLE;
case 0x00080:
return PAPER_SKEW;
case 0x10000:
return AQUIRE_IMAGE_TIMEOUT;
case 0x20000:
return SIZE_ERROR;
default:
break;
}
}
if (code.From == HGType::V4L2)
{
switch (code.Code)
{
case 0:
return V4L2_AQULRE_ERROR;
break;
case 1:
return V4L2_IMAGE_EMPTY;
default:
break;
}
}
if (code.From == HGType::STOPSCAN)
return -1;
return 0;
}

91
HuaGoCorrect/gscan3399.h Normal file
View File

@ -0,0 +1,91 @@
#pragma once
#include "IScanner.h"
#include "ThreadPool.h"
#include <thread>
#include <chrono>
class gscan3399 :public IScanner
{
public:
gscan3399();
virtual ~gscan3399();
virtual void open(int vid, int pid, int index);
virtual int aquire_image(std::string& image, int num);
virtual bool IsConnected();
virtual std::string GetFWVersion();
virtual void SetFWVersion();
virtual std::string GetSerialNum();
virtual void SetSerialNum(std::string serial);
virtual void SetRatio(int tyepe, int ration);
virtual void GetRatio(int type, int& ratio);
virtual void Reboot();
virtual void PowerOff();
virtual bool is_scan();
virtual bool Get_Scanner_PaperOn();
virtual void Config_Scanner(HGScanConfig config);
virtual void Scanner_StartScan(UINT16 count);
virtual void Stop_scan();
virtual void ResetScanner();
virtual bool Get_IsImageQueueEmpty();
virtual void reset();
virtual void run();
virtual int get_decompress_pix_type();
virtual void set_decompress_pix_type(int pixtype);
virtual bool Updata(std::string filename, std::function<void(long, long)> func);
virtual void SetIsDuplex(bool value);
virtual void ActiveteUSB();
virtual int GetScanNum();
virtual void ClrRollerNum();
virtual void ClrScanNum();
virtual void SendFlatData(CorrectParam param, int index);
virtual CaptureParams GetFlatData();
virtual void StartFlat(bool iscolor);
virtual void DevStateChange();
virtual int getMatSum();
virtual void close();
virtual void GetExpose(int& Aside, int& Bside);
virtual void SetExpose(int aside, int bside);
virtual void GetSptime(int type, int& time);
virtual void SetSptime(int type, int time);
virtual void GetSleepTime(int& sleeptime);
virtual void SetSleepTime(int sleeptime);
private:
static void usbcallback(bool isleft, void* usrdata);
int read_data(void* data, int length, int timeout);
void get_imgdata();
bool is_runing();
bool bulk_starttransfer();
bool is_bulktransferring();
void popimg();
int front_datasize();
int get_imgremains();
void imgproce(std::shared_ptr<std::vector<char>>& buffs);
void OnUsbHotplug(bool isleft);
void usb_run();
int codeconvter(HGEIntInfo code);
private:
volatile int devState;
volatile int Error_Code;
volatile bool b_usbthread;
ThreadPool m_imgthread;
std::shared_ptr<std::thread> m_usbthread;
std::shared_ptr<std::vector<char>> im_data;
BlockingQueue<std::string> m_imagespath;
std::atomic_int imgremains;
HGScanConfig m_config;
};

File diff suppressed because it is too large Load Diff

View File

@ -1,375 +1,98 @@
#pragma once
#include "scn_usb.h"
#include "IUsb.h"
#include <memory>
#include <vector>
#include <string>
#include <queue>
#include <Windows.h>
#include "MutexEx.h"
#include "opencv2/core/core.hpp"
#include <opencv2\highgui\highgui.hpp>
#include "jpeglib.h"
#include <time.h>
#include <thread>
#include <mutex>
#include "ImageMatQueue.h"
#include <map>
#include "PublicFunc.h"
#include "HuaGoCorrect.h"
#include "IScanner.h"
using namespace cv;
typedef struct tag_USBCB {
UINT32 u32_CMD;
UINT32 u32_Data;
UINT32 u32_Count;
}USBCB, *PUSBCB;
typedef struct tag_USBCBA4
{
UINT u32_Command; /* command to execute */
UINT u32_Data; /* generic data field */
UINT u32_Count; /* number of bytes to transfer */
byte buffer[512]; //=new byte[1024];
}USBCBA4, *PUSBCBA4;
//u32_CMD
enum tagUsbKeyWords :UINT32
{
//无命令
NO_COMMAND = 0,
//获取dsp 状态
GET_DSP_STATUS = 1,
//取图
GET_IMAGE = 2,
//销毁DSP中驻存的图
POP_IMAGE = 3,
//开始扫描命令
START_COMMAND = 4,
//停止扫描命令
STOP = 5,
//获取扫描仪扫描模式
GET_SCAN_MODE = 6,
//获取固件版本号
GET_FW_VERSION = 7,
//返回PC端的状态
SEND_STATUS_PC = 8,
//下发扫描配置参数
CONFIGURED_DATA = 9,
//下发固件信息
SEND_FW = 10,
//获取扫描参数
GET_CONFIG_DATA = 11,
//获取扫描总张数
GET_SCANN_NUM = 12,
//获取有无纸的状态
GET_PAPERFEEDER_STATUS = 13,
//DSP初始化
INIT_HARDWARE_SYS = 14,
//获取有无纸的状态
GET_PAPER_STATUS = 0x0d,
//下发元器件配置参数灰度LED R曝光时间
SEND_COMPONENTS_GR = 15,
//下发元器件配置参数LED G/B曝光时间
SEND_COMPONENTS_GB = 16,
//下发扫描模式
SEND_SCAN_MODE = 17,
//开始进行平场矫正
START_FLAT = 18,
//停止平场矫正
STOP_FLAT = 19,
//下发200dpi彩色平场矫正参数
SEND_200_COLOR_FLAT_DATA = 20,
//下发300dpi彩色平场矫正参数
SEND_300_COLOR_FLAT_DATA = 21,
//获取200dpi彩色平场矫正参数
GET_200_COLOR_FLAT_DATA = 22,
//获取300dpi彩色平场矫正参数
GET_300_COLOR_FLAT_DATA = 23,
//下发200dpi灰度平场校正参数
SEND_200_GRAY_FLAT_DATA = 24,
//下发300dpi灰度平场校正参数
SEND_300_GRAY_FLAT_DATA = 25,
//获取200DPI灰度平场校正参数
GET_200_GRAY_FLAT_DATA = 26,
//获取300DPI灰度平场校正参数
GET_300_GRAY_FLAT_DATA = 27,
//下发序列号命令
SEND_SERIAL = 28,
//获取序列号命令
GET_SERIAL = 29,
//获取滚轮张数
GET_ROLLER_NUM = 30,
//清零滚轮张数
CLR_ROLLER_NUM = 31,
//清零扫描总张数
CLR_SCAN_NUM = 32,
PRE_UPGRADE =33,
START_UPGRADE = 34,
RGB_ADI_PARA =35,
ADI_PARA =36,
GET_CIS_PARA =37,
SEND_COLOR_FLAT = 41,
SEND_COLORCORRECT_FLAT=42,
SEND_GRAY_FLAT=43,
SEND_GRAYCORRECT_FLAT=44,
GET_FLAT_DATA=45,
//设置横向畸变系数
SET_JUST_COF_H = 0x38,
//读取横向畸变系数
GET_JUST_COF_H = 0x39,
//设置纵向畸变系数
SET_JUST_COF_V = 0x41,
//读取纵向畸变系数
GET_JUST_COF_V
};
typedef enum tagUsbKeyWords UsbKeyWords, *PUsbKeyWords;
//u32_Data
enum tagUsbSupported
{
//停止扫描
SCAN_STOP = -2,
//异常
HAVE_ERROR = -1,
//正常状态
NORMAL = 0,
//开盖
OPEN_COVER = 1,
// 无纸
NO_FEED = 2,
// 搓纸失败
FEED_IN_ERROR = 4,
// 卡纸
PAPER_JAM = 8,
// 检测到双张
DETECT_DOUBLE_FEED = 16,
// 检测到订书钉
DETECT_STAPLE = 32,
// 纸张倾斜
PAPER_SKEW = 64,
// 自动模式
AUTO_SCAN_MODE = 65,
// 手动模式
MANAUL_SCAN_MODE = 66,
// 计数模式
COUNT_MODE = 67,
// 硬件错误
HARDWARE_ERROR = 68,
// FPGA崩溃
FPGA_ERROR = 68,
// 开始
START_SCAN = 69,
//停止
STOP_SCAN = 70,
//有图
HAVE_IMAGE = 71,
// 更新扫描参数
UPDATE_SCAN_PARAMETER = 72,
// PC繁忙或出错
PC_SCAN_BUSY_or_ERROR = 73
};
typedef enum tagUsbSupported UsbSupported, *PUsbSupported;
enum tagDevState
{
DEV_STOP = -1,
DEV_ISRUNNING,
DEV_WRONG
};
typedef enum tagDevState DevState, PDevState;
enum tagEventIndex
{
EVENT_IMAGE,
EVENT_NUM
};
enum tagDEVMODEL
{
G100=0,
G200,
G300,
G400,
G500
};
class twainImage
{
public:
twainImage(){}
~twainImage()
{
release();
}
twainImage(cv::Mat image,int side=-1)
{
this->m_image=image;
this->m_side=side;
this->m_width=image.cols;
this->m_height=image.rows;
}
bool empty()
{
return m_image.empty();
}
int GetWidth()
{
return m_image.cols;
}
int GetHeight()
{
return m_image.rows;
}
void release()
{
if (!m_image.empty())
{
m_image.release();
}
}
public:
cv::Mat m_image;
int m_side;
private:
int m_height;
int m_width;
};
class GScn_Drv
class GScn_Drv :public IScanner
{
public:
GScn_Drv();
virtual ~GScn_Drv();
virtual void open(int vid, int pid, int index);
virtual int aquire_image(std::string& image, int num);
virtual bool IsConnected();
virtual std::string GetFWVersion();
virtual void SetFWVersion();
virtual std::string GetSerialNum();
virtual void SetSerialNum(std::string serial);
virtual void SetRatio(int tyepe, int ration);
virtual void GetRatio(int type, int& ratio);
virtual void Reboot();
virtual void PowerOff() {};
virtual bool is_scan();
virtual bool Get_Scanner_PaperOn();
virtual void Config_Scanner(PUSBCB pUSBCB);
virtual void Config_Scanner(HGScanConfig config);
virtual void Scanner_StartScan(UINT16 count);
virtual void Stop_scan();
virtual void ResetScanner();
virtual bool Get_IsImageQueueEmpty();
virtual void reset();
virtual void run();
virtual void ActiveteUSB();
virtual bool Updata(std::string filename, std::function<void(long, long)> func);
virtual int GetScanNum();
~GScn_Drv();
void save_config(bool saveOrigin, bool saveFixedOrigin);
void open(int vid, int pid,int index);
void open(int vid);
void close();
int aquire_image(cv::Mat& image,int num);
int aquire_image(cv::Mat& image);
BOOL IsConnected();
void Get_Scanner_Correct_Ratio(float & hrz, float & vtc);
std::string GetFWVersion();
byte* GetSerialNum();
bool is_scan();
USBCB Get_Scanner_Status();
BOOL Get_Scanner_PaperOn();
void Config_Scanner(PUSBCB pUSBCB);
//void setlist(std::vector<std::shared_ptr<CImageApply>> list);
void Scanner_StartScan(UINT16 count);
void Set_Scanner_Correct_Ratio(float hrz, float vtc);
void Stop_scan();
void ResetScanner();
bool Get_IsImageQueueEmpty();
void reset();
INT get_decompress_pix_type();
void set_decompress_pix_type(int pixtype);
virtual void ClrRollerNum();
void enableDiscardBlank(bool bVal);
virtual void ClrScanNum();
void SetIsDuplex(BOOL value);
virtual void SendFlatData(CorrectParam param, int index);
void SetRotate(int rotateType);
virtual CaptureParams GetFlatData();
void SetBackRotate(bool enBackRoate);
virtual void StartFlat(bool iscolor);
std::vector<string> GetSerials(int vid,int pid);
virtual void DevStateChange();
void ActiveteUSB();
virtual int getMatSum();
void SetSerialNum(byte *pvalue);
virtual void close();
int GetScanNum();
virtual void GetExpose(int& Aside, int& Bside);
virtual void SetExpose(int aside, int bside);
void ClrRollerNum();
virtual void GetSptime(int type, int& time);
virtual void SetSptime(int type, int time);
void ClrScanNum();
virtual void GetSleepTime(int& sleeptime);
virtual void SetSleepTime(int sleeptime);
bool SendrAdPara(UINT para);
bool SendrRgbAdPara(UINT para);
bool SenGRPara(UINT para);
bool SenGBPara(UINT para);
void SendColorCorrentFlat(byte buffer[],int size);
void SendColorFlat(byte buffer[],int size);
void SendGrayCorrectFlat(byte buffer[],int size);
void SendGrayFlat(byte buffer[],int size);
byte* GetFlatData();
byte* GetCisPara();
bool FlatA4();
bool FlatA3(UINT para);
void DevStateChange();
int getMatSum();
void SetPath(CString csFilePath)
{
csPath = csFilePath;
}
CString GetPath()
{
return csPath;
}
void setlist(std::vector<std::shared_ptr<CImageApply> >list)
{
m_pImages.setlist(list);
}
bool FlatA4Conrrect();
ImageMatQueue m_pImages;
//HWND h;
int device_id;
bool isusbopened() { return m_usb.is_connected(); }
private:
cscn_usb m_usb;
volatile int devState;
volatile BOOL isDuplex;
volatile bool m_bRun;
std::mutex m_Locker;
std::mutex m_imgLocker;
int pixType;
int m_rotate;
bool backRotate;
BOOL canUseDiscardBlank;
std::thread m_threadUsb;
std::map<int,string> ntcMsg;
std::map<string,int> devType;
std::map<int, string> ntcMsg;
std::map<string, int> devType;
std::vector<string> vcSerials;
int selectDeviceIndex;
int m_scannerType;
CString csPath;
bool m_isScanning;
private:
void run();
cv::Mat popMat(int num);
std::string popMat(int num);
void pushMat(JpegBuffer& data);
USBCB Get_Scanner_Status();
void InitMSGMap();
void InitScannerDiviceMap();
cv::Mat Get_Img_Data(int buffersize);
DWORD usbmain();
void Pop_Image();
HGScanConfig m_config;
};

22875
HuaGoCorrect/json.hpp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -40,8 +40,8 @@
//
//M*/
#ifndef OPENCV_OLD_CV_H
#define OPENCV_OLD_CV_H
#ifndef __OPENCV_OLD_CV_H__
#define __OPENCV_OLD_CV_H__
#if defined(_MSC_VER)
#define CV_DO_PRAGMA(x) __pragma(x)
@ -61,13 +61,22 @@
//CV_WARNING("This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module")
#include "opencv2/core/core_c.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/photo/photo_c.h"
#include "opencv2/video/tracking_c.h"
#include "opencv2/objdetect/objdetect_c.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/flann/flann.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/legacy/compat.hpp"
#if !defined(CV_IMPL)
#define CV_IMPL extern "C"
#endif //CV_IMPL
#if defined(__cplusplus)
#include "opencv2/core/internal.hpp"
#endif //__cplusplus
#endif // __OPENCV_OLD_CV_H_

View File

@ -40,21 +40,13 @@
//
//M*/
#ifndef OPENCV_OLD_CV_HPP
#define OPENCV_OLD_CV_HPP
#ifndef __OPENCV_OLD_CV_HPP__
#define __OPENCV_OLD_CV_HPP__
//#if defined(__GNUC__)
//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module"
//#endif
#include "cv.h"
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/photo.hpp"
#include "opencv2/video.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/objdetect.hpp"
#include <cv.h>
#endif

View File

@ -39,18 +39,26 @@
//
//M*/
#ifndef OPENCV_OLD_AUX_H
#define OPENCV_OLD_AUX_H
#ifndef __OPENCV_OLD_AUX_H__
#define __OPENCV_OLD_AUX_H__
//#if defined(__GNUC__)
//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module"
//#endif
#include "opencv2/core/core_c.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/photo/photo_c.h"
#include "opencv2/video/tracking_c.h"
#include "opencv2/objdetect/objdetect_c.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/legacy/legacy.hpp"
#include "opencv2/legacy/compat.hpp"
#include "opencv2/legacy/blobtrack.hpp"
#include "opencv2/contrib/contrib.hpp"
#endif

View File

@ -39,14 +39,13 @@
//
//M*/
#ifndef OPENCV_OLD_AUX_HPP
#define OPENCV_OLD_AUX_HPP
#ifndef __OPENCV_OLD_AUX_HPP__
#define __OPENCV_OLD_AUX_HPP__
//#if defined(__GNUC__)
//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module"
//#endif
#include "cvaux.h"
#include "opencv2/core/utility.hpp"
#include <cvaux.h>
#endif

View File

@ -38,8 +38,8 @@
// the use of this software, even if advised of the possibility of such damage.
#ifndef OPENCV_OLD_WIMAGE_HPP
#define OPENCV_OLD_WIMAGE_HPP
#ifndef __OPENCV_OLD_WIMAGE_HPP__
#define __OPENCV_OLD_WIMAGE_HPP__
#include "opencv2/core/wimage.hpp"

View File

@ -40,13 +40,14 @@
//
//M*/
#ifndef OPENCV_OLD_CXCORE_H
#define OPENCV_OLD_CXCORE_H
#ifndef __OPENCV_OLD_CXCORE_H__
#define __OPENCV_OLD_CXCORE_H__
//#if defined(__GNUC__)
//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module"
//#endif
#include "opencv2/core/core_c.h"
#include "opencv2/core/core.hpp"
#endif

View File

@ -40,14 +40,13 @@
//
//M*/
#ifndef OPENCV_OLD_CXCORE_HPP
#define OPENCV_OLD_CXCORE_HPP
#ifndef __OPENCV_OLD_CXCORE_HPP__
#define __OPENCV_OLD_CXCORE_HPP__
//#if defined(__GNUC__)
//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module"
//#endif
#include "cxcore.h"
#include "opencv2/core.hpp"
#include <cxcore.h>
#endif

View File

@ -40,8 +40,8 @@
//
//M*/
#ifndef OPENCV_OLD_EIGEN_HPP
#define OPENCV_OLD_EIGEN_HPP
#ifndef __OPENCV_OLD_EIGEN_HPP__
#define __OPENCV_OLD_EIGEN_HPP__
#include "opencv2/core/eigen.hpp"

View File

@ -1,8 +1,6 @@
#ifndef OPENCV_OLD_CXMISC_H
#define OPENCV_OLD_CXMISC_H
#ifndef __OPENCV_OLD_CXMISC_H__
#define __OPENCV_OLD_CXMISC_H__
#ifdef __cplusplus
# include "opencv2/core/utility.hpp"
#endif
#include "opencv2/core/internal.hpp"
#endif

View File

@ -39,10 +39,12 @@
//
//M*/
#ifndef OPENCV_OLD_HIGHGUI_H
#define OPENCV_OLD_HIGHGUI_H
#ifndef __OPENCV_OLD_HIGHGUI_H__
#define __OPENCV_OLD_HIGHGUI_H__
#include "opencv2/core/core_c.h"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/highgui/highgui.hpp"
#endif

View File

@ -38,10 +38,11 @@
//
//M*/
#ifndef OPENCV_OLD_ML_H
#define OPENCV_OLD_ML_H
#ifndef __OPENCV_OLD_ML_H__
#define __OPENCV_OLD_ML_H__
#include "opencv2/core/core_c.h"
#include "opencv2/ml.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/ml/ml.hpp"
#endif

View File

@ -7,12 +7,11 @@
// copy or use the software.
//
//
// License Agreement
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
@ -41,8 +40,772 @@
//
//M*/
#ifdef __OPENCV_BUILD
#error this is a compatibility header which should not be used inside the OpenCV library
#ifndef __OPENCV_CALIB3D_HPP__
#define __OPENCV_CALIB3D_HPP__
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/core/affine.hpp"
#ifdef __cplusplus
extern "C" {
#endif
#include "opencv2/calib3d.hpp"
/****************************************************************************************\
* Camera Calibration, Pose Estimation and Stereo *
\****************************************************************************************/
typedef struct CvPOSITObject CvPOSITObject;
/* Allocates and initializes CvPOSITObject structure before doing cvPOSIT */
CVAPI(CvPOSITObject*) cvCreatePOSITObject( CvPoint3D32f* points, int point_count );
/* Runs POSIT (POSe from ITeration) algorithm for determining 3d position of
an object given its model and projection in a weak-perspective case */
CVAPI(void) cvPOSIT( CvPOSITObject* posit_object, CvPoint2D32f* image_points,
double focal_length, CvTermCriteria criteria,
float* rotation_matrix, float* translation_vector);
/* Releases CvPOSITObject structure */
CVAPI(void) cvReleasePOSITObject( CvPOSITObject** posit_object );
/* updates the number of RANSAC iterations */
CVAPI(int) cvRANSACUpdateNumIters( double p, double err_prob,
int model_points, int max_iters );
CVAPI(void) cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst );
/* Calculates fundamental matrix given a set of corresponding points */
#define CV_FM_7POINT 1
#define CV_FM_8POINT 2
#define CV_LMEDS 4
#define CV_RANSAC 8
#define CV_FM_LMEDS_ONLY CV_LMEDS
#define CV_FM_RANSAC_ONLY CV_RANSAC
#define CV_FM_LMEDS CV_LMEDS
#define CV_FM_RANSAC CV_RANSAC
enum
{
CV_ITERATIVE = 0,
CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation"
CV_P3P = 2 // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem"
};
CVAPI(int) cvFindFundamentalMat( const CvMat* points1, const CvMat* points2,
CvMat* fundamental_matrix,
int method CV_DEFAULT(CV_FM_RANSAC),
double param1 CV_DEFAULT(3.), double param2 CV_DEFAULT(0.99),
CvMat* status CV_DEFAULT(NULL) );
/* For each input point on one of images
computes parameters of the corresponding
epipolar line on the other image */
CVAPI(void) cvComputeCorrespondEpilines( const CvMat* points,
int which_image,
const CvMat* fundamental_matrix,
CvMat* correspondent_lines );
/* Triangulation functions */
CVAPI(void) cvTriangulatePoints(CvMat* projMatr1, CvMat* projMatr2,
CvMat* projPoints1, CvMat* projPoints2,
CvMat* points4D);
CVAPI(void) cvCorrectMatches(CvMat* F, CvMat* points1, CvMat* points2,
CvMat* new_points1, CvMat* new_points2);
/* Computes the optimal new camera matrix according to the free scaling parameter alpha:
alpha=0 - only valid pixels will be retained in the undistorted image
alpha=1 - all the source image pixels will be retained in the undistorted image
*/
CVAPI(void) cvGetOptimalNewCameraMatrix( const CvMat* camera_matrix,
const CvMat* dist_coeffs,
CvSize image_size, double alpha,
CvMat* new_camera_matrix,
CvSize new_imag_size CV_DEFAULT(cvSize(0,0)),
CvRect* valid_pixel_ROI CV_DEFAULT(0),
int center_principal_point CV_DEFAULT(0));
/* Converts rotation vector to rotation matrix or vice versa */
CVAPI(int) cvRodrigues2( const CvMat* src, CvMat* dst,
CvMat* jacobian CV_DEFAULT(0) );
/* Finds perspective transformation between the object plane and image (view) plane */
CVAPI(int) cvFindHomography( const CvMat* src_points,
const CvMat* dst_points,
CvMat* homography,
int method CV_DEFAULT(0),
double ransacReprojThreshold CV_DEFAULT(3),
CvMat* mask CV_DEFAULT(0));
/* Computes RQ decomposition for 3x3 matrices */
CVAPI(void) cvRQDecomp3x3( const CvMat *matrixM, CvMat *matrixR, CvMat *matrixQ,
CvMat *matrixQx CV_DEFAULT(NULL),
CvMat *matrixQy CV_DEFAULT(NULL),
CvMat *matrixQz CV_DEFAULT(NULL),
CvPoint3D64f *eulerAngles CV_DEFAULT(NULL));
/* Computes projection matrix decomposition */
CVAPI(void) cvDecomposeProjectionMatrix( const CvMat *projMatr, CvMat *calibMatr,
CvMat *rotMatr, CvMat *posVect,
CvMat *rotMatrX CV_DEFAULT(NULL),
CvMat *rotMatrY CV_DEFAULT(NULL),
CvMat *rotMatrZ CV_DEFAULT(NULL),
CvPoint3D64f *eulerAngles CV_DEFAULT(NULL));
/* Computes d(AB)/dA and d(AB)/dB */
CVAPI(void) cvCalcMatMulDeriv( const CvMat* A, const CvMat* B, CvMat* dABdA, CvMat* dABdB );
/* Computes r3 = rodrigues(rodrigues(r2)*rodrigues(r1)),
t3 = rodrigues(r2)*t1 + t2 and the respective derivatives */
CVAPI(void) cvComposeRT( const CvMat* _rvec1, const CvMat* _tvec1,
const CvMat* _rvec2, const CvMat* _tvec2,
CvMat* _rvec3, CvMat* _tvec3,
CvMat* dr3dr1 CV_DEFAULT(0), CvMat* dr3dt1 CV_DEFAULT(0),
CvMat* dr3dr2 CV_DEFAULT(0), CvMat* dr3dt2 CV_DEFAULT(0),
CvMat* dt3dr1 CV_DEFAULT(0), CvMat* dt3dt1 CV_DEFAULT(0),
CvMat* dt3dr2 CV_DEFAULT(0), CvMat* dt3dt2 CV_DEFAULT(0) );
/* Projects object points to the view plane using
the specified extrinsic and intrinsic camera parameters */
CVAPI(void) cvProjectPoints2( const CvMat* object_points, const CvMat* rotation_vector,
const CvMat* translation_vector, const CvMat* camera_matrix,
const CvMat* distortion_coeffs, CvMat* image_points,
CvMat* dpdrot CV_DEFAULT(NULL), CvMat* dpdt CV_DEFAULT(NULL),
CvMat* dpdf CV_DEFAULT(NULL), CvMat* dpdc CV_DEFAULT(NULL),
CvMat* dpddist CV_DEFAULT(NULL),
double aspect_ratio CV_DEFAULT(0));
/* Finds extrinsic camera parameters from
a few known corresponding point pairs and intrinsic parameters */
CVAPI(void) cvFindExtrinsicCameraParams2( const CvMat* object_points,
const CvMat* image_points,
const CvMat* camera_matrix,
const CvMat* distortion_coeffs,
CvMat* rotation_vector,
CvMat* translation_vector,
int use_extrinsic_guess CV_DEFAULT(0) );
/* Computes initial estimate of the intrinsic camera parameters
in case of planar calibration target (e.g. chessboard) */
CVAPI(void) cvInitIntrinsicParams2D( const CvMat* object_points,
const CvMat* image_points,
const CvMat* npoints, CvSize image_size,
CvMat* camera_matrix,
double aspect_ratio CV_DEFAULT(1.) );
#define CV_CALIB_CB_ADAPTIVE_THRESH 1
#define CV_CALIB_CB_NORMALIZE_IMAGE 2
#define CV_CALIB_CB_FILTER_QUADS 4
#define CV_CALIB_CB_FAST_CHECK 8
// Performs a fast check if a chessboard is in the input image. This is a workaround to
// a problem of cvFindChessboardCorners being slow on images with no chessboard
// - src: input image
// - size: chessboard size
// Returns 1 if a chessboard can be in this image and findChessboardCorners should be called,
// 0 if there is no chessboard, -1 in case of error
CVAPI(int) cvCheckChessboard(IplImage* src, CvSize size);
/* Detects corners on a chessboard calibration pattern */
CVAPI(int) cvFindChessboardCorners( const void* image, CvSize pattern_size,
CvPoint2D32f* corners,
int* corner_count CV_DEFAULT(NULL),
int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE) );
/* Draws individual chessboard corners or the whole chessboard detected */
CVAPI(void) cvDrawChessboardCorners( CvArr* image, CvSize pattern_size,
CvPoint2D32f* corners,
int count, int pattern_was_found );
#define CV_CALIB_USE_INTRINSIC_GUESS 1
#define CV_CALIB_FIX_ASPECT_RATIO 2
#define CV_CALIB_FIX_PRINCIPAL_POINT 4
#define CV_CALIB_ZERO_TANGENT_DIST 8
#define CV_CALIB_FIX_FOCAL_LENGTH 16
#define CV_CALIB_FIX_K1 32
#define CV_CALIB_FIX_K2 64
#define CV_CALIB_FIX_K3 128
#define CV_CALIB_FIX_K4 2048
#define CV_CALIB_FIX_K5 4096
#define CV_CALIB_FIX_K6 8192
#define CV_CALIB_RATIONAL_MODEL 16384
/* Finds intrinsic and extrinsic camera parameters
from a few views of known calibration pattern */
CVAPI(double) cvCalibrateCamera2( const CvMat* object_points,
const CvMat* image_points,
const CvMat* point_counts,
CvSize image_size,
CvMat* camera_matrix,
CvMat* distortion_coeffs,
CvMat* rotation_vectors CV_DEFAULT(NULL),
CvMat* translation_vectors CV_DEFAULT(NULL),
int flags CV_DEFAULT(0),
CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria(
CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,DBL_EPSILON)) );
/* Computes various useful characteristics of the camera from the data computed by
cvCalibrateCamera2 */
CVAPI(void) cvCalibrationMatrixValues( const CvMat *camera_matrix,
CvSize image_size,
double aperture_width CV_DEFAULT(0),
double aperture_height CV_DEFAULT(0),
double *fovx CV_DEFAULT(NULL),
double *fovy CV_DEFAULT(NULL),
double *focal_length CV_DEFAULT(NULL),
CvPoint2D64f *principal_point CV_DEFAULT(NULL),
double *pixel_aspect_ratio CV_DEFAULT(NULL));
#define CV_CALIB_FIX_INTRINSIC 256
#define CV_CALIB_SAME_FOCAL_LENGTH 512
/* Computes the transformation from one camera coordinate system to another one
from a few correspondent views of the same calibration target. Optionally, calibrates
both cameras */
CVAPI(double) cvStereoCalibrate( const CvMat* object_points, const CvMat* image_points1,
const CvMat* image_points2, const CvMat* npoints,
CvMat* camera_matrix1, CvMat* dist_coeffs1,
CvMat* camera_matrix2, CvMat* dist_coeffs2,
CvSize image_size, CvMat* R, CvMat* T,
CvMat* E CV_DEFAULT(0), CvMat* F CV_DEFAULT(0),
CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria(
CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,1e-6)),
int flags CV_DEFAULT(CV_CALIB_FIX_INTRINSIC));
#define CV_CALIB_ZERO_DISPARITY 1024
/* Computes 3D rotations (+ optional shift) for each camera coordinate system to make both
views parallel (=> to make all the epipolar lines horizontal or vertical) */
CVAPI(void) cvStereoRectify( const CvMat* camera_matrix1, const CvMat* camera_matrix2,
const CvMat* dist_coeffs1, const CvMat* dist_coeffs2,
CvSize image_size, const CvMat* R, const CvMat* T,
CvMat* R1, CvMat* R2, CvMat* P1, CvMat* P2,
CvMat* Q CV_DEFAULT(0),
int flags CV_DEFAULT(CV_CALIB_ZERO_DISPARITY),
double alpha CV_DEFAULT(-1),
CvSize new_image_size CV_DEFAULT(cvSize(0,0)),
CvRect* valid_pix_ROI1 CV_DEFAULT(0),
CvRect* valid_pix_ROI2 CV_DEFAULT(0));
/* Computes rectification transformations for uncalibrated pair of images using a set
of point correspondences */
CVAPI(int) cvStereoRectifyUncalibrated( const CvMat* points1, const CvMat* points2,
const CvMat* F, CvSize img_size,
CvMat* H1, CvMat* H2,
double threshold CV_DEFAULT(5));
/* stereo correspondence parameters and functions */
#define CV_STEREO_BM_NORMALIZED_RESPONSE 0
#define CV_STEREO_BM_XSOBEL 1
/* Block matching algorithm structure */
typedef struct CvStereoBMState
{
// pre-filtering (normalization of input images)
int preFilterType; // =CV_STEREO_BM_NORMALIZED_RESPONSE now
int preFilterSize; // averaging window size: ~5x5..21x21
int preFilterCap; // the output of pre-filtering is clipped by [-preFilterCap,preFilterCap]
// correspondence using Sum of Absolute Difference (SAD)
int SADWindowSize; // ~5x5..21x21
int minDisparity; // minimum disparity (can be negative)
int numberOfDisparities; // maximum disparity - minimum disparity (> 0)
// post-filtering
int textureThreshold; // the disparity is only computed for pixels
// with textured enough neighborhood
int uniquenessRatio; // accept the computed disparity d* only if
// SAD(d) >= SAD(d*)*(1 + uniquenessRatio/100.)
// for any d != d*+/-1 within the search range.
int speckleWindowSize; // disparity variation window
int speckleRange; // acceptable range of variation in window
int trySmallerWindows; // if 1, the results may be more accurate,
// at the expense of slower processing
CvRect roi1, roi2;
int disp12MaxDiff;
// temporary buffers
CvMat* preFilteredImg0;
CvMat* preFilteredImg1;
CvMat* slidingSumBuf;
CvMat* cost;
CvMat* disp;
} CvStereoBMState;
#define CV_STEREO_BM_BASIC 0
#define CV_STEREO_BM_FISH_EYE 1
#define CV_STEREO_BM_NARROW 2
CVAPI(CvStereoBMState*) cvCreateStereoBMState(int preset CV_DEFAULT(CV_STEREO_BM_BASIC),
int numberOfDisparities CV_DEFAULT(0));
CVAPI(void) cvReleaseStereoBMState( CvStereoBMState** state );
CVAPI(void) cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right,
CvArr* disparity, CvStereoBMState* state );
CVAPI(CvRect) cvGetValidDisparityROI( CvRect roi1, CvRect roi2, int minDisparity,
int numberOfDisparities, int SADWindowSize );
CVAPI(void) cvValidateDisparity( CvArr* disparity, const CvArr* cost,
int minDisparity, int numberOfDisparities,
int disp12MaxDiff CV_DEFAULT(1) );
/* Reprojects the computed disparity image to the 3D space using the specified 4x4 matrix */
CVAPI(void) cvReprojectImageTo3D( const CvArr* disparityImage,
CvArr* _3dImage, const CvMat* Q,
int handleMissingValues CV_DEFAULT(0) );
#ifdef __cplusplus
}
//////////////////////////////////////////////////////////////////////////////////////////
class CV_EXPORTS CvLevMarq
{
public:
CvLevMarq();
CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria=
cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
bool completeSymmFlag=false );
~CvLevMarq();
void init( int nparams, int nerrs, CvTermCriteria criteria=
cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
bool completeSymmFlag=false );
bool update( const CvMat*& param, CvMat*& J, CvMat*& err );
bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm );
void clear();
void step();
enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 };
cv::Ptr<CvMat> mask;
cv::Ptr<CvMat> prevParam;
cv::Ptr<CvMat> param;
cv::Ptr<CvMat> J;
cv::Ptr<CvMat> err;
cv::Ptr<CvMat> JtJ;
cv::Ptr<CvMat> JtJN;
cv::Ptr<CvMat> JtErr;
cv::Ptr<CvMat> JtJV;
cv::Ptr<CvMat> JtJW;
double prevErrNorm, errNorm;
int lambdaLg10;
CvTermCriteria criteria;
int state;
int iters;
bool completeSymmFlag;
};
namespace cv
{
//! converts rotation vector to rotation matrix or vice versa using Rodrigues transformation
CV_EXPORTS_W void Rodrigues(InputArray src, OutputArray dst, OutputArray jacobian=noArray());
//! type of the robust estimation algorithm
enum
{
LMEDS=CV_LMEDS, //!< least-median algorithm
RANSAC=CV_RANSAC //!< RANSAC algorithm
};
//! computes the best-fit perspective transformation mapping srcPoints to dstPoints.
CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints,
int method=0, double ransacReprojThreshold=3,
OutputArray mask=noArray());
//! variant of findHomography for backward compatibility
CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints,
OutputArray mask, int method=0, double ransacReprojThreshold=3);
//! Computes RQ decomposition of 3x3 matrix
CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ,
OutputArray Qx=noArray(),
OutputArray Qy=noArray(),
OutputArray Qz=noArray());
//! Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector
CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix,
OutputArray rotMatrix, OutputArray transVect,
OutputArray rotMatrixX=noArray(),
OutputArray rotMatrixY=noArray(),
OutputArray rotMatrixZ=noArray(),
OutputArray eulerAngles=noArray() );
//! computes derivatives of the matrix product w.r.t each of the multiplied matrix coefficients
CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B,
OutputArray dABdA,
OutputArray dABdB );
//! composes 2 [R|t] transformations together. Also computes the derivatives of the result w.r.t the arguments
CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1,
InputArray rvec2, InputArray tvec2,
OutputArray rvec3, OutputArray tvec3,
OutputArray dr3dr1=noArray(), OutputArray dr3dt1=noArray(),
OutputArray dr3dr2=noArray(), OutputArray dr3dt2=noArray(),
OutputArray dt3dr1=noArray(), OutputArray dt3dt1=noArray(),
OutputArray dt3dr2=noArray(), OutputArray dt3dt2=noArray() );
//! projects points from the model coordinate space to the image coordinates. Also computes derivatives of the image coordinates w.r.t the intrinsic and extrinsic camera parameters
CV_EXPORTS_W void projectPoints( InputArray objectPoints,
InputArray rvec, InputArray tvec,
InputArray cameraMatrix, InputArray distCoeffs,
OutputArray imagePoints,
OutputArray jacobian=noArray(),
double aspectRatio=0 );
//! computes the camera pose from a few 3D points and the corresponding projections. The outliers are not handled.
enum
{
ITERATIVE=CV_ITERATIVE,
EPNP=CV_EPNP,
P3P=CV_P3P
};
CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
InputArray cameraMatrix, InputArray distCoeffs,
OutputArray rvec, OutputArray tvec,
bool useExtrinsicGuess=false, int flags=ITERATIVE);
//! computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible.
CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints,
InputArray imagePoints,
InputArray cameraMatrix,
InputArray distCoeffs,
OutputArray rvec,
OutputArray tvec,
bool useExtrinsicGuess = false,
int iterationsCount = 100,
float reprojectionError = 8.0,
int minInliersCount = 100,
OutputArray inliers = noArray(),
int flags = ITERATIVE);
//! initializes camera matrix from a few 3D points and the corresponding projections.
CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints,
InputArrayOfArrays imagePoints,
Size imageSize, double aspectRatio=1. );
enum { CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2,
CALIB_CB_FILTER_QUADS = 4, CALIB_CB_FAST_CHECK = 8 };
//! finds checkerboard pattern of the specified size in the image
CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize,
OutputArray corners,
int flags=CALIB_CB_ADAPTIVE_THRESH+CALIB_CB_NORMALIZE_IMAGE );
//! finds subpixel-accurate positions of the chessboard corners
CV_EXPORTS bool find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size region_size);
//! draws the checkerboard pattern (found or partly found) in the image
CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize,
InputArray corners, bool patternWasFound );
enum { CALIB_CB_SYMMETRIC_GRID = 1, CALIB_CB_ASYMMETRIC_GRID = 2,
CALIB_CB_CLUSTERING = 4 };
//! finds circles' grid pattern of the specified size in the image
CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID,
const Ptr<FeatureDetector> &blobDetector = new SimpleBlobDetector());
//! the deprecated function. Use findCirclesGrid() instead of it.
CV_EXPORTS_W bool findCirclesGridDefault( InputArray image, Size patternSize,
OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID );
enum
{
CALIB_USE_INTRINSIC_GUESS = CV_CALIB_USE_INTRINSIC_GUESS,
CALIB_FIX_ASPECT_RATIO = CV_CALIB_FIX_ASPECT_RATIO,
CALIB_FIX_PRINCIPAL_POINT = CV_CALIB_FIX_PRINCIPAL_POINT,
CALIB_ZERO_TANGENT_DIST = CV_CALIB_ZERO_TANGENT_DIST,
CALIB_FIX_FOCAL_LENGTH = CV_CALIB_FIX_FOCAL_LENGTH,
CALIB_FIX_K1 = CV_CALIB_FIX_K1,
CALIB_FIX_K2 = CV_CALIB_FIX_K2,
CALIB_FIX_K3 = CV_CALIB_FIX_K3,
CALIB_FIX_K4 = CV_CALIB_FIX_K4,
CALIB_FIX_K5 = CV_CALIB_FIX_K5,
CALIB_FIX_K6 = CV_CALIB_FIX_K6,
CALIB_RATIONAL_MODEL = CV_CALIB_RATIONAL_MODEL,
// only for stereo
CALIB_FIX_INTRINSIC = CV_CALIB_FIX_INTRINSIC,
CALIB_SAME_FOCAL_LENGTH = CV_CALIB_SAME_FOCAL_LENGTH,
// for stereo rectification
CALIB_ZERO_DISPARITY = CV_CALIB_ZERO_DISPARITY
};
//! finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern.
CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints,
InputArrayOfArrays imagePoints,
Size imageSize,
CV_OUT InputOutputArray cameraMatrix,
CV_OUT InputOutputArray distCoeffs,
OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
int flags=0, TermCriteria criteria = TermCriteria(
TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON) );
//! computes several useful camera characteristics from the camera matrix, camera frame resolution and the physical sensor size.
CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix,
Size imageSize,
double apertureWidth,
double apertureHeight,
CV_OUT double& fovx,
CV_OUT double& fovy,
CV_OUT double& focalLength,
CV_OUT Point2d& principalPoint,
CV_OUT double& aspectRatio );
//! finds intrinsic and extrinsic parameters of a stereo camera
CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints,
InputArrayOfArrays imagePoints1,
InputArrayOfArrays imagePoints2,
CV_OUT InputOutputArray cameraMatrix1,
CV_OUT InputOutputArray distCoeffs1,
CV_OUT InputOutputArray cameraMatrix2,
CV_OUT InputOutputArray distCoeffs2,
Size imageSize, OutputArray R,
OutputArray T, OutputArray E, OutputArray F,
TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6),
int flags=CALIB_FIX_INTRINSIC );
//! computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters
CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1,
InputArray cameraMatrix2, InputArray distCoeffs2,
Size imageSize, InputArray R, InputArray T,
OutputArray R1, OutputArray R2,
OutputArray P1, OutputArray P2,
OutputArray Q, int flags=CALIB_ZERO_DISPARITY,
double alpha=-1, Size newImageSize=Size(),
CV_OUT Rect* validPixROI1=0, CV_OUT Rect* validPixROI2=0 );
//! computes the rectification transformation for an uncalibrated stereo camera (zero distortion is assumed)
CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2,
InputArray F, Size imgSize,
OutputArray H1, OutputArray H2,
double threshold=5 );
//! computes the rectification transformations for 3-head camera, where all the heads are on the same line.
CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1,
InputArray cameraMatrix2, InputArray distCoeffs2,
InputArray cameraMatrix3, InputArray distCoeffs3,
InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3,
Size imageSize, InputArray R12, InputArray T12,
InputArray R13, InputArray T13,
OutputArray R1, OutputArray R2, OutputArray R3,
OutputArray P1, OutputArray P2, OutputArray P3,
OutputArray Q, double alpha, Size newImgSize,
CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags );
//! returns the optimal new camera matrix
CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs,
Size imageSize, double alpha, Size newImgSize=Size(),
CV_OUT Rect* validPixROI=0, bool centerPrincipalPoint=false);
//! converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1))
CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst );
//! converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z))
CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst );
//! for backward compatibility
CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst );
//! the algorithm for finding fundamental matrix
enum
{
FM_7POINT = CV_FM_7POINT, //!< 7-point algorithm
FM_8POINT = CV_FM_8POINT, //!< 8-point algorithm
FM_LMEDS = CV_FM_LMEDS, //!< least-median algorithm
FM_RANSAC = CV_FM_RANSAC //!< RANSAC algorithm
};
//! finds fundamental matrix from a set of corresponding 2D points
CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
int method=FM_RANSAC,
double param1=3., double param2=0.99,
OutputArray mask=noArray());
//! variant of findFundamentalMat for backward compatibility
CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2,
OutputArray mask, int method=FM_RANSAC,
double param1=3., double param2=0.99);
//! finds coordinates of epipolar lines corresponding the specified points
CV_EXPORTS_W void computeCorrespondEpilines( InputArray points,
int whichImage, InputArray F,
OutputArray lines );
CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2,
InputArray projPoints1, InputArray projPoints2,
OutputArray points4D );
CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2,
OutputArray newPoints1, OutputArray newPoints2 );
template<> CV_EXPORTS void Ptr<CvStereoBMState>::delete_obj();
/*!
Block Matching Stereo Correspondence Algorithm
The class implements BM stereo correspondence algorithm by K. Konolige.
*/
class CV_EXPORTS_W StereoBM
{
public:
enum { PREFILTER_NORMALIZED_RESPONSE = 0, PREFILTER_XSOBEL = 1,
BASIC_PRESET=0, FISH_EYE_PRESET=1, NARROW_PRESET=2 };
//! the default constructor
CV_WRAP StereoBM();
//! the full constructor taking the camera-specific preset, number of disparities and the SAD window size
CV_WRAP StereoBM(int preset, int ndisparities=0, int SADWindowSize=21);
//! the method that reinitializes the state. The previous content is destroyed
void init(int preset, int ndisparities=0, int SADWindowSize=21);
//! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair
CV_WRAP_AS(compute) void operator()( InputArray left, InputArray right,
OutputArray disparity, int disptype=CV_16S );
//! pointer to the underlying CvStereoBMState
Ptr<CvStereoBMState> state;
};
/*!
Semi-Global Block Matching Stereo Correspondence Algorithm
The class implements the original SGBM stereo correspondence algorithm by H. Hirschmuller and some its modification.
*/
class CV_EXPORTS_W StereoSGBM
{
public:
enum { DISP_SHIFT=4, DISP_SCALE = (1<<DISP_SHIFT) };
//! the default constructor
CV_WRAP StereoSGBM();
//! the full constructor taking all the necessary algorithm parameters
CV_WRAP StereoSGBM(int minDisparity, int numDisparities, int SADWindowSize,
int P1=0, int P2=0, int disp12MaxDiff=0,
int preFilterCap=0, int uniquenessRatio=0,
int speckleWindowSize=0, int speckleRange=0,
bool fullDP=false);
//! the destructor
virtual ~StereoSGBM();
//! the stereo correspondence operator that computes disparity map for the specified rectified stereo pair
CV_WRAP_AS(compute) virtual void operator()(InputArray left, InputArray right,
OutputArray disp);
CV_PROP_RW int minDisparity;
CV_PROP_RW int numberOfDisparities;
CV_PROP_RW int SADWindowSize;
CV_PROP_RW int preFilterCap;
CV_PROP_RW int uniquenessRatio;
CV_PROP_RW int P1;
CV_PROP_RW int P2;
CV_PROP_RW int speckleWindowSize;
CV_PROP_RW int speckleRange;
CV_PROP_RW int disp12MaxDiff;
CV_PROP_RW bool fullDP;
protected:
Mat buffer;
};
//! filters off speckles (small regions of incorrectly computed disparity)
CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff,
InputOutputArray buf=noArray() );
//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by cv::stereoRectify())
CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2,
int minDisparity, int numberOfDisparities,
int SADWindowSize );
//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm
CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost,
int minDisparity, int numberOfDisparities,
int disp12MaxDisp=1 );
//! reprojects disparity image to 3D: (x,y,d)->(X,Y,Z) using the matrix Q returned by cv::stereoRectify
CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity,
OutputArray _3dImage, InputArray Q,
bool handleMissingValues=false,
int ddepth=-1 );
CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst,
OutputArray out, OutputArray inliers,
double ransacThreshold=3, double confidence=0.99);
namespace fisheye
{
enum{
CALIB_USE_INTRINSIC_GUESS = 1,
CALIB_RECOMPUTE_EXTRINSIC = 2,
CALIB_CHECK_COND = 4,
CALIB_FIX_SKEW = 8,
CALIB_FIX_K1 = 16,
CALIB_FIX_K2 = 32,
CALIB_FIX_K3 = 64,
CALIB_FIX_K4 = 128,
CALIB_FIX_INTRINSIC = 256
};
//! projects 3D points using fisheye model
CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine,
InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
//! projects points using fisheye model
CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec,
InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
//! distorts 2D points using fisheye model
CV_EXPORTS void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0);
//! undistorts 2D points using fisheye model
CV_EXPORTS void undistortPoints(InputArray distorted, OutputArray undistorted,
InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray());
//! computing undistortion and rectification maps for image transform by cv::remap()
//! If D is empty zero distortion is used, if R or P is empty identity matrixes are used
CV_EXPORTS void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P,
const cv::Size& size, int m1type, OutputArray map1, OutputArray map2);
//! undistorts image, optionally changes resolution and camera matrix. If Knew zero identity matrix is used
CV_EXPORTS void undistortImage(InputArray distorted, OutputArray undistorted,
InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size());
//! estimates new camera matrix for undistortion or rectification
CV_EXPORTS void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R,
OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0);
//! performs camera calibaration
CV_EXPORTS double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size,
InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0,
TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
//! stereo rectification estimation
CV_EXPORTS void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec,
OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(),
double balance = 0.0, double fov_scale = 1.0);
//! performs stereo calibaration
CV_EXPORTS double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize,
OutputArray R, OutputArray T, int flags = CALIB_FIX_INTRINSIC,
TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
}
}
#endif
#endif

View File

@ -41,87 +41,15 @@
//
//M*/
#ifndef OPENCV_CORE_AFFINE3_HPP
#define OPENCV_CORE_AFFINE3_HPP
#ifndef __OPENCV_CORE_AFFINE3_HPP__
#define __OPENCV_CORE_AFFINE3_HPP__
#ifdef __cplusplus
#include <opencv2/core.hpp>
#include <opencv2/core/core.hpp>
namespace cv
{
//! @addtogroup core
//! @{
/** @brief Affine transform
*
* It represents a 4x4 homogeneous transformation matrix \f$T\f$
*
* \f[T =
* \begin{bmatrix}
* R & t\\
* 0 & 1\\
* \end{bmatrix}
* \f]
*
* where \f$R\f$ is a 3x3 rotation matrix and \f$t\f$ is a 3x1 translation vector.
*
* You can specify \f$R\f$ either by a 3x3 rotation matrix or by a 3x1 rotation vector,
* which is converted to a 3x3 rotation matrix by the Rodrigues formula.
*
* To construct a matrix \f$T\f$ representing first rotation around the axis \f$r\f$ with rotation
* angle \f$|r|\f$ in radian (right hand rule) and then translation by the vector \f$t\f$, you can use
*
* @code
* cv::Vec3f r, t;
* cv::Affine3f T(r, t);
* @endcode
*
* If you already have the rotation matrix \f$R\f$, then you can use
*
* @code
* cv::Matx33f R;
* cv::Affine3f T(R, t);
* @endcode
*
* To extract the rotation matrix \f$R\f$ from \f$T\f$, use
*
* @code
* cv::Matx33f R = T.rotation();
* @endcode
*
* To extract the translation vector \f$t\f$ from \f$T\f$, use
*
* @code
* cv::Vec3f t = T.translation();
* @endcode
*
* To extract the rotation vector \f$r\f$ from \f$T\f$, use
*
* @code
* cv::Vec3f r = T.rvec();
* @endcode
*
* Note that since the mapping from rotation vectors to rotation matrices
* is many to one. The returned rotation vector is not necessarily the one
* you used before to set the matrix.
*
* If you have two transformations \f$T = T_1 * T_2\f$, use
*
* @code
* cv::Affine3f T, T1, T2;
* T = T2.concatenate(T1);
* @endcode
*
* To get the inverse transform of \f$T\f$, use
*
* @code
* cv::Affine3f T, T_inv;
* T_inv = T.inv();
* @endcode
*
*/
template<typename T>
class Affine3
{
@ -131,139 +59,56 @@ namespace cv
typedef Matx<float_type, 4, 4> Mat4;
typedef Vec<float_type, 3> Vec3;
//! Default constructor. It represents a 4x4 identity matrix.
Affine3();
//! Augmented affine matrix
//Augmented affine matrix
Affine3(const Mat4& affine);
/**
* The resulting 4x4 matrix is
*
* \f[
* \begin{bmatrix}
* R & t\\
* 0 & 1\\
* \end{bmatrix}
* \f]
*
* @param R 3x3 rotation matrix.
* @param t 3x1 translation vector.
*/
//Rotation matrix
Affine3(const Mat3& R, const Vec3& t = Vec3::all(0));
/**
* Rodrigues vector.
*
* The last row of the current matrix is set to [0,0,0,1].
*
* @param rvec 3x1 rotation vector. Its direction indicates the rotation axis and its length
* indicates the rotation angle in radian (using right hand rule).
* @param t 3x1 translation vector.
*/
//Rodrigues vector
Affine3(const Vec3& rvec, const Vec3& t = Vec3::all(0));
/**
* Combines all constructors above. Supports 4x4, 3x4, 3x3, 1x3, 3x1 sizes of data matrix.
*
* The last row of the current matrix is set to [0,0,0,1] when data is not 4x4.
*
* @param data 1-channel matrix.
* when it is 4x4, it is copied to the current matrix and t is not used.
* When it is 3x4, it is copied to the upper part 3x4 of the current matrix and t is not used.
* When it is 3x3, it is copied to the upper left 3x3 part of the current matrix.
* When it is 3x1 or 1x3, it is treated as a rotation vector and the Rodrigues formula is used
* to compute a 3x3 rotation matrix.
* @param t 3x1 translation vector. It is used only when data is neither 4x4 nor 3x4.
*/
//Combines all contructors above. Supports 4x4, 4x3, 3x3, 1x3, 3x1 sizes of data matrix
explicit Affine3(const Mat& data, const Vec3& t = Vec3::all(0));
//! From 16-element array
//From 16th element array
explicit Affine3(const float_type* vals);
//! Create an 4x4 identity transform
static Affine3 Identity();
/**
* Rotation matrix.
*
* Copy the rotation matrix to the upper left 3x3 part of the current matrix.
* The remaining elements of the current matrix are not changed.
*
* @param R 3x3 rotation matrix.
*
*/
//Rotation matrix
void rotation(const Mat3& R);
/**
* Rodrigues vector.
*
* It sets the upper left 3x3 part of the matrix. The remaining part is unaffected.
*
* @param rvec 3x1 rotation vector. The direction indicates the rotation axis and
* its length indicates the rotation angle in radian (using the right thumb convention).
*/
//Rodrigues vector
void rotation(const Vec3& rvec);
/**
* Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix.
*
* It sets the upper left 3x3 part of the matrix. The remaining part is unaffected.
*
* @param data 1-channel matrix.
* When it is a 3x3 matrix, it sets the upper left 3x3 part of the current matrix.
* When it is a 1x3 or 3x1 matrix, it is used as a rotation vector. The Rodrigues formula
* is used to compute the rotation matrix and sets the upper left 3x3 part of the current matrix.
*/
//Combines rotation methods above. Suports 3x3, 1x3, 3x1 sizes of data matrix;
void rotation(const Mat& data);
/**
* Copy the 3x3 matrix L to the upper left part of the current matrix
*
* It sets the upper left 3x3 part of the matrix. The remaining part is unaffected.
*
* @param L 3x3 matrix.
*/
void linear(const Mat3& L);
/**
* Copy t to the first three elements of the last column of the current matrix
*
* It sets the upper right 3x1 part of the matrix. The remaining part is unaffected.
*
* @param t 3x1 translation vector.
*/
void translation(const Vec3& t);
//! @return the upper left 3x3 part
Mat3 rotation() const;
//! @return the upper left 3x3 part
Mat3 linear() const;
//! @return the upper right 3x1 part
Vec3 translation() const;
//! Rodrigues vector.
//! @return a vector representing the upper left 3x3 rotation matrix of the current matrix.
//! @warning Since the mapping between rotation vectors and rotation matrices is many to one,
//! this function returns only one rotation vector that represents the current rotation matrix,
//! which is not necessarily the same one set by `rotation(const Vec3& rvec)`.
//Rodrigues vector
Vec3 rvec() const;
//! @return the inverse of the current matrix.
Affine3 inv(int method = cv::DECOMP_SVD) const;
//! a.rotate(R) is equivalent to Affine(R, 0) * a;
// a.rotate(R) is equivalent to Affine(R, 0) * a;
Affine3 rotate(const Mat3& R) const;
//! a.rotate(rvec) is equivalent to Affine(rvec, 0) * a;
// a.rotate(R) is equivalent to Affine(rvec, 0) * a;
Affine3 rotate(const Vec3& rvec) const;
//! a.translate(t) is equivalent to Affine(E, t) * a, where E is an identity matrix
// a.translate(t) is equivalent to Affine(E, t) * a;
Affine3 translate(const Vec3& t) const;
//! a.concatenate(affine) is equivalent to affine * a;
// a.concatenate(affine) is equivalent to affine * a;
Affine3 concatenate(const Affine3& affine) const;
template <typename Y> operator Affine3<Y>() const;
@ -283,7 +128,6 @@ namespace cv
template<typename T> static
Affine3<T> operator*(const Affine3<T>& affine1, const Affine3<T>& affine2);
//! V is a 3-element vector with member fields x, y and z
template<typename T, typename V> static
V operator*(const Affine3<T>& affine, const V& vector);
@ -301,32 +145,19 @@ namespace cv
typedef _Tp channel_type;
enum { generic_type = 0,
depth = DataType<channel_type>::depth,
channels = 16,
fmt = traits::SafeFmt<channel_type>::fmt + ((channels - 1) << 8)
#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED
,depth = DataType<channel_type>::depth
,type = CV_MAKETYPE(depth, channels)
#endif
fmt = DataType<channel_type>::fmt + ((channels - 1) << 8),
type = CV_MAKETYPE(depth, channels)
};
typedef Vec<channel_type, channels> vec_type;
};
namespace traits {
template<typename _Tp>
struct Depth< Affine3<_Tp> > { enum { value = Depth<_Tp>::value }; };
template<typename _Tp>
struct Type< Affine3<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 16) }; };
} // namespace
//! @} core
}
//! @cond IGNORED
///////////////////////////////////////////////////////////////////////////////////
// Implementation
/// Implementaiton
template<typename T> inline
cv::Affine3<T>::Affine3()
@ -359,8 +190,7 @@ cv::Affine3<T>::Affine3(const Vec3& _rvec, const Vec3& t)
template<typename T> inline
cv::Affine3<T>::Affine3(const cv::Mat& data, const Vec3& t)
{
CV_Assert(data.type() == cv::traits::Type<T>::value);
CV_Assert(data.channels() == 1);
CV_Assert(data.type() == cv::DataType<T>::type);
if (data.cols == 4 && data.rows == 4)
{
@ -371,13 +201,11 @@ cv::Affine3<T>::Affine3(const cv::Mat& data, const Vec3& t)
{
rotation(data(Rect(0, 0, 3, 3)));
translation(data(Rect(3, 0, 1, 3)));
}
else
{
rotation(data);
translation(t);
return;
}
rotation(data);
translation(t);
matrix.val[12] = matrix.val[13] = matrix.val[14] = 0;
matrix.val[15] = 1;
}
@ -401,36 +229,40 @@ void cv::Affine3<T>::rotation(const Mat3& R)
template<typename T> inline
void cv::Affine3<T>::rotation(const Vec3& _rvec)
{
double theta = norm(_rvec);
double rx = _rvec[0], ry = _rvec[1], rz = _rvec[2];
double theta = std::sqrt(rx*rx + ry*ry + rz*rz);
if (theta < DBL_EPSILON)
rotation(Mat3::eye());
else
{
const double I[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
double c = std::cos(theta);
double s = std::sin(theta);
double c1 = 1. - c;
double itheta = (theta != 0) ? 1./theta : 0.;
double itheta = theta ? 1./theta : 0.;
Point3_<T> r = _rvec*itheta;
rx *= itheta; ry *= itheta; rz *= itheta;
Mat3 rrt( r.x*r.x, r.x*r.y, r.x*r.z, r.x*r.y, r.y*r.y, r.y*r.z, r.x*r.z, r.y*r.z, r.z*r.z );
Mat3 r_x( 0, -r.z, r.y, r.z, 0, -r.x, -r.y, r.x, 0 );
double rrt[] = { rx*rx, rx*ry, rx*rz, rx*ry, ry*ry, ry*rz, rx*rz, ry*rz, rz*rz };
double _r_x_[] = { 0, -rz, ry, rz, 0, -rx, -ry, rx, 0 };
Mat3 R;
// R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x]
// where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0]
Mat3 R = c*Mat3::eye() + c1*rrt + s*r_x;
for(int k = 0; k < 9; ++k)
R.val[k] = static_cast<float_type>(c*I[k] + c1*rrt[k] + s*_r_x_[k]);
rotation(R);
}
}
//Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix;
//Combines rotation methods above. Suports 3x3, 1x3, 3x1 sizes of data matrix;
template<typename T> inline
void cv::Affine3<T>::rotation(const cv::Mat& data)
{
CV_Assert(data.type() == cv::traits::Type<T>::value);
CV_Assert(data.channels() == 1);
CV_Assert(data.type() == cv::DataType<T>::type);
if (data.cols == 3 && data.rows == 3)
{
@ -445,7 +277,7 @@ void cv::Affine3<T>::rotation(const cv::Mat& data)
rotation(_rvec);
}
else
CV_Error(Error::StsError, "Input matrix can only be 3x3, 1x3 or 3x1");
CV_Assert(!"Input marix can be 3x3, 1x3 or 3x1");
}
template<typename T> inline
@ -644,21 +476,21 @@ cv::Vec3d cv::operator*(const cv::Affine3d& affine, const cv::Vec3d& v)
template<typename T> inline
cv::Affine3<T>::Affine3(const Eigen::Transform<T, 3, Eigen::Affine, (Eigen::RowMajor)>& affine)
{
cv::Mat(4, 4, cv::traits::Type<T>::value, affine.matrix().data()).copyTo(matrix);
cv::Mat(4, 4, cv::DataType<T>::type, affine.matrix().data()).copyTo(matrix);
}
template<typename T> inline
cv::Affine3<T>::Affine3(const Eigen::Transform<T, 3, Eigen::Affine>& affine)
{
Eigen::Transform<T, 3, Eigen::Affine, (Eigen::RowMajor)> a = affine;
cv::Mat(4, 4, cv::traits::Type<T>::value, a.matrix().data()).copyTo(matrix);
cv::Mat(4, 4, cv::DataType<T>::type, a.matrix().data()).copyTo(matrix);
}
template<typename T> inline
cv::Affine3<T>::operator Eigen::Transform<T, 3, Eigen::Affine, (Eigen::RowMajor)>() const
{
Eigen::Transform<T, 3, Eigen::Affine, (Eigen::RowMajor)> r;
cv::Mat hdr(4, 4, cv::traits::Type<T>::value, r.matrix().data());
cv::Mat hdr(4, 4, cv::DataType<T>::type, r.matrix().data());
cv::Mat(matrix, false).copyTo(hdr);
return r;
}
@ -671,8 +503,7 @@ cv::Affine3<T>::operator Eigen::Transform<T, 3, Eigen::Affine>() const
#endif /* defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H */
//! @endcond
#endif /* __cplusplus */
#endif /* OPENCV_CORE_AFFINE3_HPP */
#endif /* __OPENCV_CORE_AFFINE3_HPP__ */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -12,7 +12,6 @@
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
@ -41,11 +40,13 @@
//
//M*/
#ifndef __OPENCV_CORE_EIGEN_HPP__
#define __OPENCV_CORE_EIGEN_HPP__
#ifndef OPENCV_CORE_EIGEN_HPP
#define OPENCV_CORE_EIGEN_HPP
#ifdef __cplusplus
#include "opencv2/core.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/core/core.hpp"
#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( disable: 4714 ) //__forceinline is not inlined
@ -56,50 +57,32 @@
namespace cv
{
//! @addtogroup core_eigen
//! @{
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline
void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst )
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Mat& dst )
{
if( !(src.Flags & Eigen::RowMajorBit) )
{
Mat _src(src.cols(), src.rows(), traits::Type<_Tp>::value,
(void*)src.data(), src.outerStride()*sizeof(_Tp));
Mat _src(src.cols(), src.rows(), DataType<_Tp>::type,
(void*)src.data(), src.stride()*sizeof(_Tp));
transpose(_src, dst);
}
else
{
Mat _src(src.rows(), src.cols(), traits::Type<_Tp>::value,
(void*)src.data(), src.outerStride()*sizeof(_Tp));
Mat _src(src.rows(), src.cols(), DataType<_Tp>::type,
(void*)src.data(), src.stride()*sizeof(_Tp));
_src.copyTo(dst);
}
}
// Matx case
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline
void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src,
Matx<_Tp, _rows, _cols>& dst )
{
if( !(src.Flags & Eigen::RowMajorBit) )
{
dst = Matx<_Tp, _cols, _rows>(static_cast<const _Tp*>(src.data())).t();
}
else
{
dst = Matx<_Tp, _rows, _cols>(static_cast<const _Tp*>(src.data()));
}
}
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void cv2eigen( const Mat& src,
Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst )
{
CV_DbgAssert(src.rows == _rows && src.cols == _cols);
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
if( src.type() == _dst.type() )
transpose(src, _dst);
else if( src.cols == src.rows )
@ -109,43 +92,47 @@ void cv2eigen( const Mat& src,
}
else
Mat(src.t()).convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
src.convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
// Matx case
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void cv2eigen( const Matx<_Tp, _rows, _cols>& src,
Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst )
{
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(_cols, _rows, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(_cols, _rows, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
transpose(src, _dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(_rows, _cols, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(_rows, _cols, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
Mat(src).copyTo(_dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
template<typename _Tp> static inline
template<typename _Tp>
void cv2eigen( const Mat& src,
Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst )
{
dst.resize(src.rows, src.cols);
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
if( src.type() == _dst.type() )
transpose(src, _dst);
else if( src.cols == src.rows )
@ -155,36 +142,40 @@ void cv2eigen( const Mat& src,
}
else
Mat(src.t()).convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
src.convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
// Matx case
template<typename _Tp, int _rows, int _cols> static inline
template<typename _Tp, int _rows, int _cols>
void cv2eigen( const Matx<_Tp, _rows, _cols>& src,
Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst )
{
dst.resize(_rows, _cols);
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(_cols, _rows, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(_cols, _rows, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
transpose(src, _dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(_rows, _cols, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(_rows, _cols, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
Mat(src).copyTo(_dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
template<typename _Tp> static inline
template<typename _Tp>
void cv2eigen( const Mat& src,
Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst )
{
@ -193,23 +184,25 @@ void cv2eigen( const Mat& src,
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
if( src.type() == _dst.type() )
transpose(src, _dst);
else
Mat(src.t()).convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
src.convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
// Matx case
template<typename _Tp, int _rows> static inline
template<typename _Tp, int _rows>
void cv2eigen( const Matx<_Tp, _rows, 1>& src,
Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst )
{
@ -217,20 +210,22 @@ void cv2eigen( const Matx<_Tp, _rows, 1>& src,
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(1, _rows, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(1, _rows, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
transpose(src, _dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(_rows, 1, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(_rows, 1, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
src.copyTo(_dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
template<typename _Tp> static inline
template<typename _Tp>
void cv2eigen( const Mat& src,
Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst )
{
@ -238,43 +233,48 @@ void cv2eigen( const Mat& src,
dst.resize(src.cols);
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.cols, src.rows, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
if( src.type() == _dst.type() )
transpose(src, _dst);
else
Mat(src.t()).convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(src.rows, src.cols, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
src.convertTo(_dst, _dst.type());
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
//Matx
template<typename _Tp, int _cols> static inline
template<typename _Tp, int _cols>
void cv2eigen( const Matx<_Tp, 1, _cols>& src,
Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst )
{
dst.resize(_cols);
if( !(dst.Flags & Eigen::RowMajorBit) )
{
const Mat _dst(_cols, 1, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(_cols, 1, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
transpose(src, _dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
else
{
const Mat _dst(1, _cols, traits::Type<_Tp>::value,
dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp)));
Mat _dst(1, _cols, DataType<_Tp>::type,
dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
Mat(src).copyTo(_dst);
CV_DbgAssert(_dst.data == (uchar*)dst.data());
}
}
//! @}
} // cv
}
#endif
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,72 @@
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright( C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
//(including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort(including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef OPENCV_VERSION_HPP
#define OPENCV_VERSION_HPP
/*
definition of the current version of OpenCV
Usefull to test in user programs
*/
#define CV_VERSION_MAJOR 3
#define CV_VERSION_MINOR 4
#define CV_VERSION_REVISION 6
#define CV_VERSION_STATUS ""
#ifndef __OPENCV_VERSION_HPP__
#define __OPENCV_VERSION_HPP__
#define CV_VERSION_EPOCH 2
#define CV_VERSION_MAJOR 4
#define CV_VERSION_MINOR 10
#define CV_VERSION_REVISION 0
#define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)
#define CVAUX_STRW_EXP(__A) L ## #__A
#define CVAUX_STRW_EXP(__A) L#__A
#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A)
#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS
#if CV_VERSION_REVISION
# define CV_VERSION CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION)
#else
# define CV_VERSION CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR)
#endif
/* old style version constants*/
#define CV_MAJOR_VERSION CV_VERSION_MAJOR
#define CV_MINOR_VERSION CV_VERSION_MINOR
#define CV_SUBMINOR_VERSION CV_VERSION_REVISION
#define CV_MAJOR_VERSION CV_VERSION_EPOCH
#define CV_MINOR_VERSION CV_VERSION_MAJOR
#define CV_SUBMINOR_VERSION CV_VERSION_MINOR
#endif // OPENCV_VERSION_HPP
#endif

View File

@ -1,4 +1,4 @@
/*M//////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to
@ -36,11 +36,69 @@
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
/////////////////////////////////////////////////////////////////////////////////
//M*/
#ifndef OPENCV_CORE_WIMAGE_HPP
#define OPENCV_CORE_WIMAGE_HPP
/////////////////////////////////////////////////////////////////////////////////
//
// Image class which provides a thin layer around an IplImage. The goals
// of the class design are:
// 1. All the data has explicit ownership to avoid memory leaks
// 2. No hidden allocations or copies for performance.
// 3. Easy access to OpenCV methods (which will access IPP if available)
// 4. Can easily treat external data as an image
// 5. Easy to create images which are subsets of other images
// 6. Fast pixel access which can take advantage of number of channels
// if known at compile time.
//
// The WImage class is the image class which provides the data accessors.
// The 'W' comes from the fact that it is also a wrapper around the popular
// but inconvenient IplImage class. A WImage can be constructed either using a
// WImageBuffer class which allocates and frees the data,
// or using a WImageView class which constructs a subimage or a view into
// external data. The view class does no memory management. Each class
// actually has two versions, one when the number of channels is known at
// compile time and one when it isn't. Using the one with the number of
// channels specified can provide some compile time optimizations by using the
// fact that the number of channels is a constant.
//
// We use the convention (c,r) to refer to column c and row r with (0,0) being
// the upper left corner. This is similar to standard Euclidean coordinates
// with the first coordinate varying in the horizontal direction and the second
// coordinate varying in the vertical direction.
// Thus (c,r) is usually in the domain [0, width) X [0, height)
//
// Example usage:
// WImageBuffer3_b im(5,7); // Make a 5X7 3 channel image of type uchar
// WImageView3_b sub_im(im, 2,2, 3,3); // 3X3 submatrix
// vector<float> vec(10, 3.0f);
// WImageView1_f user_im(&vec[0], 2, 5); // 2X5 image w/ supplied data
//
// im.SetZero(); // same as cvSetZero(im.Ipl())
// *im(2, 3) = 15; // Modify the element at column 2, row 3
// MySetRand(&sub_im);
//
// // Copy the second row into the first. This can be done with no memory
// // allocation and will use SSE if IPP is available.
// int w = im.Width();
// im.View(0,0, w,1).CopyFrom(im.View(0,1, w,1));
//
// // Doesn't care about source of data since using WImage
// void MySetRand(WImage_b* im) { // Works with any number of channels
// for (int r = 0; r < im->Height(); ++r) {
// float* row = im->Row(r);
// for (int c = 0; c < im->Width(); ++c) {
// for (int ch = 0; ch < im->Channels(); ++ch, ++row) {
// *row = uchar(rand() & 255);
// }
// }
// }
// }
//
// Functions that are not part of the basic image allocation, viewing, and
// access should come from OpenCV, except some useful functions that are not
// part of OpenCV can be found in wimage_util.h
#ifndef __OPENCV_CORE_WIMAGE_HPP__
#define __OPENCV_CORE_WIMAGE_HPP__
#include "opencv2/core/core_c.h"
@ -48,9 +106,6 @@
namespace cv {
//! @addtogroup core
//! @{
template <typename T> class WImage;
template <typename T> class WImageBuffer;
template <typename T> class WImageView;
@ -110,63 +165,12 @@ typedef WImageC<ushort, 3> WImage3_16u;
typedef WImageViewC<ushort, 3> WImageView3_16u;
typedef WImageBufferC<ushort, 3> WImageBuffer3_16u;
/** @brief Image class which provides a thin layer around an IplImage.
The goals of the class design are:
-# All the data has explicit ownership to avoid memory leaks
-# No hidden allocations or copies for performance.
-# Easy access to OpenCV methods (which will access IPP if available)
-# Can easily treat external data as an image
-# Easy to create images which are subsets of other images
-# Fast pixel access which can take advantage of number of channels if known at compile time.
The WImage class is the image class which provides the data accessors. The 'W' comes from the fact
that it is also a wrapper around the popular but inconvenient IplImage class. A WImage can be
constructed either using a WImageBuffer class which allocates and frees the data, or using a
WImageView class which constructs a subimage or a view into external data. The view class does no
memory management. Each class actually has two versions, one when the number of channels is known
at compile time and one when it isn't. Using the one with the number of channels specified can
provide some compile time optimizations by using the fact that the number of channels is a
constant.
We use the convention (c,r) to refer to column c and row r with (0,0) being the upper left corner.
This is similar to standard Euclidean coordinates with the first coordinate varying in the
horizontal direction and the second coordinate varying in the vertical direction. Thus (c,r) is
usually in the domain [0, width) X [0, height)
Example usage:
@code
WImageBuffer3_b im(5,7); // Make a 5X7 3 channel image of type uchar
WImageView3_b sub_im(im, 2,2, 3,3); // 3X3 submatrix
vector<float> vec(10, 3.0f);
WImageView1_f user_im(&vec[0], 2, 5); // 2X5 image w/ supplied data
im.SetZero(); // same as cvSetZero(im.Ipl())
*im(2, 3) = 15; // Modify the element at column 2, row 3
MySetRand(&sub_im);
// Copy the second row into the first. This can be done with no memory
// allocation and will use SSE if IPP is available.
int w = im.Width();
im.View(0,0, w,1).CopyFrom(im.View(0,1, w,1));
// Doesn't care about source of data since using WImage
void MySetRand(WImage_b* im) { // Works with any number of channels
for (int r = 0; r < im->Height(); ++r) {
float* row = im->Row(r);
for (int c = 0; c < im->Width(); ++c) {
for (int ch = 0; ch < im->Channels(); ++ch, ++row) {
*row = uchar(rand() & 255);
}
}
}
}
@endcode
Functions that are not part of the basic image allocation, viewing, and access should come from
OpenCV, except some useful functions that are not part of OpenCV can be found in wimage_util.h
*/
//
// WImage definitions
//
// This WImage class gives access to the data it refers to. It can be
// constructed either by allocating the data with a WImageBuffer class or
// using the WImageView class to refer to a subimage or outside data.
template<typename T>
class WImage
{
@ -248,10 +252,10 @@ protected:
};
/** Image class when both the pixel type and number of channels
are known at compile time. This wrapper will speed up some of the operations
like accessing individual pixels using the () operator.
*/
// Image class when both the pixel type and number of channels
// are known at compile time. This wrapper will speed up some of the operations
// like accessing individual pixels using the () operator.
template<typename T, int C>
class WImageC : public WImage<T>
{
@ -288,9 +292,12 @@ protected:
}
};
/** Image class which owns the data, so it can be allocated and is always
freed. It cannot be copied but can be explicitly cloned.
*/
//
// WImageBuffer definitions
//
// Image class which owns the data, so it can be allocated and is always
// freed. It cannot be copied but can be explicity cloned.
//
template<typename T>
class WImageBuffer : public WImage<T>
{
@ -345,8 +352,8 @@ private:
void operator=(const WImageBuffer&);
};
/** Like a WImageBuffer class but when the number of channels is known at compile time.
*/
// Like a WImageBuffer class but when the number of channels is known
// at compile time.
template<typename T, int C>
class WImageBufferC : public WImageC<T, C>
{
@ -402,10 +409,14 @@ private:
void operator=(const WImageBufferC&);
};
/** View into an image class which allows treating a subimage as an image or treating external data
as an image
*/
template<typename T> class WImageView : public WImage<T>
//
// WImageView definitions
//
// View into an image class which allows treating a subimage as an image
// or treating external data as an image
//
template<typename T>
class WImageView : public WImage<T>
{
public:
typedef typename WImage<T>::BaseType BaseType;
@ -507,9 +518,15 @@ inline int WImage<float>::Depth() const {return IPL_DEPTH_32F; }
template<>
inline int WImage<double>::Depth() const {return IPL_DEPTH_64F; }
//
// Pure virtual destructors still need to be defined.
//
template<typename T> inline WImage<T>::~WImage() {}
template<typename T, int C> inline WImageC<T, C>::~WImageC() {}
//
// Allocate ImageData
//
template<typename T>
inline void WImageBuffer<T>::Allocate(int width, int height, int nchannels)
{
@ -530,6 +547,9 @@ inline void WImageBufferC<T, C>::Allocate(int width, int height)
}
}
//
// ImageView methods
//
template<typename T>
WImageView<T>::WImageView(WImage<T>* img, int c, int r, int width, int height)
: WImage<T>(0)
@ -594,8 +614,6 @@ WImageViewC<T, C> WImageC<T, C>::View(int c, int r, int width, int height) {
return WImageViewC<T, C>(this, c, r, width, height);
}
//! @} core
} // end of namespace
#endif // __cplusplus

View File

@ -97,7 +97,6 @@ public:
blocksize = blockSize;
remaining = 0;
base = NULL;
loc = NULL;
usedMemory = 0;
wastedMemory = 0;
@ -182,9 +181,6 @@ public:
return mem;
}
private:
PooledAllocator(const PooledAllocator &); // copy disabled
PooledAllocator& operator=(const PooledAllocator &); // assign disabled
};
}

View File

@ -44,60 +44,59 @@ struct base_any_policy
virtual void clone(void* const* src, void** dest) = 0;
virtual void move(void* const* src, void** dest) = 0;
virtual void* get_value(void** src) = 0;
virtual const void* get_value(void* const * src) = 0;
virtual ::size_t get_size() = 0;
virtual const std::type_info& type() = 0;
virtual void print(std::ostream& out, void* const* src) = 0;
#ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY
virtual ~base_any_policy() {}
#endif
};
template<typename T>
struct typed_base_any_policy : base_any_policy
{
virtual ::size_t get_size() CV_OVERRIDE { return sizeof(T); }
virtual const std::type_info& type() CV_OVERRIDE { return typeid(T); }
virtual ::size_t get_size() { return sizeof(T); }
virtual const std::type_info& type() { return typeid(T); }
};
template<typename T>
struct small_any_policy CV_FINAL : typed_base_any_policy<T>
struct small_any_policy : typed_base_any_policy<T>
{
virtual void static_delete(void**) CV_OVERRIDE { }
virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE
virtual void static_delete(void**) { }
virtual void copy_from_value(void const* src, void** dest)
{
new (dest) T(* reinterpret_cast<T const*>(src));
}
virtual void clone(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; }
virtual void move(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; }
virtual void* get_value(void** src) CV_OVERRIDE { return reinterpret_cast<void*>(src); }
virtual const void* get_value(void* const * src) CV_OVERRIDE { return reinterpret_cast<const void*>(src); }
virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast<T const*>(src); }
virtual void clone(void* const* src, void** dest) { *dest = *src; }
virtual void move(void* const* src, void** dest) { *dest = *src; }
virtual void* get_value(void** src) { return reinterpret_cast<void*>(src); }
virtual void print(std::ostream& out, void* const* src) { out << *reinterpret_cast<T const*>(src); }
};
template<typename T>
struct big_any_policy CV_FINAL : typed_base_any_policy<T>
struct big_any_policy : typed_base_any_policy<T>
{
virtual void static_delete(void** x) CV_OVERRIDE
virtual void static_delete(void** x)
{
if (* x) delete (* reinterpret_cast<T**>(x));
*x = NULL;
if (* x) delete (* reinterpret_cast<T**>(x)); *x = NULL;
}
virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE
virtual void copy_from_value(void const* src, void** dest)
{
*dest = new T(*reinterpret_cast<T const*>(src));
}
virtual void clone(void* const* src, void** dest) CV_OVERRIDE
virtual void clone(void* const* src, void** dest)
{
*dest = new T(**reinterpret_cast<T* const*>(src));
}
virtual void move(void* const* src, void** dest) CV_OVERRIDE
virtual void move(void* const* src, void** dest)
{
(*reinterpret_cast<T**>(dest))->~T();
**reinterpret_cast<T**>(dest) = **reinterpret_cast<T* const*>(src);
}
virtual void* get_value(void** src) CV_OVERRIDE { return *src; }
virtual const void* get_value(void* const * src) CV_OVERRIDE { return *src; }
virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast<T const*>(*src); }
virtual void* get_value(void** src) { return *src; }
virtual void print(std::ostream& out, void* const* src) { out << *reinterpret_cast<T const*>(*src); }
};
template<> inline void big_any_policy<flann_centers_init_t>::print(std::ostream& out, void* const* src)
@ -110,11 +109,6 @@ template<> inline void big_any_policy<flann_algorithm_t>::print(std::ostream& ou
out << int(*reinterpret_cast<flann_algorithm_t const*>(*src));
}
template<> inline void big_any_policy<cv::String>::print(std::ostream& out, void* const* src)
{
out << (*reinterpret_cast<cv::String const*>(*src)).c_str();
}
template<typename T>
struct choose_policy
{
@ -156,27 +150,13 @@ SMALL_POLICY(bool);
#undef SMALL_POLICY
template <typename T>
class SinglePolicy
{
SinglePolicy();
SinglePolicy(const SinglePolicy& other);
SinglePolicy& operator=(const SinglePolicy& other);
public:
static base_any_policy* get_policy();
private:
static typename choose_policy<T>::type policy;
};
template <typename T>
typename choose_policy<T>::type SinglePolicy<T>::policy;
/// This function will return a different policy for each type.
template <typename T>
inline base_any_policy* SinglePolicy<T>::get_policy() { return &policy; }
template<typename T>
base_any_policy* get_policy()
{
static typename choose_policy<T>::type policy;
return &policy;
}
} // namespace anyimpl
struct any
@ -190,26 +170,26 @@ public:
/// Initializing constructor.
template <typename T>
any(const T& x)
: policy(anyimpl::SinglePolicy<anyimpl::empty_any>::get_policy()), object(NULL)
: policy(anyimpl::get_policy<anyimpl::empty_any>()), object(NULL)
{
assign(x);
}
/// Empty constructor.
any()
: policy(anyimpl::SinglePolicy<anyimpl::empty_any>::get_policy()), object(NULL)
: policy(anyimpl::get_policy<anyimpl::empty_any>()), object(NULL)
{ }
/// Special initializing constructor for string literals.
any(const char* x)
: policy(anyimpl::SinglePolicy<anyimpl::empty_any>::get_policy()), object(NULL)
: policy(anyimpl::get_policy<anyimpl::empty_any>()), object(NULL)
{
assign(x);
}
/// Copy constructor.
any(const any& x)
: policy(anyimpl::SinglePolicy<anyimpl::empty_any>::get_policy()), object(NULL)
: policy(anyimpl::get_policy<anyimpl::empty_any>()), object(NULL)
{
assign(x);
}
@ -234,7 +214,7 @@ public:
any& assign(const T& x)
{
reset();
policy = anyimpl::SinglePolicy<T>::get_policy();
policy = anyimpl::get_policy<T>();
policy->copy_from_value(&x, &object);
return *this;
}
@ -246,12 +226,6 @@ public:
return assign(x);
}
/// Assignment operator. Template-based version above doesn't work as expected. We need regular assignment operator here.
any& operator=(const any& x)
{
return assign(x);
}
/// Assignment operator, specialed for literal strings.
/// They have types like const char [6] which don't work as expected.
any& operator=(const char* x)
@ -281,7 +255,7 @@ public:
const T& cast() const
{
if (policy->type() != typeid(T)) throw anyimpl::bad_any_cast();
const T* r = reinterpret_cast<const T*>(policy->get_value(&object));
T* r = reinterpret_cast<T*>(policy->get_value(const_cast<void **>(&object)));
return *r;
}
@ -295,7 +269,7 @@ public:
void reset()
{
policy->static_delete(&object);
policy = anyimpl::SinglePolicy<anyimpl::empty_any>::get_policy();
policy = anyimpl::get_policy<anyimpl::empty_any>();
}
/// Returns true if the two types are the same.

View File

@ -30,8 +30,6 @@
#ifndef OPENCV_FLANN_AUTOTUNED_INDEX_H_
#define OPENCV_FLANN_AUTOTUNED_INDEX_H_
#include <sstream>
#include "general.h"
#include "nn_index.h"
#include "ground_truth.h"
@ -83,7 +81,6 @@ public:
memory_weight_ = get_param(params, "memory_weight", 0.0f);
sample_fraction_ = get_param(params,"sample_fraction", 0.1f);
bestIndex_ = NULL;
speedup_ = 0;
}
AutotunedIndex(const AutotunedIndex&);
@ -100,7 +97,7 @@ public:
/**
* Method responsible with building the index.
*/
virtual void buildIndex() CV_OVERRIDE
virtual void buildIndex()
{
std::ostringstream stream;
bestParams_ = estimateBuildParams();
@ -124,7 +121,7 @@ public:
/**
* Saves the index to a stream
*/
virtual void saveIndex(FILE* stream) CV_OVERRIDE
virtual void saveIndex(FILE* stream)
{
save_value(stream, (int)bestIndex_->getType());
bestIndex_->saveIndex(stream);
@ -134,7 +131,7 @@ public:
/**
* Loads the index from a stream
*/
virtual void loadIndex(FILE* stream) CV_OVERRIDE
virtual void loadIndex(FILE* stream)
{
int index_type;
@ -151,7 +148,7 @@ public:
/**
* Method that searches for nearest-neighbors
*/
virtual void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
virtual void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
{
int checks = get_param<int>(searchParams,"checks",FLANN_CHECKS_AUTOTUNED);
if (checks == FLANN_CHECKS_AUTOTUNED) {
@ -163,7 +160,7 @@ public:
}
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return bestIndex_->getParameters();
}
@ -182,7 +179,7 @@ public:
/**
* Number of features in this index.
*/
virtual size_t size() const CV_OVERRIDE
virtual size_t size() const
{
return bestIndex_->size();
}
@ -190,7 +187,7 @@ public:
/**
* The length of each vector in this index.
*/
virtual size_t veclen() const CV_OVERRIDE
virtual size_t veclen() const
{
return bestIndex_->veclen();
}
@ -198,7 +195,7 @@ public:
/**
* The amount of memory (in bytes) this index uses.
*/
virtual int usedMemory() const CV_OVERRIDE
virtual int usedMemory() const
{
return bestIndex_->usedMemory();
}
@ -206,7 +203,7 @@ public:
/**
* Algorithm name
*/
virtual flann_algorithm_t getType() const CV_OVERRIDE
virtual flann_algorithm_t getType() const
{
return FLANN_INDEX_AUTOTUNED;
}
@ -277,7 +274,7 @@ private:
// struct KMeansSimpleDownhillFunctor {
//
// Autotune& autotuner;
// KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {}
// KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {};
//
// float operator()(int* params) {
//
@ -302,7 +299,7 @@ private:
// struct KDTreeSimpleDownhillFunctor {
//
// Autotune& autotuner;
// KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {}
// KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {};
//
// float operator()(int* params) {
// float maxFloat = numeric_limits<float>::max();
@ -380,7 +377,6 @@ private:
// evaluate kdtree for all parameter combinations
for (size_t i = 0; i < FLANN_ARRAY_LEN(testTrees); ++i) {
CostData cost;
cost.params["algorithm"] = FLANN_INDEX_KDTREE;
cost.params["trees"] = testTrees[i];
evaluate_kdtree(cost);

View File

@ -101,7 +101,7 @@ public:
/**
* @return The index type
*/
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return FLANN_INDEX_COMPOSITE;
}
@ -109,7 +109,7 @@ public:
/**
* @return Size of the index
*/
size_t size() const CV_OVERRIDE
size_t size() const
{
return kdtree_index_->size();
}
@ -117,7 +117,7 @@ public:
/**
* \returns The dimensionality of the features in this index.
*/
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return kdtree_index_->veclen();
}
@ -125,7 +125,7 @@ public:
/**
* \returns The amount of memory (in bytes) used by the index.
*/
int usedMemory() const CV_OVERRIDE
int usedMemory() const
{
return kmeans_index_->usedMemory() + kdtree_index_->usedMemory();
}
@ -133,7 +133,7 @@ public:
/**
* \brief Builds the index
*/
void buildIndex() CV_OVERRIDE
void buildIndex()
{
Logger::info("Building kmeans tree...\n");
kmeans_index_->buildIndex();
@ -145,7 +145,7 @@ public:
* \brief Saves the index to a stream
* \param stream The stream to save the index to
*/
void saveIndex(FILE* stream) CV_OVERRIDE
void saveIndex(FILE* stream)
{
kmeans_index_->saveIndex(stream);
kdtree_index_->saveIndex(stream);
@ -155,7 +155,7 @@ public:
* \brief Loads the index from a stream
* \param stream The stream from which the index is loaded
*/
void loadIndex(FILE* stream) CV_OVERRIDE
void loadIndex(FILE* stream)
{
kmeans_index_->loadIndex(stream);
kdtree_index_->loadIndex(stream);
@ -164,7 +164,7 @@ public:
/**
* \returns The index parameters
*/
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return index_params_;
}
@ -172,7 +172,7 @@ public:
/**
* \brief Method that searches for nearest-neighbours
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
{
kmeans_index_->findNeighbors(result, vec, searchParams);
kdtree_index_->findNeighbors(result, vec, searchParams);

View File

@ -35,7 +35,7 @@
#ifdef FLANN_EXPORT
#undef FLANN_EXPORT
#endif
#ifdef _WIN32
#ifdef WIN32
/* win32 dll export/import directives */
#ifdef FLANN_EXPORTS
#define FLANN_EXPORT __declspec(dllexport)
@ -50,6 +50,19 @@
#endif
#ifdef FLANN_DEPRECATED
#undef FLANN_DEPRECATED
#endif
#ifdef __GNUC__
#define FLANN_DEPRECATED __attribute__ ((deprecated))
#elif defined(_MSC_VER)
#define FLANN_DEPRECATED __declspec(deprecated)
#else
#pragma message("WARNING: You need to implement FLANN_DEPRECATED for this compiler")
#define FLANN_DEPRECATED
#endif
#undef FLANN_PLATFORM_32_BIT
#undef FLANN_PLATFORM_64_BIT
#if defined __amd64__ || defined __x86_64__ || defined _WIN64 || defined _M_X64
@ -94,7 +107,6 @@ enum flann_centers_init_t
FLANN_CENTERS_RANDOM = 0,
FLANN_CENTERS_GONZALES = 1,
FLANN_CENTERS_KMEANSPP = 2,
FLANN_CENTERS_GROUPWISE = 3,
// deprecated constants, should use the FLANN_CENTERS_* ones instead
CENTERS_RANDOM = 0,

View File

@ -43,11 +43,11 @@ typedef unsigned __int64 uint64_t;
#include "defines.h"
#if defined _WIN32 && defined(_M_ARM)
#if (defined WIN32 || defined _WIN32) && defined(_M_ARM)
# include <Intrin.h>
#endif
#if defined(__ARM_NEON__) && !defined(__CUDACC__)
#ifdef __ARM_NEON__
# include "arm_neon.h"
#endif
@ -384,6 +384,41 @@ struct HammingLUT
typedef unsigned char ElementType;
typedef int ResultType;
/** this will count the bits in a ^ b
*/
ResultType operator()(const unsigned char* a, const unsigned char* b, int size) const
{
static const uchar popCountTable[] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
ResultType result = 0;
for (int i = 0; i < size; i++) {
result += popCountTable[a[i] ^ b[i]];
}
return result;
}
};
/**
* Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor
* bit count of A exclusive XOR'ed with B
*/
struct HammingLUT2
{
typedef False is_kdtree_distance;
typedef False is_vector_space_distance;
typedef unsigned char ElementType;
typedef int ResultType;
/** this will count the bits in a ^ b
*/
ResultType operator()(const unsigned char* a, const unsigned char* b, size_t size) const
@ -425,7 +460,7 @@ struct Hamming
ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
{
ResultType result = 0;
#if defined(__ARM_NEON__) && !defined(__CUDACC__)
#ifdef __ARM_NEON__
{
uint32x4_t bits = vmovq_n_u32(0);
for (size_t i = 0; i < size; i += 16) {
@ -462,9 +497,10 @@ struct Hamming
}
}
#else // NO NEON and NOT GNUC
typedef unsigned long long pop_t;
HammingLUT lut;
result = lut(reinterpret_cast<const unsigned char*> (a),
reinterpret_cast<const unsigned char*> (b), size);
reinterpret_cast<const unsigned char*> (b), size * sizeof(pop_t));
#endif
return result;
}
@ -594,7 +630,7 @@ struct HellingerDistance
typedef typename Accumulator<T>::Type ResultType;
/**
* Compute the Hellinger distance
* Compute the histogram intersection distance
*/
template <typename Iterator1, typename Iterator2>
ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
@ -627,8 +663,7 @@ struct HellingerDistance
template <typename U, typename V>
inline ResultType accum_dist(const U& a, const V& b, int) const
{
ResultType diff = sqrt(static_cast<ResultType>(a)) - sqrt(static_cast<ResultType>(b));
return diff * diff;
return sqrt(static_cast<ResultType>(a)) - sqrt(static_cast<ResultType>(b));
}
};
@ -697,7 +732,7 @@ struct KL_Divergence
typedef typename Accumulator<T>::Type ResultType;
/**
* Compute the Kullback-Leibler divergence
* Compute the KullbackLeibler divergence
*/
template <typename Iterator1, typename Iterator2>
ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const
@ -706,7 +741,7 @@ struct KL_Divergence
Iterator1 last = a + size;
while (a < last) {
if (* b != 0) {
if (* a != 0) {
ResultType ratio = (ResultType)(*a / *b);
if (ratio>0) {
result += *a * log(ratio);
@ -729,11 +764,9 @@ struct KL_Divergence
inline ResultType accum_dist(const U& a, const V& b, int) const
{
ResultType result = ResultType();
if( *b != 0 ) {
ResultType ratio = (ResultType)(a / b);
if (ratio>0) {
result = a * log(ratio);
}
ResultType ratio = (ResultType)(a / b);
if (ratio>0) {
result = a * log(ratio);
}
return result;
}
@ -842,7 +875,7 @@ typename Distance::ResultType ensureSquareDistance( typename Distance::ResultTyp
/*
* ...and a template to ensure the user that he will process the normal distance,
* and not squared distance, without losing processing time calling sqrt(ensureSquareDistance)
* and not squared distance, without loosing processing time calling sqrt(ensureSquareDistance)
* that will result in doing actually sqrt(dist*dist) for L1 distance for instance.
*/
template <typename Distance, typename ElementType>

View File

@ -5,7 +5,10 @@
namespace cvflann
{
CV_DEPRECATED inline void dummyfunc() {}
#if (defined WIN32 || defined _WIN32 || defined WINCE) && defined CVAPI_EXPORTS
__declspec(dllexport)
#endif
void dummyfunc();
}

View File

@ -57,14 +57,14 @@ namespace cvflann {
class DynamicBitset
{
public:
/** default constructor
/** @param default constructor
*/
DynamicBitset() : size_(0)
DynamicBitset()
{
}
/** only constructor we use in our code
* @param sz the size of the bitset (in bits)
/** @param only constructor we use in our code
* @param the size of the bitset (in bits)
*/
DynamicBitset(size_t sz)
{
@ -87,7 +87,7 @@ public:
return bitset_.empty();
}
/** set all the bits to 0
/** @param set all the bits to 0
*/
void reset()
{
@ -95,7 +95,7 @@ public:
}
/** @brief set one bit to 0
* @param index
* @param
*/
void reset(size_t index)
{
@ -106,15 +106,15 @@ public:
* This function is useful when resetting a given set of bits so that the
* whole bitset ends up being 0: if that's the case, we don't care about setting
* other bits to 0
* @param index
* @param
*/
void reset_block(size_t index)
{
bitset_[index / cell_bit_size_] = 0;
}
/** resize the bitset so that it contains at least sz bits
* @param sz
/** @param resize the bitset so that it contains at least size bits
* @param size
*/
void resize(size_t sz)
{
@ -122,7 +122,7 @@ public:
bitset_.resize(sz / cell_bit_size_ + 1);
}
/** set a bit to true
/** @param set a bit to true
* @param index the index of the bit to set to 1
*/
void set(size_t index)
@ -130,14 +130,14 @@ public:
bitset_[index / cell_bit_size_] |= size_t(1) << (index % cell_bit_size_);
}
/** gives the number of contained bits
/** @param gives the number of contained bits
*/
size_t size() const
{
return size_;
}
/** check if a bit is set
/** @param check if a bit is set
* @param index the index of the bit to check
* @return true if the bit is set
*/

View File

@ -7,12 +7,11 @@
// copy or use the software.
//
//
// License Agreement
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
@ -41,8 +40,388 @@
//
//M*/
#ifdef __OPENCV_BUILD
#error this is a compatibility header which should not be used inside the OpenCV library
#ifndef _OPENCV_FLANN_HPP_
#define _OPENCV_FLANN_HPP_
#ifdef __cplusplus
#include "opencv2/core/types_c.h"
#include "opencv2/core/core.hpp"
#include "opencv2/flann/flann_base.hpp"
#include "opencv2/flann/miniflann.hpp"
namespace cvflann
{
CV_EXPORTS flann_distance_t flann_distance_type();
FLANN_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order);
}
namespace cv
{
namespace flann
{
template <typename T> struct CvType {};
template <> struct CvType<unsigned char> { static int type() { return CV_8U; } };
template <> struct CvType<char> { static int type() { return CV_8S; } };
template <> struct CvType<unsigned short> { static int type() { return CV_16U; } };
template <> struct CvType<short> { static int type() { return CV_16S; } };
template <> struct CvType<int> { static int type() { return CV_32S; } };
template <> struct CvType<float> { static int type() { return CV_32F; } };
template <> struct CvType<double> { static int type() { return CV_64F; } };
// bring the flann parameters into this namespace
using ::cvflann::get_param;
using ::cvflann::print_params;
// bring the flann distances into this namespace
using ::cvflann::L2_Simple;
using ::cvflann::L2;
using ::cvflann::L1;
using ::cvflann::MinkowskiDistance;
using ::cvflann::MaxDistance;
using ::cvflann::HammingLUT;
using ::cvflann::Hamming;
using ::cvflann::Hamming2;
using ::cvflann::HistIntersectionDistance;
using ::cvflann::HellingerDistance;
using ::cvflann::ChiSquareDistance;
using ::cvflann::KL_Divergence;
template <typename Distance>
class GenericIndex
{
public:
typedef typename Distance::ElementType ElementType;
typedef typename Distance::ResultType DistanceType;
GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance());
~GenericIndex();
void knnSearch(const vector<ElementType>& query, vector<int>& indices,
vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& params);
void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params);
int radiusSearch(const vector<ElementType>& query, vector<int>& indices,
vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& params);
int radiusSearch(const Mat& query, Mat& indices, Mat& dists,
DistanceType radius, const ::cvflann::SearchParams& params);
void save(std::string filename) { nnIndex->save(filename); }
int veclen() const { return nnIndex->veclen(); }
int size() const { return nnIndex->size(); }
::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); }
FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); }
private:
::cvflann::Index<Distance>* nnIndex;
};
#define FLANN_DISTANCE_CHECK \
if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \
printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\
"the distance using cvflann::set_distance_type. This is no longer working as expected "\
"(cv::flann::Index always uses L2). You should create the index templated on the distance, "\
"for example for L1 distance use: GenericIndex< L1<float> > \n"); \
}
template <typename Distance>
GenericIndex<Distance>::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance)
{
CV_Assert(dataset.type() == CvType<ElementType>::type());
CV_Assert(dataset.isContinuous());
::cvflann::Matrix<ElementType> m_dataset((ElementType*)dataset.ptr<ElementType>(0), dataset.rows, dataset.cols);
nnIndex = new ::cvflann::Index<Distance>(m_dataset, params, distance);
FLANN_DISTANCE_CHECK
nnIndex->buildIndex();
}
template <typename Distance>
GenericIndex<Distance>::~GenericIndex()
{
delete nnIndex;
}
template <typename Distance>
void GenericIndex<Distance>::knnSearch(const vector<ElementType>& query, vector<int>& indices, vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& searchParams)
{
::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
FLANN_DISTANCE_CHECK
nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
}
template <typename Distance>
void GenericIndex<Distance>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams)
{
CV_Assert(queries.type() == CvType<ElementType>::type());
CV_Assert(queries.isContinuous());
::cvflann::Matrix<ElementType> m_queries((ElementType*)queries.ptr<ElementType>(0), queries.rows, queries.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CvType<DistanceType>::type());
CV_Assert(dists.isContinuous());
::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
FLANN_DISTANCE_CHECK
nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
}
template <typename Distance>
int GenericIndex<Distance>::radiusSearch(const vector<ElementType>& query, vector<int>& indices, vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
{
::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
FLANN_DISTANCE_CHECK
return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
template <typename Distance>
int GenericIndex<Distance>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
{
CV_Assert(query.type() == CvType<ElementType>::type());
CV_Assert(query.isContinuous());
::cvflann::Matrix<ElementType> m_query((ElementType*)query.ptr<ElementType>(0), query.rows, query.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CvType<DistanceType>::type());
CV_Assert(dists.isContinuous());
::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
FLANN_DISTANCE_CHECK
return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
/**
* @deprecated Use GenericIndex class instead
*/
template <typename T>
class
#ifndef _MSC_VER
FLANN_DEPRECATED
#endif
Index_ {
public:
typedef typename L2<T>::ElementType ElementType;
typedef typename L2<T>::ResultType DistanceType;
Index_(const Mat& features, const ::cvflann::IndexParams& params);
~Index_();
void knnSearch(const vector<ElementType>& query, vector<int>& indices, vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& params);
void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params);
int radiusSearch(const vector<ElementType>& query, vector<int>& indices, vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& params);
int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& params);
void save(std::string filename)
{
if (nnIndex_L1) nnIndex_L1->save(filename);
if (nnIndex_L2) nnIndex_L2->save(filename);
}
int veclen() const
{
if (nnIndex_L1) return nnIndex_L1->veclen();
if (nnIndex_L2) return nnIndex_L2->veclen();
}
int size() const
{
if (nnIndex_L1) return nnIndex_L1->size();
if (nnIndex_L2) return nnIndex_L2->size();
}
::cvflann::IndexParams getParameters()
{
if (nnIndex_L1) return nnIndex_L1->getParameters();
if (nnIndex_L2) return nnIndex_L2->getParameters();
}
FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters()
{
if (nnIndex_L1) return nnIndex_L1->getIndexParameters();
if (nnIndex_L2) return nnIndex_L2->getIndexParameters();
}
private:
// providing backwards compatibility for L2 and L1 distances (most common)
::cvflann::Index< L2<ElementType> >* nnIndex_L2;
::cvflann::Index< L1<ElementType> >* nnIndex_L1;
};
#ifdef _MSC_VER
template <typename T>
class FLANN_DEPRECATED Index_;
#endif
#include "opencv2/flann.hpp"
template <typename T>
Index_<T>::Index_(const Mat& dataset, const ::cvflann::IndexParams& params)
{
printf("[WARNING] The cv::flann::Index_<T> class is deperecated, use cv::flann::GenericIndex<Distance> instead\n");
CV_Assert(dataset.type() == CvType<ElementType>::type());
CV_Assert(dataset.isContinuous());
::cvflann::Matrix<ElementType> m_dataset((ElementType*)dataset.ptr<ElementType>(0), dataset.rows, dataset.cols);
if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) {
nnIndex_L1 = NULL;
nnIndex_L2 = new ::cvflann::Index< L2<ElementType> >(m_dataset, params);
}
else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) {
nnIndex_L1 = new ::cvflann::Index< L1<ElementType> >(m_dataset, params);
nnIndex_L2 = NULL;
}
else {
printf("[ERROR] cv::flann::Index_<T> only provides backwards compatibility for the L1 and L2 distances. "
"For other distance types you must use cv::flann::GenericIndex<Distance>\n");
CV_Assert(0);
}
if (nnIndex_L1) nnIndex_L1->buildIndex();
if (nnIndex_L2) nnIndex_L2->buildIndex();
}
template <typename T>
Index_<T>::~Index_()
{
if (nnIndex_L1) delete nnIndex_L1;
if (nnIndex_L2) delete nnIndex_L2;
}
template <typename T>
void Index_<T>::knnSearch(const vector<ElementType>& query, vector<int>& indices, vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& searchParams)
{
::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
}
template <typename T>
void Index_<T>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams)
{
CV_Assert(queries.type() == CvType<ElementType>::type());
CV_Assert(queries.isContinuous());
::cvflann::Matrix<ElementType> m_queries((ElementType*)queries.ptr<ElementType>(0), queries.rows, queries.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CvType<DistanceType>::type());
CV_Assert(dists.isContinuous());
::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
}
template <typename T>
int Index_<T>::radiusSearch(const vector<ElementType>& query, vector<int>& indices, vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
{
::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
template <typename T>
int Index_<T>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
{
CV_Assert(query.type() == CvType<ElementType>::type());
CV_Assert(query.isContinuous());
::cvflann::Matrix<ElementType> m_query((ElementType*)query.ptr<ElementType>(0), query.rows, query.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CvType<DistanceType>::type());
CV_Assert(dists.isContinuous());
::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
template <typename Distance>
int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params,
Distance d = Distance())
{
typedef typename Distance::ElementType ElementType;
typedef typename Distance::ResultType DistanceType;
CV_Assert(features.type() == CvType<ElementType>::type());
CV_Assert(features.isContinuous());
::cvflann::Matrix<ElementType> m_features((ElementType*)features.ptr<ElementType>(0), features.rows, features.cols);
CV_Assert(centers.type() == CvType<DistanceType>::type());
CV_Assert(centers.isContinuous());
::cvflann::Matrix<DistanceType> m_centers((DistanceType*)centers.ptr<DistanceType>(0), centers.rows, centers.cols);
return ::cvflann::hierarchicalClustering<Distance>(m_features, m_centers, params, d);
}
template <typename ELEM_TYPE, typename DIST_TYPE>
FLANN_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params)
{
printf("[WARNING] cv::flann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE> is deprecated, use "
"cv::flann::hierarchicalClustering<Distance> instead\n");
if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) {
return hierarchicalClustering< L2<ELEM_TYPE> >(features, centers, params);
}
else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) {
return hierarchicalClustering< L1<ELEM_TYPE> >(features, centers, params);
}
else {
printf("[ERROR] cv::flann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE> only provides backwards "
"compatibility for the L1 and L2 distances. "
"For other distance types you must use cv::flann::hierarchicalClustering<Distance>\n");
CV_Assert(0);
}
}
} } // namespace cv::flann
#endif // __cplusplus
#endif

View File

@ -32,6 +32,7 @@
#define OPENCV_FLANN_BASE_HPP_
#include <vector>
#include <string>
#include <cassert>
#include <cstdio>
@ -61,7 +62,7 @@ inline void log_verbosity(int level)
*/
struct SavedIndexParams : public IndexParams
{
SavedIndexParams(cv::String filename)
SavedIndexParams(std::string filename)
{
(* this)["algorithm"] = FLANN_INDEX_SAVED;
(*this)["filename"] = filename;
@ -70,7 +71,7 @@ struct SavedIndexParams : public IndexParams
template<typename Distance>
NNIndex<Distance>* load_saved_index(const Matrix<typename Distance::ElementType>& dataset, const cv::String& filename, Distance distance)
NNIndex<Distance>* load_saved_index(const Matrix<typename Distance::ElementType>& dataset, const std::string& filename, Distance distance)
{
typedef typename Distance::ElementType ElementType;
@ -80,11 +81,9 @@ NNIndex<Distance>* load_saved_index(const Matrix<typename Distance::ElementType>
}
IndexHeader header = load_header(fin);
if (header.data_type != Datatype<ElementType>::type()) {
fclose(fin);
throw FLANNException("Datatype of saved index is different than of the one to be created.");
}
if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) {
fclose(fin);
throw FLANNException("The index saved belongs to a different dataset");
}
@ -112,7 +111,7 @@ public:
loaded_ = false;
if (index_type == FLANN_INDEX_SAVED) {
nnIndex_ = load_saved_index<Distance>(features, get_param<cv::String>(params,"filename"), distance);
nnIndex_ = load_saved_index<Distance>(features, get_param<std::string>(params,"filename"), distance);
loaded_ = true;
}
else {
@ -128,14 +127,14 @@ public:
/**
* Builds the index.
*/
void buildIndex() CV_OVERRIDE
void buildIndex()
{
if (!loaded_) {
nnIndex_->buildIndex();
}
}
void save(cv::String filename)
void save(std::string filename)
{
FILE* fout = fopen(filename.c_str(), "wb");
if (fout == NULL) {
@ -150,7 +149,7 @@ public:
* \brief Saves the index to a stream
* \param stream The stream to save the index to
*/
virtual void saveIndex(FILE* stream) CV_OVERRIDE
virtual void saveIndex(FILE* stream)
{
nnIndex_->saveIndex(stream);
}
@ -159,7 +158,7 @@ public:
* \brief Loads the index from a stream
* \param stream The stream from which the index is loaded
*/
virtual void loadIndex(FILE* stream) CV_OVERRIDE
virtual void loadIndex(FILE* stream)
{
nnIndex_->loadIndex(stream);
}
@ -167,7 +166,7 @@ public:
/**
* \returns number of features in this index.
*/
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return nnIndex_->veclen();
}
@ -175,7 +174,7 @@ public:
/**
* \returns The dimensionality of the features in this index.
*/
size_t size() const CV_OVERRIDE
size_t size() const
{
return nnIndex_->size();
}
@ -183,7 +182,7 @@ public:
/**
* \returns The index type (kdtree, kmeans,...)
*/
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return nnIndex_->getType();
}
@ -191,7 +190,7 @@ public:
/**
* \returns The amount of memory (in bytes) used by the index.
*/
virtual int usedMemory() const CV_OVERRIDE
virtual int usedMemory() const
{
return nnIndex_->usedMemory();
}
@ -200,7 +199,7 @@ public:
/**
* \returns The index parameters
*/
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return nnIndex_->getParameters();
}
@ -213,7 +212,7 @@ public:
* \param[in] knn Number of nearest neighbors to return
* \param[in] params Search parameters
*/
void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params) CV_OVERRIDE
void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params)
{
nnIndex_->knnSearch(queries, indices, dists, knn, params);
}
@ -227,7 +226,7 @@ public:
* \param[in] params Search parameters
* \returns Number of neighbors found
*/
int radiusSearch(const Matrix<ElementType>& query, Matrix<int>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params) CV_OVERRIDE
int radiusSearch(const Matrix<ElementType>& query, Matrix<int>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params)
{
return nnIndex_->radiusSearch(query, indices, dists, radius, params);
}
@ -235,7 +234,7 @@ public:
/**
* \brief Method that searches for nearest-neighbours
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
{
nnIndex_->findNeighbors(result, vec, searchParams);
}
@ -243,7 +242,7 @@ public:
/**
* \brief Returns actual index
*/
CV_DEPRECATED NNIndex<Distance>* getIndex()
FLANN_DEPRECATED NNIndex<Distance>* getIndex()
{
return nnIndex_;
}
@ -252,7 +251,7 @@ public:
* \brief Returns index parameters.
* \deprecated use getParameters() instead.
*/
CV_DEPRECATED const IndexParams* getIndexParameters()
FLANN_DEPRECATED const IndexParams* getIndexParameters()
{
return &index_params_;
}
@ -264,9 +263,6 @@ private:
bool loaded_;
/** Parameters passed to the index */
IndexParams index_params_;
Index(const Index &); // copy disabled
Index& operator=(const Index &); // assign disabled
};
/**

View File

@ -31,17 +31,19 @@
#ifndef OPENCV_FLANN_GENERAL_H_
#define OPENCV_FLANN_GENERAL_H_
#include "opencv2/core.hpp"
#include "defines.h"
#include <stdexcept>
#include <cassert>
namespace cvflann
{
class FLANNException : public cv::Exception
class FLANNException : public std::runtime_error
{
public:
FLANNException(const char* message) : cv::Exception(0, message, "", __FILE__, __LINE__) { }
FLANNException(const char* message) : std::runtime_error(message) { }
FLANNException(const cv::String& message) : cv::Exception(0, message, "", __FILE__, __LINE__) { }
FLANNException(const std::string& message) : std::runtime_error(message) { }
};
}

View File

@ -73,7 +73,7 @@ hid_t get_hdf5_type<double>() { return H5T_NATIVE_DOUBLE; }
#define CHECK_ERROR(x,y) if ((x)<0) throw FLANNException((y));
template<typename T>
void save_to_file(const cvflann::Matrix<T>& dataset, const String& filename, const String& name)
void save_to_file(const cvflann::Matrix<T>& dataset, const std::string& filename, const std::string& name)
{
#if H5Eset_auto_vers == 2
@ -125,7 +125,7 @@ void save_to_file(const cvflann::Matrix<T>& dataset, const String& filename, con
template<typename T>
void load_from_file(cvflann::Matrix<T>& dataset, const String& filename, const String& name)
void load_from_file(cvflann::Matrix<T>& dataset, const std::string& filename, const std::string& name)
{
herr_t status;
hid_t file_id = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
@ -166,7 +166,7 @@ namespace mpi
* @param name Name of dataset inside file
*/
template<typename T>
void load_from_file(cvflann::Matrix<T>& dataset, const String& filename, const String& name)
void load_from_file(cvflann::Matrix<T>& dataset, const std::string& filename, const std::string& name)
{
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Info info = MPI_INFO_NULL;

View File

@ -32,6 +32,7 @@
#define OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_
#include <algorithm>
#include <string>
#include <map>
#include <cassert>
#include <limits>
@ -266,84 +267,6 @@ private:
}
/**
* Chooses the initial centers in a way inspired by Gonzales (by Pierre-Emmanuel Viel):
* select the first point of the list as a candidate, then parse the points list. If another
* point is further than current candidate from the other centers, test if it is a good center
* of a local aggregation. If it is, replace current candidate by this point. And so on...
*
* Used with KMeansIndex that computes centers coordinates by averaging positions of clusters points,
* this doesn't make a real difference with previous methods. But used with HierarchicalClusteringIndex
* class that pick centers among existing points instead of computing the barycenters, there is a real
* improvement.
*
* Params:
* k = number of centers
* vecs = the dataset of points
* indices = indices in the dataset
* Returns:
*/
void GroupWiseCenterChooser(int k, int* dsindices, int indices_length, int* centers, int& centers_length)
{
const float kSpeedUpFactor = 1.3f;
int n = indices_length;
DistanceType* closestDistSq = new DistanceType[n];
// Choose one random center and set the closestDistSq values
int index = rand_int(n);
assert(index >=0 && index < n);
centers[0] = dsindices[index];
for (int i = 0; i < n; i++) {
closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols);
}
// Choose each center
int centerCount;
for (centerCount = 1; centerCount < k; centerCount++) {
// Repeat several trials
double bestNewPot = -1;
int bestNewIndex = 0;
DistanceType furthest = 0;
for (index = 0; index < n; index++) {
// We will test only the potential of the points further than current candidate
if( closestDistSq[index] > kSpeedUpFactor * (float)furthest ) {
// Compute the new potential
double newPot = 0;
for (int i = 0; i < n; i++) {
newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols)
, closestDistSq[i] );
}
// Store the best result
if ((bestNewPot < 0)||(newPot <= bestNewPot)) {
bestNewPot = newPot;
bestNewIndex = index;
furthest = closestDistSq[index];
}
}
}
// Add the appropriate center
centers[centerCount] = dsindices[bestNewIndex];
for (int i = 0; i < n; i++) {
closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols)
, closestDistSq[i] );
}
}
centers_length = centerCount;
delete[] closestDistSq;
}
public:
@ -377,9 +300,6 @@ public:
else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
chooseCenters = &HierarchicalClusteringIndex::chooseCentersKMeanspp;
}
else if (centers_init_==FLANN_CENTERS_GROUPWISE) {
chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser;
}
else {
throw FLANNException("Unknown algorithm for choosing initial centers.");
}
@ -435,7 +355,7 @@ public:
/**
* Returns size of index.
*/
size_t size() const CV_OVERRIDE
size_t size() const
{
return size_;
}
@ -443,7 +363,7 @@ public:
/**
* Returns the length of an index feature.
*/
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return veclen_;
}
@ -453,7 +373,7 @@ public:
* Computes the inde memory usage
* Returns: memory used by the index
*/
int usedMemory() const CV_OVERRIDE
int usedMemory() const
{
return pool.usedMemory+pool.wastedMemory+memoryCounter;
}
@ -461,7 +381,7 @@ public:
/**
* Builds the index
*/
void buildIndex() CV_OVERRIDE
void buildIndex()
{
if (branching_<2) {
throw FLANNException("Branching factor must be at least 2");
@ -480,13 +400,13 @@ public:
}
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return FLANN_INDEX_HIERARCHICAL;
}
void saveIndex(FILE* stream) CV_OVERRIDE
void saveIndex(FILE* stream)
{
save_value(stream, branching_);
save_value(stream, trees_);
@ -501,7 +421,7 @@ public:
}
void loadIndex(FILE* stream) CV_OVERRIDE
void loadIndex(FILE* stream)
{
free_elements();
@ -544,7 +464,7 @@ public:
* vec = the vector for which to search the nearest neighbors
* searchParams = parameters that influence the search algorithm (checks)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
{
int maxChecks = get_param(searchParams,"checks",32);
@ -569,7 +489,7 @@ public:
}
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return params;
}

View File

@ -120,29 +120,24 @@ public:
/**
* Builds the index
*/
void buildIndex() CV_OVERRIDE
void buildIndex()
{
/* Construct the randomized trees. */
for (int i = 0; i < trees_; i++) {
/* Randomize the order of vectors to allow for unbiased sampling. */
#ifndef OPENCV_FLANN_USE_STD_RAND
cv::randShuffle(vind_);
#else
std::random_shuffle(vind_.begin(), vind_.end());
#endif
tree_roots_[i] = divideTree(&vind_[0], int(size_) );
}
}
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return FLANN_INDEX_KDTREE;
}
void saveIndex(FILE* stream) CV_OVERRIDE
void saveIndex(FILE* stream)
{
save_value(stream, trees_);
for (int i=0; i<trees_; ++i) {
@ -152,7 +147,7 @@ public:
void loadIndex(FILE* stream) CV_OVERRIDE
void loadIndex(FILE* stream)
{
load_value(stream, trees_);
if (tree_roots_!=NULL) {
@ -170,7 +165,7 @@ public:
/**
* Returns size of index.
*/
size_t size() const CV_OVERRIDE
size_t size() const
{
return size_;
}
@ -178,7 +173,7 @@ public:
/**
* Returns the length of an index feature.
*/
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return veclen_;
}
@ -187,7 +182,7 @@ public:
* Computes the inde memory usage
* Returns: memory used by the index
*/
int usedMemory() const CV_OVERRIDE
int usedMemory() const
{
return int(pool_.usedMemory+pool_.wastedMemory+dataset_.rows*sizeof(int)); // pool memory and vind array memory
}
@ -201,7 +196,7 @@ public:
* vec = the vector for which to search the nearest neighbors
* maxCheck = the maximum number of restarts (in a best-bin-first manner)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
{
int maxChecks = get_param(searchParams,"checks", 32);
float epsError = 1+get_param(searchParams,"eps",0.0f);
@ -214,7 +209,7 @@ public:
}
}
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return index_params_;
}

View File

@ -87,7 +87,6 @@ public:
{
size_ = dataset_.rows;
dim_ = dataset_.cols;
root_node_ = 0;
int dim_param = get_param(params,"dim",-1);
if (dim_param>0) dim_ = dim_param;
leaf_max_size_ = get_param(params,"leaf_max_size",10);
@ -114,7 +113,7 @@ public:
/**
* Builds the index
*/
void buildIndex() CV_OVERRIDE
void buildIndex()
{
computeBoundingBox(root_bbox_);
root_node_ = divideTree(0, (int)size_, root_bbox_ ); // construct the tree
@ -133,13 +132,13 @@ public:
}
}
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return FLANN_INDEX_KDTREE_SINGLE;
}
void saveIndex(FILE* stream) CV_OVERRIDE
void saveIndex(FILE* stream)
{
save_value(stream, size_);
save_value(stream, dim_);
@ -154,7 +153,7 @@ public:
}
void loadIndex(FILE* stream) CV_OVERRIDE
void loadIndex(FILE* stream)
{
load_value(stream, size_);
load_value(stream, dim_);
@ -179,7 +178,7 @@ public:
/**
* Returns size of index.
*/
size_t size() const CV_OVERRIDE
size_t size() const
{
return size_;
}
@ -187,7 +186,7 @@ public:
/**
* Returns the length of an index feature.
*/
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return dim_;
}
@ -196,7 +195,7 @@ public:
* Computes the inde memory usage
* Returns: memory used by the index
*/
int usedMemory() const CV_OVERRIDE
int usedMemory() const
{
return (int)(pool_.usedMemory+pool_.wastedMemory+dataset_.rows*sizeof(int)); // pool memory and vind array memory
}
@ -210,7 +209,7 @@ public:
* \param[in] knn Number of nearest neighbors to return
* \param[in] params Search parameters
*/
void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params) CV_OVERRIDE
void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params)
{
assert(queries.cols == veclen());
assert(indices.rows >= queries.rows);
@ -225,7 +224,7 @@ public:
}
}
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return index_params_;
}
@ -239,7 +238,7 @@ public:
* vec = the vector for which to search the nearest neighbors
* maxCheck = the maximum number of restarts (in a best-bin-first manner)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
{
float epsError = 1+get_param(searchParams,"eps",0.0f);

View File

@ -32,6 +32,7 @@
#define OPENCV_FLANN_KMEANS_INDEX_H_
#include <algorithm>
#include <string>
#include <map>
#include <cassert>
#include <limits>
@ -266,61 +267,11 @@ public:
public:
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return FLANN_INDEX_KMEANS;
}
class KMeansDistanceComputer : public cv::ParallelLoopBody
{
public:
KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
const int _branching, const int* _indices, const Matrix<double>& _dcenters, const size_t _veclen,
std::vector<int> &_new_centroids, std::vector<DistanceType> &_sq_dists)
: distance(_distance)
, dataset(_dataset)
, branching(_branching)
, indices(_indices)
, dcenters(_dcenters)
, veclen(_veclen)
, new_centroids(_new_centroids)
, sq_dists(_sq_dists)
{
}
void operator()(const cv::Range& range) const CV_OVERRIDE
{
const int begin = range.start;
const int end = range.end;
for( int i = begin; i<end; ++i)
{
DistanceType sq_dist(distance(dataset[indices[i]], dcenters[0], veclen));
int new_centroid(0);
for (int j=1; j<branching; ++j) {
DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
if (sq_dist>new_sq_dist) {
new_centroid = j;
sq_dist = new_sq_dist;
}
}
sq_dists[i] = sq_dist;
new_centroids[i] = new_centroid;
}
}
private:
Distance distance;
const Matrix<ElementType>& dataset;
const int branching;
const int* indices;
const Matrix<double>& dcenters;
const size_t veclen;
std::vector<int> &new_centroids;
std::vector<DistanceType> &sq_dists;
KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
};
/**
* Index constructor
*
@ -383,7 +334,7 @@ public:
/**
* Returns size of index.
*/
size_t size() const CV_OVERRIDE
size_t size() const
{
return size_;
}
@ -391,7 +342,7 @@ public:
/**
* Returns the length of an index feature.
*/
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return veclen_;
}
@ -406,7 +357,7 @@ public:
* Computes the inde memory usage
* Returns: memory used by the index
*/
int usedMemory() const CV_OVERRIDE
int usedMemory() const
{
return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
}
@ -414,7 +365,7 @@ public:
/**
* Builds the index
*/
void buildIndex() CV_OVERRIDE
void buildIndex()
{
if (branching_<2) {
throw FLANNException("Branching factor must be at least 2");
@ -426,14 +377,12 @@ public:
}
root_ = pool_.allocate<KMeansNode>();
std::memset(root_, 0, sizeof(KMeansNode));
computeNodeStatistics(root_, indices_, (int)size_);
computeClustering(root_, indices_, (int)size_, branching_,0);
}
void saveIndex(FILE* stream) CV_OVERRIDE
void saveIndex(FILE* stream)
{
save_value(stream, branching_);
save_value(stream, iterations_);
@ -445,7 +394,7 @@ public:
}
void loadIndex(FILE* stream) CV_OVERRIDE
void loadIndex(FILE* stream)
{
load_value(stream, branching_);
load_value(stream, iterations_);
@ -480,7 +429,7 @@ public:
* vec = the vector for which to search the nearest neighbors
* searchParams = parameters that influence the search algorithm (checks, cb_index)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
{
int maxChecks = get_param(searchParams,"checks",32);
@ -539,7 +488,7 @@ public:
return clusterCount;
}
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return index_params_;
}
@ -710,8 +659,7 @@ private:
return;
}
cv::AutoBuffer<int> centers_idx_buf(branching);
int* centers_idx = centers_idx_buf.data();
int* centers_idx = new int[branching];
int centers_length;
(this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
@ -719,30 +667,29 @@ private:
node->indices = indices;
std::sort(node->indices,node->indices+indices_length);
node->childs = NULL;
delete [] centers_idx;
return;
}
cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
Matrix<double> dcenters(dcenters_buf.data(), branching, veclen_);
Matrix<double> dcenters(new double[branching*veclen_],branching,veclen_);
for (int i=0; i<centers_length; ++i) {
ElementType* vec = dataset_[centers_idx[i]];
for (size_t k=0; k<veclen_; ++k) {
dcenters[i][k] = double(vec[k]);
}
}
delete[] centers_idx;
std::vector<DistanceType> radiuses(branching);
cv::AutoBuffer<int> count_buf(branching);
int* count = count_buf.data();
int* count = new int[branching];
for (int i=0; i<branching; ++i) {
radiuses[i] = 0;
count[i] = 0;
}
// assign points to clusters
cv::AutoBuffer<int> belongs_to_buf(indices_length);
int* belongs_to = belongs_to_buf.data();
int* belongs_to = new int[indices_length];
for (int i=0; i<indices_length; ++i) {
DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[0], veclen_);
@ -785,23 +732,25 @@ private:
}
}
std::vector<int> new_centroids(indices_length);
std::vector<DistanceType> sq_dists(indices_length);
// reassign points to clusters
KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
parallel_for_(cv::Range(0, (int)indices_length), invoker);
for (int i=0; i < (int)indices_length; ++i) {
DistanceType sq_dist(sq_dists[i]);
int new_centroid(new_centroids[i]);
if (sq_dist > radiuses[new_centroid]) {
for (int i=0; i<indices_length; ++i) {
DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[0], veclen_);
int new_centroid = 0;
for (int j=1; j<branching; ++j) {
DistanceType new_sq_dist = distance_(dataset_[indices[i]], dcenters[j], veclen_);
if (sq_dist>new_sq_dist) {
new_centroid = j;
sq_dist = new_sq_dist;
}
}
if (sq_dist>radiuses[new_centroid]) {
radiuses[new_centroid] = sq_dist;
}
if (new_centroid != belongs_to[i]) {
count[belongs_to[i]]--;
count[new_centroid]++;
belongs_to[i] = new_centroid;
converged = false;
}
}
@ -867,16 +816,19 @@ private:
variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);
node->childs[c] = pool_.allocate<KMeansNode>();
std::memset(node->childs[c], 0, sizeof(KMeansNode));
node->childs[c]->radius = radiuses[c];
node->childs[c]->pivot = centers[c];
node->childs[c]->variance = variance;
node->childs[c]->mean_radius = mean_radius;
node->childs[c]->indices = NULL;
computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
start=end;
}
delete[] dcenters.data;
delete[] centers;
delete[] count;
delete[] belongs_to;
}
@ -1054,7 +1006,7 @@ private:
/**
* Helper function the descends in the hierarchical k-means tree by splitting those clusters that minimize
* Helper function the descends in the hierarchical k-means tree by spliting those clusters that minimize
* the overall variance of the clustering.
* Params:
* root = root node

View File

@ -63,47 +63,47 @@ public:
LinearIndex(const LinearIndex&);
LinearIndex& operator=(const LinearIndex&);
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return FLANN_INDEX_LINEAR;
}
size_t size() const CV_OVERRIDE
size_t size() const
{
return dataset_.rows;
}
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return dataset_.cols;
}
int usedMemory() const CV_OVERRIDE
int usedMemory() const
{
return 0;
}
void buildIndex() CV_OVERRIDE
void buildIndex()
{
/* nothing to do here for linear search */
}
void saveIndex(FILE*) CV_OVERRIDE
void saveIndex(FILE*)
{
/* nothing to do here for linear search */
}
void loadIndex(FILE*) CV_OVERRIDE
void loadIndex(FILE*)
{
/* nothing to do here for linear search */
index_params_["algorithm"] = getType();
}
void findNeighbors(ResultSet<DistanceType>& resultSet, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& resultSet, const ElementType* vec, const SearchParams& /*searchParams*/)
{
ElementType* data = dataset_.data;
for (size_t i = 0; i < dataset_.rows; ++i, data += dataset_.cols) {
@ -112,7 +112,7 @@ public:
}
}
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return index_params_;
}

View File

@ -63,12 +63,7 @@ class Logger
stream = stdout;
}
else {
#ifdef _MSC_VER
if (fopen_s(&stream, name, "w") != 0)
stream = NULL;
#else
stream = fopen(name,"w");
#endif
if (stream == NULL) {
stream = stdout;
}

View File

@ -107,25 +107,37 @@ public:
/**
* Builds the index
*/
void buildIndex() CV_OVERRIDE
void buildIndex()
{
std::vector<size_t> indices(feature_size_ * CHAR_BIT);
tables_.resize(table_number_);
for (unsigned int i = 0; i < table_number_; ++i) {
//re-initialize the random indices table that the LshTable will use to pick its sub-dimensions
if( (indices.size() == feature_size_ * CHAR_BIT) || (indices.size() < key_size_) )
{
indices.resize( feature_size_ * CHAR_BIT );
for (size_t j = 0; j < feature_size_ * CHAR_BIT; ++j)
indices[j] = j;
std::random_shuffle(indices.begin(), indices.end());
}
lsh::LshTable<ElementType>& table = tables_[i];
table = lsh::LshTable<ElementType>(feature_size_, key_size_);
table = lsh::LshTable<ElementType>(feature_size_, key_size_, indices);
// Add the features to the table
table.add(dataset_);
}
}
flann_algorithm_t getType() const CV_OVERRIDE
flann_algorithm_t getType() const
{
return FLANN_INDEX_LSH;
}
void saveIndex(FILE* stream) CV_OVERRIDE
void saveIndex(FILE* stream)
{
save_value(stream,table_number_);
save_value(stream,key_size_);
@ -133,7 +145,7 @@ public:
save_value(stream, dataset_);
}
void loadIndex(FILE* stream) CV_OVERRIDE
void loadIndex(FILE* stream)
{
load_value(stream, table_number_);
load_value(stream, key_size_);
@ -151,7 +163,7 @@ public:
/**
* Returns size of index.
*/
size_t size() const CV_OVERRIDE
size_t size() const
{
return dataset_.rows;
}
@ -159,7 +171,7 @@ public:
/**
* Returns the length of an index feature.
*/
size_t veclen() const CV_OVERRIDE
size_t veclen() const
{
return feature_size_;
}
@ -168,13 +180,13 @@ public:
* Computes the index memory usage
* Returns: memory used by the index
*/
int usedMemory() const CV_OVERRIDE
int usedMemory() const
{
return (int)(dataset_.rows * sizeof(int));
}
IndexParams getParameters() const CV_OVERRIDE
IndexParams getParameters() const
{
return index_params_;
}
@ -187,7 +199,7 @@ public:
* \param[in] knn Number of nearest neighbors to return
* \param[in] params Search parameters
*/
virtual void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params) CV_OVERRIDE
virtual void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params)
{
assert(queries.cols == veclen());
assert(indices.rows >= queries.rows);
@ -217,7 +229,7 @@ public:
* vec = the vector for which to search the nearest neighbors
* maxCheck = the maximum number of restarts (in a best-bin-first manner)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& /*searchParams*/)
{
getNeighbors(vec, result);
}

View File

@ -146,9 +146,6 @@ public:
*/
LshTable()
{
key_size_ = 0;
feature_size_ = 0;
speed_level_ = kArray;
}
/** Default constructor
@ -156,10 +153,8 @@ public:
* @param feature_size is the size of the feature (considered as a ElementType[])
* @param key_size is the number of bits that are turned on in the feature
*/
LshTable(unsigned int feature_size, unsigned int key_size)
LshTable(unsigned int /*feature_size*/, unsigned int /*key_size*/, std::vector<size_t> & /*indices*/)
{
feature_size_ = feature_size;
CV_UNUSED(key_size);
std::cerr << "LSH is not implemented for that type" << std::endl;
assert(0);
}
@ -268,10 +263,12 @@ private:
{
const size_t key_size_lower_bound = 1;
//a value (size_t(1) << key_size) must fit the size_t type so key_size has to be strictly less than size of size_t
const size_t key_size_upper_bound = (std::min)(sizeof(BucketKey) * CHAR_BIT + 1, sizeof(size_t) * CHAR_BIT);
const size_t key_size_upper_bound = std::min(sizeof(BucketKey) * CHAR_BIT + 1, sizeof(size_t) * CHAR_BIT);
if (key_size < key_size_lower_bound || key_size >= key_size_upper_bound)
{
CV_Error(cv::Error::StsBadArg, cv::format("Invalid key_size (=%d). Valid values for your system are %d <= key_size < %d.", (int)key_size, (int)key_size_lower_bound, (int)key_size_upper_bound));
std::stringstream errorMessage;
errorMessage << "Invalid key_size (=" << key_size << "). Valid values for your system are " << key_size_lower_bound << " <= key_size < " << key_size_upper_bound << ".";
CV_Error(CV_StsBadArg, errorMessage.str());
}
speed_level_ = kHash;
@ -333,8 +330,6 @@ private:
*/
unsigned int key_size_;
unsigned int feature_size_;
// Members only used for the unsigned char specialization
/** The mask to apply to a feature to get the hash key
* Only used in the unsigned char case
@ -346,25 +341,20 @@ private:
// Specialization for unsigned char
template<>
inline LshTable<unsigned char>::LshTable(unsigned int feature_size, unsigned int subsignature_size)
inline LshTable<unsigned char>::LshTable( unsigned int feature_size,
unsigned int subsignature_size,
std::vector<size_t> & indices )
{
feature_size_ = feature_size;
initialize(subsignature_size);
// Allocate the mask
mask_ = std::vector<size_t>((feature_size * sizeof(char) + sizeof(size_t) - 1) / sizeof(size_t), 0);
// A bit brutal but fast to code
std::vector<int> indices(feature_size * CHAR_BIT);
for (size_t i = 0; i < feature_size * CHAR_BIT; ++i) indices[i] = (int)i;
#ifndef OPENCV_FLANN_USE_STD_RAND
cv::randShuffle(indices);
#else
std::random_shuffle(indices.begin(), indices.end());
#endif
mask_ = std::vector<size_t>((size_t)ceil((float)(feature_size * sizeof(char)) / (float)sizeof(size_t)), 0);
// Generate a random set of order of subsignature_size_ bits
for (unsigned int i = 0; i < key_size_; ++i) {
size_t index = indices[i];
//Ensure the Nth bit will be selected only once among the different LshTables
//to avoid having two different tables with signatures sharing many dimensions/many bits
size_t index = indices[0];
indices.erase( indices.begin() );
// Set that bit in the mask
size_t divisor = CHAR_BIT * sizeof(size_t);
@ -396,7 +386,6 @@ inline size_t LshTable<unsigned char>::getKey(const unsigned char* feature) cons
{
// no need to check if T is dividable by sizeof(size_t) like in the Hamming
// distance computation as we have a mask
// FIXIT: This is bad assumption, because we reading tail bytes after of the allocated features buffer
const size_t* feature_block_ptr = reinterpret_cast<const size_t*> ((const void*)feature);
// Figure out the subsignature of the feature
@ -405,20 +394,10 @@ inline size_t LshTable<unsigned char>::getKey(const unsigned char* feature) cons
size_t subsignature = 0;
size_t bit_index = 1;
for (unsigned i = 0; i < feature_size_; i += sizeof(size_t)) {
for (std::vector<size_t>::const_iterator pmask_block = mask_.begin(); pmask_block != mask_.end(); ++pmask_block) {
// get the mask and signature blocks
size_t feature_block;
if (i <= feature_size_ - sizeof(size_t))
{
feature_block = *feature_block_ptr;
}
else
{
size_t tmp = 0;
memcpy(&tmp, feature_block_ptr, feature_size_ - i); // preserve bytes order
feature_block = tmp;
}
size_t mask_block = mask_[i / sizeof(size_t)];
size_t feature_block = *feature_block_ptr;
size_t mask_block = *pmask_block;
while (mask_block) {
// Get the lowest set bit in the mask block
size_t lowest_bit = mask_block & (-(ptrdiff_t)mask_block);

View File

@ -66,7 +66,7 @@ public:
/**
* Convenience function for deallocating the storage data.
*/
CV_DEPRECATED void free()
FLANN_DEPRECATED void free()
{
fprintf(stderr, "The cvflann::Matrix<T>::free() method is deprecated "
"and it does not do any memory deallocation any more. You are"

View File

@ -40,10 +40,12 @@
//
//M*/
#ifndef OPENCV_MINIFLANN_HPP
#define OPENCV_MINIFLANN_HPP
#ifndef _OPENCV_MINIFLANN_HPP_
#define _OPENCV_MINIFLANN_HPP_
#include "opencv2/core.hpp"
#ifdef __cplusplus
#include "opencv2/core/core.hpp"
#include "opencv2/flann/defines.h"
namespace cv
@ -57,27 +59,23 @@ struct CV_EXPORTS IndexParams
IndexParams();
~IndexParams();
String getString(const String& key, const String& defaultVal=String()) const;
int getInt(const String& key, int defaultVal=-1) const;
double getDouble(const String& key, double defaultVal=-1) const;
std::string getString(const std::string& key, const std::string& defaultVal=std::string()) const;
int getInt(const std::string& key, int defaultVal=-1) const;
double getDouble(const std::string& key, double defaultVal=-1) const;
void setString(const String& key, const String& value);
void setInt(const String& key, int value);
void setDouble(const String& key, double value);
void setFloat(const String& key, float value);
void setBool(const String& key, bool value);
void setString(const std::string& key, const std::string& value);
void setInt(const std::string& key, int value);
void setDouble(const std::string& key, double value);
void setFloat(const std::string& key, float value);
void setBool(const std::string& key, bool value);
void setAlgorithm(int value);
void getAll(std::vector<String>& names,
void getAll(std::vector<std::string>& names,
std::vector<int>& types,
std::vector<String>& strValues,
std::vector<std::string>& strValues,
std::vector<double>& numValues) const;
void* params;
private:
IndexParams(const IndexParams &); // copy disabled
IndexParams& operator=(const IndexParams &); // assign disabled
};
struct CV_EXPORTS KDTreeIndexParams : public IndexParams
@ -93,13 +91,13 @@ struct CV_EXPORTS LinearIndexParams : public IndexParams
struct CV_EXPORTS CompositeIndexParams : public IndexParams
{
CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11,
cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f );
cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2 );
};
struct CV_EXPORTS AutotunedIndexParams : public IndexParams
{
AutotunedIndexParams(float target_precision = 0.8f, float build_weight = 0.01f,
float memory_weight = 0, float sample_fraction = 0.1f);
AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01,
float memory_weight = 0, float sample_fraction = 0.1);
};
struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams
@ -111,7 +109,7 @@ struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams
struct CV_EXPORTS KMeansIndexParams : public IndexParams
{
KMeansIndexParams(int branching = 32, int iterations = 11,
cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f );
cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2 );
};
struct CV_EXPORTS LshIndexParams : public IndexParams
@ -121,7 +119,7 @@ struct CV_EXPORTS LshIndexParams : public IndexParams
struct CV_EXPORTS SavedIndexParams : public IndexParams
{
SavedIndexParams(const String& filename);
SavedIndexParams(const std::string& filename);
};
struct CV_EXPORTS SearchParams : public IndexParams
@ -144,8 +142,8 @@ public:
OutputArray dists, double radius, int maxResults,
const SearchParams& params=SearchParams());
CV_WRAP virtual void save(const String& filename) const;
CV_WRAP virtual bool load(InputArray features, const String& filename);
CV_WRAP virtual void save(const std::string& filename) const;
CV_WRAP virtual bool load(InputArray features, const std::string& filename);
CV_WRAP virtual void release();
CV_WRAP cvflann::flann_distance_t getDistance() const;
CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const;
@ -159,4 +157,6 @@ protected:
} } // namespace cv::flann
#endif // __cplusplus
#endif

View File

@ -31,6 +31,8 @@
#ifndef OPENCV_FLANN_NNINDEX_H
#define OPENCV_FLANN_NNINDEX_H
#include <string>
#include "general.h"
#include "matrix.h"
#include "result_set.h"

View File

@ -39,7 +39,7 @@
namespace cvflann
{
typedef std::map<cv::String, any> IndexParams;
typedef std::map<std::string, any> IndexParams;
struct SearchParams : public IndexParams
{
@ -56,7 +56,7 @@ struct SearchParams : public IndexParams
template<typename T>
T get_param(const IndexParams& params, cv::String name, const T& default_value)
T get_param(const IndexParams& params, std::string name, const T& default_value)
{
IndexParams::const_iterator it = params.find(name);
if (it != params.end()) {
@ -68,14 +68,14 @@ T get_param(const IndexParams& params, cv::String name, const T& default_value)
}
template<typename T>
T get_param(const IndexParams& params, cv::String name)
T get_param(const IndexParams& params, std::string name)
{
IndexParams::const_iterator it = params.find(name);
if (it != params.end()) {
return it->second.cast<T>();
}
else {
throw FLANNException(cv::String("Missing parameter '")+name+cv::String("' in the parameters given"));
throw FLANNException(std::string("Missing parameter '")+name+std::string("' in the parameters given"));
}
}

View File

@ -40,31 +40,13 @@
namespace cvflann
{
inline int rand()
{
#ifndef OPENCV_FLANN_USE_STD_RAND
# if INT_MAX == RAND_MAX
int v = cv::theRNG().next() & INT_MAX;
# else
int v = cv::theRNG().uniform(0, RAND_MAX + 1);
# endif
#else
int v = std::rand();
#endif // OPENCV_FLANN_USE_STD_RAND
return v;
}
/**
* Seeds the random number generator
* @param seed Random seed
*/
inline void seed_random(unsigned int seed)
{
#ifndef OPENCV_FLANN_USE_STD_RAND
cv::theRNG() = cv::RNG(seed);
#else
std::srand(seed);
#endif
srand(seed);
}
/*
@ -78,7 +60,7 @@ inline void seed_random(unsigned int seed)
*/
inline double rand_double(double high = 1.0, double low = 0)
{
return low + ((high-low) * (rand() / (RAND_MAX + 1.0)));
return low + ((high-low) * (std::rand() / (RAND_MAX + 1.0)));
}
/**
@ -89,7 +71,7 @@ inline double rand_double(double high = 1.0, double low = 0)
*/
inline int rand_int(int high = RAND_MAX, int low = 0)
{
return low + (int) ( double(high-low) * (rand() / (RAND_MAX + 1.0)));
return low + (int) ( double(high-low) * (std::rand() / (RAND_MAX + 1.0)));
}
/**
@ -125,11 +107,7 @@ public:
for (int i = 0; i < size_; ++i) vals_[i] = i;
// shuffle the elements in the array
#ifndef OPENCV_FLANN_USE_STD_RAND
cv::randShuffle(vals_);
#else
std::random_shuffle(vals_.begin(), vals_.end());
#endif
counter_ = 0;
}

View File

@ -109,13 +109,13 @@ public:
return count;
}
bool full() const CV_OVERRIDE
bool full() const
{
return count == capacity;
}
void addPoint(DistanceType dist, int index) CV_OVERRIDE
void addPoint(DistanceType dist, int index)
{
if (dist >= worst_distance_) return;
int i;
@ -139,7 +139,7 @@ public:
worst_distance_ = dists[capacity-1];
}
DistanceType worstDist() const CV_OVERRIDE
DistanceType worstDist() const
{
return worst_distance_;
}
@ -176,13 +176,13 @@ public:
return count;
}
bool full() const CV_OVERRIDE
bool full() const
{
return count == capacity;
}
void addPoint(DistanceType dist, int index) CV_OVERRIDE
void addPoint(DistanceType dist, int index)
{
if (dist >= worst_distance_) return;
int i;
@ -215,7 +215,7 @@ public:
worst_distance_ = dists[capacity-1];
}
DistanceType worstDist() const CV_OVERRIDE
DistanceType worstDist() const
{
return worst_distance_;
}
@ -303,14 +303,14 @@ public:
/** Default cosntructor */
UniqueResultSet() :
is_full_(false), worst_distance_(std::numeric_limits<DistanceType>::max())
worst_distance_(std::numeric_limits<DistanceType>::max())
{
}
/** Check the status of the set
* @return true if we have k NN
*/
inline bool full() const CV_OVERRIDE
inline bool full() const
{
return is_full_;
}
@ -365,7 +365,7 @@ public:
* If we don't have enough neighbors, it returns the max possible value
* @return
*/
inline DistanceType worstDist() const CV_OVERRIDE
inline DistanceType worstDist() const
{
return worst_distance_;
}
@ -402,7 +402,7 @@ public:
* @param dist distance for that neighbor
* @param index index of that neighbor
*/
inline void addPoint(DistanceType dist, int index) CV_OVERRIDE
inline void addPoint(DistanceType dist, int index)
{
// Don't do anything if we are worse than the worst
if (dist >= worst_distance_) return;
@ -422,7 +422,7 @@ public:
/** Remove all elements in the set
*/
void clear() CV_OVERRIDE
void clear()
{
dist_indices_.clear();
worst_distance_ = std::numeric_limits<DistanceType>::max();
@ -449,7 +449,7 @@ class RadiusUniqueResultSet : public UniqueResultSet<DistanceType>
{
public:
/** Constructor
* @param radius the maximum distance of a neighbor
* @param capacity the number of neighbors to store at max
*/
RadiusUniqueResultSet(DistanceType radius) :
radius_(radius)
@ -461,14 +461,14 @@ public:
* @param dist distance for that neighbor
* @param index index of that neighbor
*/
void addPoint(DistanceType dist, int index) CV_OVERRIDE
void addPoint(DistanceType dist, int index)
{
if (dist <= radius_) dist_indices_.insert(DistIndex(dist, index));
}
/** Remove all elements in the set
*/
inline void clear() CV_OVERRIDE
inline void clear()
{
dist_indices_.clear();
}
@ -477,7 +477,7 @@ public:
/** Check the status of the set
* @return alwys false
*/
inline bool full() const CV_OVERRIDE
inline bool full() const
{
return true;
}
@ -486,7 +486,7 @@ public:
* If we don't have enough neighbors, it returns the max possible value
* @return
*/
inline DistanceType worstDist() const CV_OVERRIDE
inline DistanceType worstDist() const
{
return radius_;
}
@ -509,7 +509,6 @@ class KNNRadiusUniqueResultSet : public KNNUniqueResultSet<DistanceType>
public:
/** Constructor
* @param capacity the number of neighbors to store at max
* @param radius the maximum distance of a neighbor
*/
KNNRadiusUniqueResultSet(unsigned int capacity, DistanceType radius)
{

View File

@ -32,8 +32,7 @@
#define OPENCV_FLANN_TIMER_H
#include <time.h>
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
namespace cvflann
{
@ -45,7 +44,7 @@ namespace cvflann
*/
class StartStopTimer
{
int64 startTime;
clock_t startTime;
public:
/**
@ -67,7 +66,7 @@ public:
*/
void start()
{
startTime = cv::getTickCount();
startTime = clock();
}
/**
@ -75,8 +74,8 @@ public:
*/
void stop()
{
int64 stopTime = cv::getTickCount();
value += ( (double)stopTime - startTime) / cv::getTickFrequency();
clock_t stopTime = clock();
value += ( (double)stopTime - startTime) / CLOCKS_PER_SEC;
}
/**

View File

@ -12,7 +12,6 @@
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
@ -41,8 +40,216 @@
//
//M*/
#ifdef __OPENCV_BUILD
#error this is a compatibility header which should not be used inside the OpenCV library
#ifndef __OPENCV_HIGHGUI_HPP__
#define __OPENCV_HIGHGUI_HPP__
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui_c.h"
#ifdef __cplusplus
struct CvCapture;
struct CvVideoWriter;
namespace cv
{
enum {
// Flags for namedWindow
WINDOW_NORMAL = CV_WINDOW_NORMAL, // the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size
WINDOW_AUTOSIZE = CV_WINDOW_AUTOSIZE, // the user cannot resize the window, the size is constrainted by the image displayed
WINDOW_OPENGL = CV_WINDOW_OPENGL, // window with opengl support
// Flags for set / getWindowProperty
WND_PROP_FULLSCREEN = CV_WND_PROP_FULLSCREEN, // fullscreen property
WND_PROP_AUTOSIZE = CV_WND_PROP_AUTOSIZE, // autosize property
WND_PROP_ASPECT_RATIO = CV_WND_PROP_ASPECTRATIO, // window's aspect ration
WND_PROP_OPENGL = CV_WND_PROP_OPENGL // opengl support
};
CV_EXPORTS_W void namedWindow(const string& winname, int flags = WINDOW_AUTOSIZE);
CV_EXPORTS_W void destroyWindow(const string& winname);
CV_EXPORTS_W void destroyAllWindows();
CV_EXPORTS_W int startWindowThread();
CV_EXPORTS_W int waitKey(int delay = 0);
CV_EXPORTS_W void imshow(const string& winname, InputArray mat);
CV_EXPORTS_W void resizeWindow(const string& winname, int width, int height);
CV_EXPORTS_W void moveWindow(const string& winname, int x, int y);
CV_EXPORTS_W void setWindowProperty(const string& winname, int prop_id, double prop_value);//YV
CV_EXPORTS_W double getWindowProperty(const string& winname, int prop_id);//YV
enum
{
EVENT_MOUSEMOVE =0,
EVENT_LBUTTONDOWN =1,
EVENT_RBUTTONDOWN =2,
EVENT_MBUTTONDOWN =3,
EVENT_LBUTTONUP =4,
EVENT_RBUTTONUP =5,
EVENT_MBUTTONUP =6,
EVENT_LBUTTONDBLCLK =7,
EVENT_RBUTTONDBLCLK =8,
EVENT_MBUTTONDBLCLK =9
};
enum
{
EVENT_FLAG_LBUTTON =1,
EVENT_FLAG_RBUTTON =2,
EVENT_FLAG_MBUTTON =4,
EVENT_FLAG_CTRLKEY =8,
EVENT_FLAG_SHIFTKEY =16,
EVENT_FLAG_ALTKEY =32
};
typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata);
//! assigns callback for mouse events
CV_EXPORTS void setMouseCallback(const string& winname, MouseCallback onMouse, void* userdata = 0);
typedef void (CV_CDECL *TrackbarCallback)(int pos, void* userdata);
CV_EXPORTS int createTrackbar(const string& trackbarname, const string& winname,
int* value, int count,
TrackbarCallback onChange = 0,
void* userdata = 0);
CV_EXPORTS_W int getTrackbarPos(const string& trackbarname, const string& winname);
CV_EXPORTS_W void setTrackbarPos(const string& trackbarname, const string& winname, int pos);
// OpenGL support
typedef void (*OpenGlDrawCallback)(void* userdata);
CV_EXPORTS void setOpenGlDrawCallback(const string& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0);
CV_EXPORTS void setOpenGlContext(const string& winname);
CV_EXPORTS void updateWindow(const string& winname);
// < Deperecated
CV_EXPORTS void pointCloudShow(const string& winname, const GlCamera& camera, const GlArrays& arr);
CV_EXPORTS void pointCloudShow(const string& winname, const GlCamera& camera, InputArray points, InputArray colors = noArray());
// >
//Only for Qt
CV_EXPORTS CvFont fontQt(const string& nameFont, int pointSize=-1,
Scalar color=Scalar::all(0), int weight=CV_FONT_NORMAL,
int style=CV_STYLE_NORMAL, int spacing=0);
CV_EXPORTS void addText( const Mat& img, const string& text, Point org, CvFont font);
CV_EXPORTS void displayOverlay(const string& winname, const string& text, int delayms CV_DEFAULT(0));
CV_EXPORTS void displayStatusBar(const string& winname, const string& text, int delayms CV_DEFAULT(0));
CV_EXPORTS void saveWindowParameters(const string& windowName);
CV_EXPORTS void loadWindowParameters(const string& windowName);
CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]);
CV_EXPORTS void stopLoop();
typedef void (CV_CDECL *ButtonCallback)(int state, void* userdata);
CV_EXPORTS int createButton( const string& bar_name, ButtonCallback on_change,
void* userdata=NULL, int type=CV_PUSH_BUTTON,
bool initial_button_state=0);
//-------------------------
enum
{
// 8bit, color or not
IMREAD_UNCHANGED =-1,
// 8bit, gray
IMREAD_GRAYSCALE =0,
// ?, color
IMREAD_COLOR =1,
// any depth, ?
IMREAD_ANYDEPTH =2,
// ?, any color
IMREAD_ANYCOLOR =4
};
enum
{
IMWRITE_JPEG_QUALITY =1,
IMWRITE_PNG_COMPRESSION =16,
IMWRITE_PNG_STRATEGY =17,
IMWRITE_PNG_BILEVEL =18,
IMWRITE_PNG_STRATEGY_DEFAULT =0,
IMWRITE_PNG_STRATEGY_FILTERED =1,
IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2,
IMWRITE_PNG_STRATEGY_RLE =3,
IMWRITE_PNG_STRATEGY_FIXED =4,
IMWRITE_PXM_BINARY =32
};
CV_EXPORTS_W Mat imread( const string& filename, int flags=1 );
CV_EXPORTS_W bool imwrite( const string& filename, InputArray img,
const vector<int>& params=vector<int>());
CV_EXPORTS_W Mat imdecode( InputArray buf, int flags );
CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst );
CV_EXPORTS_W bool imencode( const string& ext, InputArray img,
CV_OUT vector<uchar>& buf,
const vector<int>& params=vector<int>());
#ifndef CV_NO_VIDEO_CAPTURE_CPP_API
template<> void CV_EXPORTS Ptr<CvCapture>::delete_obj();
template<> void CV_EXPORTS Ptr<CvVideoWriter>::delete_obj();
class CV_EXPORTS_W VideoCapture
{
public:
CV_WRAP VideoCapture();
CV_WRAP VideoCapture(const string& filename);
CV_WRAP VideoCapture(int device);
virtual ~VideoCapture();
CV_WRAP virtual bool open(const string& filename);
CV_WRAP virtual bool open(int device);
CV_WRAP virtual bool isOpened() const;
CV_WRAP virtual void release();
CV_WRAP virtual bool grab();
CV_WRAP virtual bool retrieve(CV_OUT Mat& image, int channel=0);
virtual VideoCapture& operator >> (CV_OUT Mat& image);
CV_WRAP virtual bool read(CV_OUT Mat& image);
CV_WRAP virtual bool set(int propId, double value);
CV_WRAP virtual double get(int propId);
protected:
Ptr<CvCapture> cap;
};
class CV_EXPORTS_W VideoWriter
{
public:
CV_WRAP VideoWriter();
CV_WRAP VideoWriter(const string& filename, int fourcc, double fps,
Size frameSize, bool isColor=true);
virtual ~VideoWriter();
CV_WRAP virtual bool open(const string& filename, int fourcc, double fps,
Size frameSize, bool isColor=true);
CV_WRAP virtual bool isOpened() const;
CV_WRAP virtual void release();
virtual VideoWriter& operator << (const Mat& image);
CV_WRAP virtual void write(const Mat& image);
protected:
Ptr<CvVideoWriter> writer;
};
#endif
#include "opencv2/highgui.hpp"
}
#endif
#endif

View File

@ -39,26 +39,15 @@
//
//M*/
#ifndef OPENCV_HIGHGUI_H
#define OPENCV_HIGHGUI_H
#ifndef __OPENCV_HIGHGUI_H__
#define __OPENCV_HIGHGUI_H__
#include "opencv2/core/core_c.h"
#include "opencv2/imgproc/imgproc_c.h"
#ifdef HAVE_OPENCV_IMGCODECS
#include "opencv2/imgcodecs/imgcodecs_c.h"
#endif
#ifdef HAVE_OPENCV_VIDEOIO
#include "opencv2/videoio/videoio_c.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @addtogroup highgui_c
@{
*/
/****************************************************************************************\
* Basic GUI functions *
\****************************************************************************************/
@ -78,7 +67,7 @@ enum { CV_STYLE_NORMAL = 0,//QFont::StyleNormal,
};
/* ---------*/
//for color cvScalar(blue_component, green_component, red_component[, alpha_component])
//for color cvScalar(blue_component, green_component, red\_component[, alpha_component])
//and alpha= 0 <-> 0xFF (not transparent <-> transparent)
CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvScalar color CV_DEFAULT(cvScalarAll(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0));
@ -111,7 +100,6 @@ enum
CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property
CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property
CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support
CV_WND_PROP_VISIBLE = 4,
//These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty
CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size
@ -135,11 +123,6 @@ CVAPI(int) cvNamedWindow( const char* name, int flags CV_DEFAULT(CV_WINDOW_AUTOS
CVAPI(void) cvSetWindowProperty(const char* name, int prop_id, double prop_value);
CVAPI(double) cvGetWindowProperty(const char* name, int prop_id);
#ifdef __cplusplus // FIXIT remove in OpenCV 4.0
/* Get window image rectangle coordinates, width and height */
CVAPI(cv::Rect)cvGetWindowImageRect(const char* name);
#endif
/* display image within window (highgui windows remember their content) */
CVAPI(void) cvShowImage( const char* name, const CvArr* image );
@ -175,8 +158,6 @@ CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name
/* retrieve or set trackbar position */
CVAPI(int) cvGetTrackbarPos( const char* trackbar_name, const char* window_name );
CVAPI(void) cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos );
CVAPI(void) cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval);
CVAPI(void) cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval);
enum
{
@ -189,9 +170,7 @@ enum
CV_EVENT_MBUTTONUP =6,
CV_EVENT_LBUTTONDBLCLK =7,
CV_EVENT_RBUTTONDBLCLK =8,
CV_EVENT_MBUTTONDBLCLK =9,
CV_EVENT_MOUSEWHEEL =10,
CV_EVENT_MOUSEHWHEEL =11
CV_EVENT_MBUTTONDBLCLK =9
};
enum
@ -204,15 +183,70 @@ enum
CV_EVENT_FLAG_ALTKEY =32
};
#define CV_GET_WHEEL_DELTA(flags) ((short)((flags >> 16) & 0xffff)) // upper 16 bits
typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param);
/* assign callback for mouse events */
CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse,
void* param CV_DEFAULT(NULL));
enum
{
/* 8bit, color or not */
CV_LOAD_IMAGE_UNCHANGED =-1,
/* 8bit, gray */
CV_LOAD_IMAGE_GRAYSCALE =0,
/* ?, color */
CV_LOAD_IMAGE_COLOR =1,
/* any depth, ? */
CV_LOAD_IMAGE_ANYDEPTH =2,
/* ?, any color */
CV_LOAD_IMAGE_ANYCOLOR =4
};
/* load image from file
iscolor can be a combination of above flags where CV_LOAD_IMAGE_UNCHANGED
overrides the other flags
using CV_LOAD_IMAGE_ANYCOLOR alone is equivalent to CV_LOAD_IMAGE_UNCHANGED
unless CV_LOAD_IMAGE_ANYDEPTH is specified images are converted to 8bit
*/
CVAPI(IplImage*) cvLoadImage( const char* filename, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR));
CVAPI(CvMat*) cvLoadImageM( const char* filename, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR));
enum
{
CV_IMWRITE_JPEG_QUALITY =1,
CV_IMWRITE_PNG_COMPRESSION =16,
CV_IMWRITE_PNG_STRATEGY =17,
CV_IMWRITE_PNG_BILEVEL =18,
CV_IMWRITE_PNG_STRATEGY_DEFAULT =0,
CV_IMWRITE_PNG_STRATEGY_FILTERED =1,
CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2,
CV_IMWRITE_PNG_STRATEGY_RLE =3,
CV_IMWRITE_PNG_STRATEGY_FIXED =4,
CV_IMWRITE_PXM_BINARY =32
};
/* save image to file */
CVAPI(int) cvSaveImage( const char* filename, const CvArr* image,
const int* params CV_DEFAULT(0) );
/* decode image stored in the buffer */
CVAPI(IplImage*) cvDecodeImage( const CvMat* buf, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR));
CVAPI(CvMat*) cvDecodeImageM( const CvMat* buf, int iscolor CV_DEFAULT(CV_LOAD_IMAGE_COLOR));
/* encode image and store the result as a byte vector (single-row 8uC1 matrix) */
CVAPI(CvMat*) cvEncodeImage( const char* ext, const CvArr* image,
const int* params CV_DEFAULT(0) );
enum
{
CV_CVTIMG_FLIP =1,
CV_CVTIMG_SWAP_RB =2
};
/* utility function: convert one image to another with optional vertical flip */
CVAPI(void) cvConvertImage( const CvArr* src, CvArr* dst, int flags CV_DEFAULT(0));
/* wait for key event infinitely (delay<=0) or for "delay" milliseconds */
CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0));
@ -226,10 +260,363 @@ CVAPI(void) cvUpdateWindow(const char* window_name);
/****************************************************************************************\
* Working with Video Files and Cameras *
\****************************************************************************************/
/* "black box" capture structure */
typedef struct CvCapture CvCapture;
/* start capturing frames from video file */
CVAPI(CvCapture*) cvCreateFileCapture( const char* filename );
enum
{
CV_CAP_ANY =0, // autodetect
CV_CAP_MIL =100, // MIL proprietary drivers
CV_CAP_VFW =200, // platform native
CV_CAP_V4L =200,
CV_CAP_V4L2 =200,
CV_CAP_FIREWARE =300, // IEEE 1394 drivers
CV_CAP_FIREWIRE =300,
CV_CAP_IEEE1394 =300,
CV_CAP_DC1394 =300,
CV_CAP_CMU1394 =300,
CV_CAP_STEREO =400, // TYZX proprietary drivers
CV_CAP_TYZX =400,
CV_TYZX_LEFT =400,
CV_TYZX_RIGHT =401,
CV_TYZX_COLOR =402,
CV_TYZX_Z =403,
CV_CAP_QT =500, // QuickTime
CV_CAP_UNICAP =600, // Unicap drivers
CV_CAP_DSHOW =700, // DirectShow (via videoInput)
CV_CAP_MSMF =1400, // Microsoft Media Foundation (via videoInput)
CV_CAP_PVAPI =800, // PvAPI, Prosilica GigE SDK
CV_CAP_OPENNI =900, // OpenNI (for Kinect)
CV_CAP_OPENNI_ASUS =910, // OpenNI (for Asus Xtion)
CV_CAP_ANDROID =1000, // Android
CV_CAP_ANDROID_BACK =CV_CAP_ANDROID+99, // Android back camera
CV_CAP_ANDROID_FRONT =CV_CAP_ANDROID+98, // Android front camera
CV_CAP_XIAPI =1100, // XIMEA Camera API
CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API)
CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK
CV_CAP_INTELPERC = 1500 // Intel Perceptual Computing SDK
};
/* start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) */
CVAPI(CvCapture*) cvCreateCameraCapture( int index );
/* grab a frame, return 1 on success, 0 on fail.
this function is thought to be fast */
CVAPI(int) cvGrabFrame( CvCapture* capture );
/* get the frame grabbed with cvGrabFrame(..)
This function may apply some frame processing like
frame decompression, flipping etc.
!!!DO NOT RELEASE or MODIFY the retrieved frame!!! */
CVAPI(IplImage*) cvRetrieveFrame( CvCapture* capture, int streamIdx CV_DEFAULT(0) );
/* Just a combination of cvGrabFrame and cvRetrieveFrame
!!!DO NOT RELEASE or MODIFY the retrieved frame!!! */
CVAPI(IplImage*) cvQueryFrame( CvCapture* capture );
/* stop capturing/reading and free resources */
CVAPI(void) cvReleaseCapture( CvCapture** capture );
enum
{
// modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode)
// every feature can have only one mode turned on at a time
CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically)
CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user
CV_CAP_PROP_DC1394_MODE_AUTO = -2,
CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1,
CV_CAP_PROP_POS_MSEC =0,
CV_CAP_PROP_POS_FRAMES =1,
CV_CAP_PROP_POS_AVI_RATIO =2,
CV_CAP_PROP_FRAME_WIDTH =3,
CV_CAP_PROP_FRAME_HEIGHT =4,
CV_CAP_PROP_FPS =5,
CV_CAP_PROP_FOURCC =6,
CV_CAP_PROP_FRAME_COUNT =7,
CV_CAP_PROP_FORMAT =8,
CV_CAP_PROP_MODE =9,
CV_CAP_PROP_BRIGHTNESS =10,
CV_CAP_PROP_CONTRAST =11,
CV_CAP_PROP_SATURATION =12,
CV_CAP_PROP_HUE =13,
CV_CAP_PROP_GAIN =14,
CV_CAP_PROP_EXPOSURE =15,
CV_CAP_PROP_CONVERT_RGB =16,
CV_CAP_PROP_WHITE_BALANCE_BLUE_U =17,
CV_CAP_PROP_RECTIFICATION =18,
CV_CAP_PROP_MONOCROME =19,
CV_CAP_PROP_SHARPNESS =20,
CV_CAP_PROP_AUTO_EXPOSURE =21, // exposure control done by camera,
// user can adjust refernce level
// using this feature
CV_CAP_PROP_GAMMA =22,
CV_CAP_PROP_TEMPERATURE =23,
CV_CAP_PROP_TRIGGER =24,
CV_CAP_PROP_TRIGGER_DELAY =25,
CV_CAP_PROP_WHITE_BALANCE_RED_V =26,
CV_CAP_PROP_ZOOM =27,
CV_CAP_PROP_FOCUS =28,
CV_CAP_PROP_GUID =29,
CV_CAP_PROP_ISO_SPEED =30,
CV_CAP_PROP_MAX_DC1394 =31,
CV_CAP_PROP_BACKLIGHT =32,
CV_CAP_PROP_PAN =33,
CV_CAP_PROP_TILT =34,
CV_CAP_PROP_ROLL =35,
CV_CAP_PROP_IRIS =36,
CV_CAP_PROP_SETTINGS =37,
CV_CAP_PROP_AUTOGRAB =1024, // property for highgui class CvCapture_Android only
CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING=1025, // readonly, tricky property, returns cpnst char* indeed
CV_CAP_PROP_PREVIEW_FORMAT=1026, // readonly, tricky property, returns cpnst char* indeed
// OpenNI map generators
CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31,
CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30,
CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR,
// Properties of cameras available through OpenNI interfaces
CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100,
CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm
CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm
CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels
CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag
CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map
// by changing depth generator's view point (if the flag is "on") or
// sets this view point to its normal one (if the flag is "off").
CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105,
CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106,
CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107,
CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108,
CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109,
CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT,
CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE,
CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE,
CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH,
CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION,
CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION,
// Properties of cameras available through GStreamer interface
CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1
CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast
// Properties of cameras available through XIMEA SDK interface
CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping.
CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format.
CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels).
CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels).
CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger.
CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE.
CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input
CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode
CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level
CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output
CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode
CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED
CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality
CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition)
CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance
CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain
CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%).
CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure
CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure
CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %)
CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds
// Properties for Android cameras
CV_CAP_PROP_ANDROID_FLASH_MODE = 8001,
CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002,
CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003,
CV_CAP_PROP_ANDROID_ANTIBANDING = 8004,
CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008,
CV_CAP_PROP_ANDROID_EXPOSE_LOCK = 8009,
CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK = 8010,
// Properties of cameras available through AVFOUNDATION interface
CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001,
CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002,
CV_CAP_PROP_IOS_DEVICE_FLASH = 9003,
CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004,
CV_CAP_PROP_IOS_DEVICE_TORCH = 9005,
// Properties of cameras available through Smartek Giganetix Ethernet Vision interface
/* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */
CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001,
CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002,
CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003,
CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004,
CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005,
CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006,
CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001,
CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002,
CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003,
CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004,
CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005,
CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006,
CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007,
// Intel PerC streams
CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29,
CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28,
CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR
};
enum
{
// Data given from depth generator.
CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1)
CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3)
CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1)
CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1)
CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1
// Data given from RGB image generator.
CV_CAP_OPENNI_BGR_IMAGE = 5,
CV_CAP_OPENNI_GRAY_IMAGE = 6
};
// Supported output modes of OpenNI image generator
enum
{
CV_CAP_OPENNI_VGA_30HZ = 0,
CV_CAP_OPENNI_SXGA_15HZ = 1,
CV_CAP_OPENNI_SXGA_30HZ = 2,
CV_CAP_OPENNI_QVGA_30HZ = 3,
CV_CAP_OPENNI_QVGA_60HZ = 4
};
//supported by Android camera output formats
enum
{
CV_CAP_ANDROID_COLOR_FRAME_BGR = 0, //BGR
CV_CAP_ANDROID_COLOR_FRAME = CV_CAP_ANDROID_COLOR_FRAME_BGR,
CV_CAP_ANDROID_GREY_FRAME = 1, //Y
CV_CAP_ANDROID_COLOR_FRAME_RGB = 2,
CV_CAP_ANDROID_COLOR_FRAME_BGRA = 3,
CV_CAP_ANDROID_COLOR_FRAME_RGBA = 4
};
// supported Android camera flash modes
enum
{
CV_CAP_ANDROID_FLASH_MODE_AUTO = 0,
CV_CAP_ANDROID_FLASH_MODE_OFF,
CV_CAP_ANDROID_FLASH_MODE_ON,
CV_CAP_ANDROID_FLASH_MODE_RED_EYE,
CV_CAP_ANDROID_FLASH_MODE_TORCH
};
// supported Android camera focus modes
enum
{
CV_CAP_ANDROID_FOCUS_MODE_AUTO = 0,
CV_CAP_ANDROID_FOCUS_MODE_CONTINUOUS_PICTURE,
CV_CAP_ANDROID_FOCUS_MODE_CONTINUOUS_VIDEO,
CV_CAP_ANDROID_FOCUS_MODE_EDOF,
CV_CAP_ANDROID_FOCUS_MODE_FIXED,
CV_CAP_ANDROID_FOCUS_MODE_INFINITY,
CV_CAP_ANDROID_FOCUS_MODE_MACRO
};
// supported Android camera white balance modes
enum
{
CV_CAP_ANDROID_WHITE_BALANCE_AUTO = 0,
CV_CAP_ANDROID_WHITE_BALANCE_CLOUDY_DAYLIGHT,
CV_CAP_ANDROID_WHITE_BALANCE_DAYLIGHT,
CV_CAP_ANDROID_WHITE_BALANCE_FLUORESCENT,
CV_CAP_ANDROID_WHITE_BALANCE_INCANDESCENT,
CV_CAP_ANDROID_WHITE_BALANCE_SHADE,
CV_CAP_ANDROID_WHITE_BALANCE_TWILIGHT,
CV_CAP_ANDROID_WHITE_BALANCE_WARM_FLUORESCENT
};
// supported Android camera antibanding modes
enum
{
CV_CAP_ANDROID_ANTIBANDING_50HZ = 0,
CV_CAP_ANDROID_ANTIBANDING_60HZ,
CV_CAP_ANDROID_ANTIBANDING_AUTO,
CV_CAP_ANDROID_ANTIBANDING_OFF
};
enum
{
CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth.
CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates.
CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam.
CV_CAP_INTELPERC_IMAGE = 3
};
/* retrieve or set capture properties */
CVAPI(double) cvGetCaptureProperty( CvCapture* capture, int property_id );
CVAPI(int) cvSetCaptureProperty( CvCapture* capture, int property_id, double value );
// Return the type of the capturer (eg, CV_CAP_V4W, CV_CAP_UNICAP), which is unknown if created with CV_CAP_ANY
CVAPI(int) cvGetCaptureDomain( CvCapture* capture);
/* "black box" video file writer structure */
typedef struct CvVideoWriter CvVideoWriter;
#define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24))
CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4)
{
return CV_FOURCC_MACRO(c1, c2, c3, c4);
}
#define CV_FOURCC_PROMPT -1 /* Open Codec Selection Dialog (Windows only) */
#define CV_FOURCC_DEFAULT CV_FOURCC('I', 'Y', 'U', 'V') /* Use default codec for specified filename (Linux only) */
/* initialize video file writer */
CVAPI(CvVideoWriter*) cvCreateVideoWriter( const char* filename, int fourcc,
double fps, CvSize frame_size,
int is_color CV_DEFAULT(1));
//CVAPI(CvVideoWriter*) cvCreateImageSequenceWriter( const char* filename,
// int is_color CV_DEFAULT(1));
/* write frame to video file */
CVAPI(int) cvWriteFrame( CvVideoWriter* writer, const IplImage* image );
/* close video file writer */
CVAPI(void) cvReleaseVideoWriter( CvVideoWriter** writer );
/****************************************************************************************\
* Obsolete functions/synonyms *
\****************************************************************************************/
#define cvCaptureFromFile cvCreateFileCapture
#define cvCaptureFromCAM cvCreateCameraCapture
#define cvCaptureFromAVI cvCaptureFromFile
#define cvCreateAVIWriter cvCreateVideoWriter
#define cvWriteToAVI cvWriteFrame
#define cvAddSearchPath(path)
#define cvvInitSystem cvInitSystem
#define cvvNamedWindow cvNamedWindow
@ -237,14 +624,17 @@ CVAPI(void) cvUpdateWindow(const char* window_name);
#define cvvResizeWindow cvResizeWindow
#define cvvDestroyWindow cvDestroyWindow
#define cvvCreateTrackbar cvCreateTrackbar
#define cvvLoadImage(name) cvLoadImage((name),1)
#define cvvSaveImage cvSaveImage
#define cvvAddSearchPath cvAddSearchPath
#define cvvWaitKey(name) cvWaitKey(0)
#define cvvWaitKeyEx(name,delay) cvWaitKey(delay)
#define cvvConvertImage cvConvertImage
#define HG_AUTOSIZE CV_WINDOW_AUTOSIZE
#define set_preprocess_func cvSetPreprocessFuncWin32
#define set_postprocess_func cvSetPostprocessFuncWin32
#if defined _WIN32
#if defined WIN32 || defined _WIN32
CVAPI(void) cvSetPreprocessFuncWin32_(const void* callback);
CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback);
@ -253,8 +643,6 @@ CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback);
#endif
/** @} highgui_c */
#ifdef __cplusplus
}
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -40,8 +40,8 @@
//
//M*/
#ifndef OPENCV_IMGPROC_TYPES_C_H
#define OPENCV_IMGPROC_TYPES_C_H
#ifndef __OPENCV_IMGPROC_TYPES_C_H__
#define __OPENCV_IMGPROC_TYPES_C_H__
#include "opencv2/core/core_c.h"
@ -49,55 +49,41 @@
extern "C" {
#endif
/** @addtogroup imgproc_c
@{
*/
/** Connected component structure */
/* Connected component structure */
typedef struct CvConnectedComp
{
double area; /**<area of the connected component */
CvScalar value; /**<average color of the connected component */
CvRect rect; /**<ROI of the component */
CvSeq* contour; /**<optional component boundary
double area; /* area of the connected component */
CvScalar value; /* average color of the connected component */
CvRect rect; /* ROI of the component */
CvSeq* contour; /* optional component boundary
(the contour might have child contours corresponding to the holes)*/
}
CvConnectedComp;
/** Image smooth methods */
enum SmoothMethod_c
/* Image smooth methods */
enum
{
/** linear convolution with \f$\texttt{size1}\times\texttt{size2}\f$ box kernel (all 1's). If
you want to smooth different pixels with different-size box kernels, you can use the integral
image that is computed using integral */
CV_BLUR_NO_SCALE =0,
/** linear convolution with \f$\texttt{size1}\times\texttt{size2}\f$ box kernel (all
1's) with subsequent scaling by \f$1/(\texttt{size1}\cdot\texttt{size2})\f$ */
CV_BLUR =1,
/** linear convolution with a \f$\texttt{size1}\times\texttt{size2}\f$ Gaussian kernel */
CV_GAUSSIAN =2,
/** median filter with a \f$\texttt{size1}\times\texttt{size1}\f$ square aperture */
CV_MEDIAN =3,
/** bilateral filter with a \f$\texttt{size1}\times\texttt{size1}\f$ square aperture, color
sigma= sigma1 and spatial sigma= sigma2. If size1=0, the aperture square side is set to
cvRound(sigma2\*1.5)\*2+1. See cv::bilateralFilter */
CV_BILATERAL =4
};
/** Filters used in pyramid decomposition */
/* Filters used in pyramid decomposition */
enum
{
CV_GAUSSIAN_5x5 = 7
};
/** Special filters */
/* Special filters */
enum
{
CV_SCHARR =-1,
CV_MAX_SOBEL_KSIZE =7
};
/** Constants for color conversion */
/* Constants for color conversion */
enum
{
CV_BGR2BGRA =0,
@ -338,32 +324,11 @@ enum
CV_RGBA2YUV_YV12 = 133,
CV_BGRA2YUV_YV12 = 134,
// Edge-Aware Demosaicing
CV_BayerBG2BGR_EA = 135,
CV_BayerGB2BGR_EA = 136,
CV_BayerRG2BGR_EA = 137,
CV_BayerGR2BGR_EA = 138,
CV_BayerBG2RGB_EA = CV_BayerRG2BGR_EA,
CV_BayerGB2RGB_EA = CV_BayerGR2BGR_EA,
CV_BayerRG2RGB_EA = CV_BayerBG2BGR_EA,
CV_BayerGR2RGB_EA = CV_BayerGB2BGR_EA,
CV_BayerBG2BGRA =139,
CV_BayerGB2BGRA =140,
CV_BayerRG2BGRA =141,
CV_BayerGR2BGRA =142,
CV_BayerBG2RGBA =CV_BayerRG2BGRA,
CV_BayerGB2RGBA =CV_BayerGR2BGRA,
CV_BayerRG2RGBA =CV_BayerBG2BGRA,
CV_BayerGR2RGBA =CV_BayerGB2BGRA,
CV_COLORCVT_MAX = 143
CV_COLORCVT_MAX = 135
};
/** Sub-pixel interpolation methods */
/* Sub-pixel interpolation methods */
enum
{
CV_INTER_NN =0,
@ -373,25 +338,23 @@ enum
CV_INTER_LANCZOS4 =4
};
/** ... and other image warping flags */
/* ... and other image warping flags */
enum
{
CV_WARP_FILL_OUTLIERS =8,
CV_WARP_INVERSE_MAP =16
};
/** Shapes of a structuring element for morphological operations
@see cv::MorphShapes, cv::getStructuringElement
*/
enum MorphShapes_c
/* Shapes of a structuring element for morphological operations */
enum
{
CV_SHAPE_RECT =0,
CV_SHAPE_CROSS =1,
CV_SHAPE_ELLIPSE =2,
CV_SHAPE_CUSTOM =100 //!< custom structuring element
CV_SHAPE_CUSTOM =100
};
/** Morphological operations */
/* Morphological operations */
enum
{
CV_MOP_ERODE =0,
@ -403,71 +366,23 @@ enum
CV_MOP_BLACKHAT =6
};
/** Spatial and central moments */
/* Spatial and central moments */
typedef struct CvMoments
{
double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; /**< spatial moments */
double mu20, mu11, mu02, mu30, mu21, mu12, mu03; /**< central moments */
double inv_sqrt_m00; /**< m00 != 0 ? 1/sqrt(m00) : 0 */
#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)
CvMoments(){}
CvMoments(const cv::Moments& m)
{
m00 = m.m00; m10 = m.m10; m01 = m.m01;
m20 = m.m20; m11 = m.m11; m02 = m.m02;
m30 = m.m30; m21 = m.m21; m12 = m.m12; m03 = m.m03;
mu20 = m.mu20; mu11 = m.mu11; mu02 = m.mu02;
mu30 = m.mu30; mu21 = m.mu21; mu12 = m.mu12; mu03 = m.mu03;
double am00 = std::abs(m.m00);
inv_sqrt_m00 = am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0;
}
operator cv::Moments() const
{
return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03);
}
#endif
double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; /* spatial moments */
double mu20, mu11, mu02, mu30, mu21, mu12, mu03; /* central moments */
double inv_sqrt_m00; /* m00 != 0 ? 1/sqrt(m00) : 0 */
}
CvMoments;
#ifdef __cplusplus
} // extern "C"
CV_INLINE CvMoments cvMoments()
{
#if !defined(CV__ENABLE_C_API_CTORS)
CvMoments self = CV_STRUCT_INITIALIZER; return self;
#else
return CvMoments();
#endif
}
CV_INLINE CvMoments cvMoments(const cv::Moments& m)
{
#if !defined(CV__ENABLE_C_API_CTORS)
double am00 = std::abs(m.m00);
CvMoments self = {
m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03,
m.mu20, m.mu11, m.mu02, m.mu30, m.mu21, m.mu12, m.mu03,
am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0
};
return self;
#else
return CvMoments(m);
#endif
}
extern "C" {
#endif // __cplusplus
/** Hu invariants */
/* Hu invariants */
typedef struct CvHuMoments
{
double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /**< Hu invariants */
double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /* Hu invariants */
}
CvHuMoments;
/** Template matching methods */
/* Template matching methods */
enum
{
CV_TM_SQDIFF =0,
@ -480,7 +395,7 @@ enum
typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param );
/** Contour retrieval modes */
/* Contour retrieval modes */
enum
{
CV_RETR_EXTERNAL=0,
@ -490,7 +405,7 @@ enum
CV_RETR_FLOODFILL=4
};
/** Contour approximation methods */
/* Contour approximation methods */
enum
{
CV_CHAIN_CODE=0,
@ -502,12 +417,12 @@ enum
};
/*
Internal structure that is used for sequential retrieving contours from the image.
Internal structure that is used for sequental retrieving contours from the image.
It supports both hierarchical and plane variants of Suzuki algorithm.
*/
typedef struct _CvContourScanner* CvContourScanner;
/** Freeman chain reader state */
/* Freeman chain reader state */
typedef struct CvChainPtReader
{
CV_SEQ_READER_FIELDS()
@ -517,7 +432,7 @@ typedef struct CvChainPtReader
}
CvChainPtReader;
/** initializes 8-element array for fast access to 3x3 neighborhood of a pixel */
/* initializes 8-element array for fast access to 3x3 neighborhood of a pixel */
#define CV_INIT_3X3_DELTAS( deltas, step, nch ) \
((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \
(deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \
@ -525,21 +440,94 @@ CvChainPtReader;
(deltas)[6] = (step), (deltas)[7] = (step) + (nch))
/** Contour approximation algorithms */
/****************************************************************************************\
* Planar subdivisions *
\****************************************************************************************/
typedef size_t CvSubdiv2DEdge;
#define CV_QUADEDGE2D_FIELDS() \
int flags; \
struct CvSubdiv2DPoint* pt[4]; \
CvSubdiv2DEdge next[4];
#define CV_SUBDIV2D_POINT_FIELDS()\
int flags; \
CvSubdiv2DEdge first; \
CvPoint2D32f pt; \
int id;
#define CV_SUBDIV2D_VIRTUAL_POINT_FLAG (1 << 30)
typedef struct CvQuadEdge2D
{
CV_QUADEDGE2D_FIELDS()
}
CvQuadEdge2D;
typedef struct CvSubdiv2DPoint
{
CV_SUBDIV2D_POINT_FIELDS()
}
CvSubdiv2DPoint;
#define CV_SUBDIV2D_FIELDS() \
CV_GRAPH_FIELDS() \
int quad_edges; \
int is_geometry_valid; \
CvSubdiv2DEdge recent_edge; \
CvPoint2D32f topleft; \
CvPoint2D32f bottomright;
typedef struct CvSubdiv2D
{
CV_SUBDIV2D_FIELDS()
}
CvSubdiv2D;
typedef enum CvSubdiv2DPointLocation
{
CV_PTLOC_ERROR = -2,
CV_PTLOC_OUTSIDE_RECT = -1,
CV_PTLOC_INSIDE = 0,
CV_PTLOC_VERTEX = 1,
CV_PTLOC_ON_EDGE = 2
}
CvSubdiv2DPointLocation;
typedef enum CvNextEdgeType
{
CV_NEXT_AROUND_ORG = 0x00,
CV_NEXT_AROUND_DST = 0x22,
CV_PREV_AROUND_ORG = 0x11,
CV_PREV_AROUND_DST = 0x33,
CV_NEXT_AROUND_LEFT = 0x13,
CV_NEXT_AROUND_RIGHT = 0x31,
CV_PREV_AROUND_LEFT = 0x20,
CV_PREV_AROUND_RIGHT = 0x02
}
CvNextEdgeType;
/* get the next edge with the same origin point (counterwise) */
#define CV_SUBDIV2D_NEXT_EDGE( edge ) (((CvQuadEdge2D*)((edge) & ~3))->next[(edge)&3])
/* Contour approximation algorithms */
enum
{
CV_POLY_APPROX_DP = 0
};
/** Shape matching methods */
/* Shape matching methods */
enum
{
CV_CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f]
CV_CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f]
CV_CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f]
CV_CONTOURS_MATCH_I1 =1,
CV_CONTOURS_MATCH_I2 =2,
CV_CONTOURS_MATCH_I3 =3
};
/** Shape orientation */
/* Shape orientation */
enum
{
CV_CLOCKWISE =1,
@ -547,29 +535,27 @@ enum
};
/** Convexity defect */
/* Convexity defect */
typedef struct CvConvexityDefect
{
CvPoint* start; /**< point of the contour where the defect begins */
CvPoint* end; /**< point of the contour where the defect ends */
CvPoint* depth_point; /**< the farthest from the convex hull point within the defect */
float depth; /**< distance between the farthest point and the convex hull */
CvPoint* start; /* point of the contour where the defect begins */
CvPoint* end; /* point of the contour where the defect ends */
CvPoint* depth_point; /* the farthest from the convex hull point within the defect */
float depth; /* distance between the farthest point and the convex hull */
} CvConvexityDefect;
/** Histogram comparison methods */
/* Histogram comparison methods */
enum
{
CV_COMP_CORREL =0,
CV_COMP_CHISQR =1,
CV_COMP_INTERSECT =2,
CV_COMP_BHATTACHARYYA =3,
CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA,
CV_COMP_CHISQR_ALT =4,
CV_COMP_KL_DIV =5
CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA
};
/** Mask size for distance transform */
/* Mask size for distance transform */
enum
{
CV_DIST_MASK_3 =3,
@ -577,51 +563,48 @@ enum
CV_DIST_MASK_PRECISE =0
};
/** Content of output label array: connected components or pixels */
/* Content of output label array: connected components or pixels */
enum
{
CV_DIST_LABEL_CCOMP = 0,
CV_DIST_LABEL_PIXEL = 1
};
/** Distance types for Distance Transform and M-estimators */
/* Distance types for Distance Transform and M-estimators */
enum
{
CV_DIST_USER =-1, /**< User defined distance */
CV_DIST_L1 =1, /**< distance = |x1-x2| + |y1-y2| */
CV_DIST_L2 =2, /**< the simple euclidean distance */
CV_DIST_C =3, /**< distance = max(|x1-x2|,|y1-y2|) */
CV_DIST_L12 =4, /**< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */
CV_DIST_FAIR =5, /**< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */
CV_DIST_WELSCH =6, /**< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */
CV_DIST_HUBER =7 /**< distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345 */
CV_DIST_USER =-1, /* User defined distance */
CV_DIST_L1 =1, /* distance = |x1-x2| + |y1-y2| */
CV_DIST_L2 =2, /* the simple euclidean distance */
CV_DIST_C =3, /* distance = max(|x1-x2|,|y1-y2|) */
CV_DIST_L12 =4, /* L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */
CV_DIST_FAIR =5, /* distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */
CV_DIST_WELSCH =6, /* distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */
CV_DIST_HUBER =7 /* distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345 */
};
/** Threshold types */
/* Threshold types */
enum
{
CV_THRESH_BINARY =0, /**< value = value > threshold ? max_value : 0 */
CV_THRESH_BINARY_INV =1, /**< value = value > threshold ? 0 : max_value */
CV_THRESH_TRUNC =2, /**< value = value > threshold ? threshold : value */
CV_THRESH_TOZERO =3, /**< value = value > threshold ? value : 0 */
CV_THRESH_TOZERO_INV =4, /**< value = value > threshold ? 0 : value */
CV_THRESH_BINARY =0, /* value = value > threshold ? max_value : 0 */
CV_THRESH_BINARY_INV =1, /* value = value > threshold ? 0 : max_value */
CV_THRESH_TRUNC =2, /* value = value > threshold ? threshold : value */
CV_THRESH_TOZERO =3, /* value = value > threshold ? value : 0 */
CV_THRESH_TOZERO_INV =4, /* value = value > threshold ? 0 : value */
CV_THRESH_MASK =7,
CV_THRESH_OTSU =8, /**< use Otsu algorithm to choose the optimal threshold value;
CV_THRESH_OTSU =8 /* use Otsu algorithm to choose the optimal threshold value;
combine the flag with one of the above CV_THRESH_* values */
CV_THRESH_TRIANGLE =16 /**< use Triangle algorithm to choose the optimal threshold value;
combine the flag with one of the above CV_THRESH_* values, but not
with CV_THRESH_OTSU */
};
/** Adaptive threshold methods */
/* Adaptive threshold methods */
enum
{
CV_ADAPTIVE_THRESH_MEAN_C =0,
CV_ADAPTIVE_THRESH_GAUSSIAN_C =1
};
/** FloodFill flags */
/* FloodFill flags */
enum
{
CV_FLOODFILL_FIXED_RANGE =(1 << 16),
@ -629,13 +612,13 @@ enum
};
/** Canny edge detector flags */
/* Canny edge detector flags */
enum
{
CV_CANNY_L2_GRADIENT =(1 << 31)
};
/** Variants of a Hough transform */
/* Variants of a Hough transform */
enum
{
CV_HOUGH_STANDARD =0,
@ -650,8 +633,6 @@ struct CvFeatureTree;
struct CvLSH;
struct CvLSHOperations;
/** @} */
#ifdef __cplusplus
}
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -40,100 +40,22 @@
//
//M*/
#ifndef OPENCV_ALL_HPP
#define OPENCV_ALL_HPP
#ifndef __OPENCV_ALL_HPP__
#define __OPENCV_ALL_HPP__
// File that defines what modules where included during the build of OpenCV
// These are purely the defines of the correct HAVE_OPENCV_modulename values
#include "opencv2/opencv_modules.hpp"
// Then the list of defines is checked to include the correct headers
// Core library is always included --> without no OpenCV functionality available
#include "opencv2/core.hpp"
// Then the optional modules are checked
#ifdef HAVE_OPENCV_CALIB3D
#include "opencv2/calib3d.hpp"
#endif
#ifdef HAVE_OPENCV_FEATURES2D
#include "opencv2/features2d.hpp"
#endif
#ifdef HAVE_OPENCV_DNN
#include "opencv2/dnn.hpp"
#endif
#ifdef HAVE_OPENCV_FLANN
#include "opencv2/flann.hpp"
#endif
#ifdef HAVE_OPENCV_HIGHGUI
#include "opencv2/highgui.hpp"
#endif
#ifdef HAVE_OPENCV_IMGCODECS
#include "opencv2/imgcodecs.hpp"
#endif
#ifdef HAVE_OPENCV_IMGPROC
#include "opencv2/imgproc.hpp"
#endif
#ifdef HAVE_OPENCV_ML
#include "opencv2/ml.hpp"
#endif
#ifdef HAVE_OPENCV_OBJDETECT
#include "opencv2/objdetect.hpp"
#endif
#ifdef HAVE_OPENCV_PHOTO
#include "opencv2/photo.hpp"
#endif
#ifdef HAVE_OPENCV_SHAPE
#include "opencv2/shape.hpp"
#endif
#ifdef HAVE_OPENCV_STITCHING
#include "opencv2/stitching.hpp"
#endif
#ifdef HAVE_OPENCV_SUPERRES
#include "opencv2/superres.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEO
#include "opencv2/video.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEOIO
#include "opencv2/videoio.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEOSTAB
#include "opencv2/videostab.hpp"
#endif
#ifdef HAVE_OPENCV_VIZ
#include "opencv2/viz.hpp"
#endif
// Finally CUDA specific entries are checked and added
#ifdef HAVE_OPENCV_CUDAARITHM
#include "opencv2/cudaarithm.hpp"
#endif
#ifdef HAVE_OPENCV_CUDABGSEGM
#include "opencv2/cudabgsegm.hpp"
#endif
#ifdef HAVE_OPENCV_CUDACODEC
#include "opencv2/cudacodec.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAFEATURES2D
#include "opencv2/cudafeatures2d.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAFILTERS
#include "opencv2/cudafilters.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAIMGPROC
#include "opencv2/cudaimgproc.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAOBJDETECT
#include "opencv2/cudaobjdetect.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAOPTFLOW
#include "opencv2/cudaoptflow.hpp"
#endif
#ifdef HAVE_OPENCV_CUDASTEREO
#include "opencv2/cudastereo.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAWARPING
#include "opencv2/cudawarping.hpp"
#endif
#include "opencv2/core/core_c.h"
#include "opencv2/core/core.hpp"
#include "opencv2/flann/miniflann.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/photo/photo.hpp"
#include "opencv2/video/video.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/ml/ml.hpp"
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp"
#endif

View File

@ -6,26 +6,24 @@
*
*/
// This definition means that OpenCV is built with enabled non-free code.
// For example, patented algorithms for non-profit/non-commercial use only.
/* #undef OPENCV_ENABLE_NONFREE */
#define HAVE_OPENCV_CALIB3D
#define HAVE_OPENCV_CONTRIB
#define HAVE_OPENCV_CORE
#define HAVE_OPENCV_DNN
#define HAVE_OPENCV_FEATURES2D
#define HAVE_OPENCV_FLANN
#define HAVE_OPENCV_GPU
#define HAVE_OPENCV_HIGHGUI
#define HAVE_OPENCV_IMGCODECS
#define HAVE_OPENCV_IMGPROC
#define HAVE_OPENCV_LEGACY
#define HAVE_OPENCV_ML
#define HAVE_OPENCV_NONFREE
#define HAVE_OPENCV_OBJDETECT
#define HAVE_OPENCV_OCL
#define HAVE_OPENCV_PHOTO
#define HAVE_OPENCV_SHAPE
#define HAVE_OPENCV_STITCHING
#define HAVE_OPENCV_SUPERRES
#define HAVE_OPENCV_TS
#define HAVE_OPENCV_VIDEO
#define HAVE_OPENCV_VIDEOIO
#define HAVE_OPENCV_VIDEOSTAB

View File

@ -7,12 +7,11 @@
// copy or use the software.
//
//
// License Agreement
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
@ -41,8 +40,52 @@
//
//M*/
#ifdef __OPENCV_BUILD
#error this is a compatibility header which should not be used inside the OpenCV library
#endif
#ifndef __OPENCV_PHOTO_HPP__
#define __OPENCV_PHOTO_HPP__
#include "opencv2/photo.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/photo/photo_c.h"
#ifdef __cplusplus
/*! \namespace cv
Namespace where all the C++ OpenCV functionality resides
*/
namespace cv
{
//! the inpainting algorithm
enum
{
INPAINT_NS=CV_INPAINT_NS, // Navier-Stokes algorithm
INPAINT_TELEA=CV_INPAINT_TELEA // A. Telea algorithm
};
//! restores the damaged image areas using one of the available intpainting algorithms
CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask,
OutputArray dst, double inpaintRadius, int flags );
CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, float h = 3,
int templateWindowSize = 7, int searchWindowSize = 21);
CV_EXPORTS_W void fastNlMeansDenoisingColored( InputArray src, OutputArray dst,
float h = 3, float hColor = 3,
int templateWindowSize = 7, int searchWindowSize = 21);
CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst,
int imgToDenoiseIndex, int temporalWindowSize,
float h = 3, int templateWindowSize = 7, int searchWindowSize = 21);
CV_EXPORTS_W void fastNlMeansDenoisingColoredMulti( InputArrayOfArrays srcImgs, OutputArray dst,
int imgToDenoiseIndex, int temporalWindowSize,
float h = 3, float hColor = 3,
int templateWindowSize = 7, int searchWindowSize = 21);
}
#endif //__cplusplus
#endif

View File

@ -40,8 +40,8 @@
//
//M*/
#ifndef OPENCV_PHOTO_C_H
#define OPENCV_PHOTO_C_H
#ifndef __OPENCV_PHOTO_C_H__
#define __OPENCV_PHOTO_C_H__
#include "opencv2/core/core_c.h"
@ -49,12 +49,8 @@
extern "C" {
#endif
/** @addtogroup photo_c
@{
*/
/* Inpainting algorithms */
enum InpaintingModes
enum
{
CV_INPAINT_NS =0,
CV_INPAINT_TELEA =1
@ -65,10 +61,9 @@ enum InpaintingModes
CVAPI(void) cvInpaint( const CvArr* src, const CvArr* inpaint_mask,
CvArr* dst, double inpaintRange, int flags );
/** @} */
#ifdef __cplusplus
} //extern "C"
#endif
#endif //OPENCV_PHOTO_C_H
#endif //__OPENCV_PHOTO_C_H__

View File

@ -40,47 +40,26 @@
//
//M*/
#ifndef OPENCV_STITCHING_AUTOCALIB_HPP
#define OPENCV_STITCHING_AUTOCALIB_HPP
#ifndef __OPENCV_STITCHING_AUTOCALIB_HPP__
#define __OPENCV_STITCHING_AUTOCALIB_HPP__
#include "opencv2/core.hpp"
#include "opencv2/core/core.hpp"
#include "matchers.hpp"
namespace cv {
namespace detail {
//! @addtogroup stitching_autocalib
//! @{
/** @brief Tries to estimate focal lengths from the given homography under the assumption that the camera
undergoes rotations around its centre only.
@param H Homography.
@param f0 Estimated focal length along X axis.
@param f1 Estimated focal length along Y axis.
@param f0_ok True, if f0 was estimated successfully, false otherwise.
@param f1_ok True, if f1 was estimated successfully, false otherwise.
See "Construction of Panoramic Image Mosaics with Global and Local Alignment"
by Heung-Yeung Shum and Richard Szeliski.
*/
// See "Construction of Panoramic Image Mosaics with Global and Local Alignment"
// by Heung-Yeung Shum and Richard Szeliski.
void CV_EXPORTS focalsFromHomography(const Mat &H, double &f0, double &f1, bool &f0_ok, bool &f1_ok);
/** @brief Estimates focal lengths for each given camera.
@param features Features of images.
@param pairwise_matches Matches between all image pairs.
@param focals Estimated focal lengths for each camera.
*/
void CV_EXPORTS estimateFocal(const std::vector<ImageFeatures> &features,
const std::vector<MatchesInfo> &pairwise_matches,
std::vector<double> &focals);
bool CV_EXPORTS calibrateRotatingCamera(const std::vector<Mat> &Hs, Mat &K);
//! @} stitching_autocalib
} // namespace detail
} // namespace cv
#endif // OPENCV_STITCHING_AUTOCALIB_HPP
#endif // __OPENCV_STITCHING_AUTOCALIB_HPP__

View File

@ -40,26 +40,16 @@
//
//M*/
#ifndef OPENCV_STITCHING_BLENDERS_HPP
#define OPENCV_STITCHING_BLENDERS_HPP
#ifndef __OPENCV_STITCHING_BLENDERS_HPP__
#define __OPENCV_STITCHING_BLENDERS_HPP__
#if defined(NO)
# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers.
#endif
#include "opencv2/core.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/core/core.hpp"
namespace cv {
namespace detail {
//! @addtogroup stitching_blend
//! @{
/** @brief Base class for all blenders.
Simple blender which puts one image over another
*/
// Simple blender which puts one image over another
class CV_EXPORTS Blender
{
public:
@ -68,35 +58,17 @@ public:
enum { NO, FEATHER, MULTI_BAND };
static Ptr<Blender> createDefault(int type, bool try_gpu = false);
/** @brief Prepares the blender for blending.
@param corners Source images top-left corners
@param sizes Source image sizes
*/
void prepare(const std::vector<Point> &corners, const std::vector<Size> &sizes);
/** @overload */
virtual void prepare(Rect dst_roi);
/** @brief Processes the image.
@param img Source image
@param mask Source image mask
@param tl Source image top-left corners
*/
virtual void feed(InputArray img, InputArray mask, Point tl);
/** @brief Blends and returns the final pano.
@param dst Final pano
@param dst_mask Final pano mask
*/
virtual void blend(InputOutputArray dst, InputOutputArray dst_mask);
virtual void feed(const Mat &img, const Mat &mask, Point tl);
virtual void blend(Mat &dst, Mat &dst_mask);
protected:
UMat dst_, dst_mask_;
Mat dst_, dst_mask_;
Rect dst_roi_;
};
/** @brief Simple blender which mixes images at its borders.
*/
class CV_EXPORTS FeatherBlender : public Blender
{
public:
@ -105,25 +77,24 @@ public:
float sharpness() const { return sharpness_; }
void setSharpness(float val) { sharpness_ = val; }
void prepare(Rect dst_roi) CV_OVERRIDE;
void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE;
void blend(InputOutputArray dst, InputOutputArray dst_mask) CV_OVERRIDE;
void prepare(Rect dst_roi);
void feed(const Mat &img, const Mat &mask, Point tl);
void blend(Mat &dst, Mat &dst_mask);
//! Creates weight maps for fixed set of source images by their masks and top-left corners.
//! Final image can be obtained by simple weighting of the source images.
Rect createWeightMaps(const std::vector<UMat> &masks, const std::vector<Point> &corners,
std::vector<UMat> &weight_maps);
// Creates weight maps for fixed set of source images by their masks and top-left corners.
// Final image can be obtained by simple weighting of the source images.
Rect createWeightMaps(const std::vector<Mat> &masks, const std::vector<Point> &corners,
std::vector<Mat> &weight_maps);
private:
float sharpness_;
UMat weight_map_;
UMat dst_weight_map_;
Mat weight_map_;
Mat dst_weight_map_;
};
inline FeatherBlender::FeatherBlender(float _sharpness) { setSharpness(_sharpness); }
/** @brief Blender which uses multi-band blending algorithm (see @cite BA83).
*/
class CV_EXPORTS MultiBandBlender : public Blender
{
public:
@ -132,53 +103,35 @@ public:
int numBands() const { return actual_num_bands_; }
void setNumBands(int val) { actual_num_bands_ = val; }
void prepare(Rect dst_roi) CV_OVERRIDE;
void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE;
void blend(InputOutputArray dst, InputOutputArray dst_mask) CV_OVERRIDE;
void prepare(Rect dst_roi);
void feed(const Mat &img, const Mat &mask, Point tl);
void blend(Mat &dst, Mat &dst_mask);
private:
int actual_num_bands_, num_bands_;
std::vector<UMat> dst_pyr_laplace_;
std::vector<UMat> dst_band_weights_;
std::vector<Mat> dst_pyr_laplace_;
std::vector<Mat> dst_band_weights_;
Rect dst_roi_final_;
bool can_use_gpu_;
int weight_type_; //CV_32F or CV_16S
#if defined(HAVE_OPENCV_CUDAARITHM) && defined(HAVE_OPENCV_CUDAWARPING)
std::vector<cuda::GpuMat> gpu_dst_pyr_laplace_;
std::vector<cuda::GpuMat> gpu_dst_band_weights_;
std::vector<Point> gpu_tl_points_;
std::vector<cuda::GpuMat> gpu_imgs_with_border_;
std::vector<std::vector<cuda::GpuMat> > gpu_weight_pyr_gauss_vec_;
std::vector<std::vector<cuda::GpuMat> > gpu_src_pyr_laplace_vec_;
std::vector<std::vector<cuda::GpuMat> > gpu_ups_;
cuda::GpuMat gpu_dst_mask_;
cuda::GpuMat gpu_mask_;
cuda::GpuMat gpu_img_;
cuda::GpuMat gpu_weight_map_;
cuda::GpuMat gpu_add_mask_;
int gpu_feed_idx_;
bool gpu_initialized_;
#endif
};
//////////////////////////////////////////////////////////////////////////////
// Auxiliary functions
void CV_EXPORTS normalizeUsingWeightMap(InputArray weight, InputOutputArray src);
void CV_EXPORTS normalizeUsingWeightMap(const Mat& weight, Mat& src);
void CV_EXPORTS createWeightMap(InputArray mask, float sharpness, InputOutputArray weight);
void CV_EXPORTS createWeightMap(const Mat& mask, float sharpness, Mat& weight);
void CV_EXPORTS createLaplacePyr(InputArray img, int num_levels, std::vector<UMat>& pyr);
void CV_EXPORTS createLaplacePyrGpu(InputArray img, int num_levels, std::vector<UMat>& pyr);
void CV_EXPORTS createLaplacePyr(const Mat &img, int num_levels, std::vector<Mat>& pyr);
void CV_EXPORTS createLaplacePyrGpu(const Mat &img, int num_levels, std::vector<Mat>& pyr);
// Restores source image
void CV_EXPORTS restoreImageFromLaplacePyr(std::vector<UMat>& pyr);
void CV_EXPORTS restoreImageFromLaplacePyrGpu(std::vector<UMat>& pyr);
//! @}
void CV_EXPORTS restoreImageFromLaplacePyr(std::vector<Mat>& pyr);
void CV_EXPORTS restoreImageFromLaplacePyrGpu(std::vector<Mat>& pyr);
} // namespace detail
} // namespace cv
#endif // OPENCV_STITCHING_BLENDERS_HPP
#endif // __OPENCV_STITCHING_BLENDERS_HPP__

View File

@ -40,26 +40,19 @@
//
//M*/
#ifndef OPENCV_STITCHING_CAMERA_HPP
#define OPENCV_STITCHING_CAMERA_HPP
#ifndef __OPENCV_STITCHING_CAMERA_HPP__
#define __OPENCV_STITCHING_CAMERA_HPP__
#include "opencv2/core.hpp"
#include "opencv2/core/core.hpp"
namespace cv {
namespace detail {
//! @addtogroup stitching
//! @{
/** @brief Describes camera parameters.
@note Translation is assumed to be zero during the whole stitching pipeline. :
*/
struct CV_EXPORTS CameraParams
{
CameraParams();
CameraParams(const CameraParams& other);
CameraParams& operator =(const CameraParams& other);
const CameraParams& operator =(const CameraParams& other);
Mat K() const;
double focal; // Focal length
@ -70,9 +63,7 @@ struct CV_EXPORTS CameraParams
Mat t; // Translation
};
//! @}
} // namespace detail
} // namespace cv
#endif // #ifndef OPENCV_STITCHING_CAMERA_HPP
#endif // #ifndef __OPENCV_STITCHING_CAMERA_HPP__

View File

@ -40,23 +40,14 @@
//
//M*/
#ifndef OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP
#define OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP
#ifndef __OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP__
#define __OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP__
#if defined(NO)
# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers.
#endif
#include "opencv2/core.hpp"
#include "opencv2/core/core.hpp"
namespace cv {
namespace detail {
//! @addtogroup stitching_exposure
//! @{
/** @brief Base class for all exposure compensators.
*/
class CV_EXPORTS ExposureCompensator
{
public:
@ -65,72 +56,51 @@ public:
enum { NO, GAIN, GAIN_BLOCKS };
static Ptr<ExposureCompensator> createDefault(int type);
/**
@param corners Source image top-left corners
@param images Source images
@param masks Image masks to update (second value in pair specifies the value which should be used
to detect where image is)
*/
void feed(const std::vector<Point> &corners, const std::vector<UMat> &images,
const std::vector<UMat> &masks);
/** @overload */
virtual void feed(const std::vector<Point> &corners, const std::vector<UMat> &images,
const std::vector<std::pair<UMat,uchar> > &masks) = 0;
/** @brief Compensate exposure in the specified image.
@param index Image index
@param corner Image top-left corner
@param image Image to process
@param mask Image mask
*/
virtual void apply(int index, Point corner, InputOutputArray image, InputArray mask) = 0;
void feed(const std::vector<Point> &corners, const std::vector<Mat> &images,
const std::vector<Mat> &masks);
virtual void feed(const std::vector<Point> &corners, const std::vector<Mat> &images,
const std::vector<std::pair<Mat,uchar> > &masks) = 0;
virtual void apply(int index, Point corner, Mat &image, const Mat &mask) = 0;
};
/** @brief Stub exposure compensator which does nothing.
*/
class CV_EXPORTS NoExposureCompensator : public ExposureCompensator
{
public:
void feed(const std::vector<Point> &/*corners*/, const std::vector<UMat> &/*images*/,
const std::vector<std::pair<UMat,uchar> > &/*masks*/) CV_OVERRIDE { }
void apply(int /*index*/, Point /*corner*/, InputOutputArray /*image*/, InputArray /*mask*/) CV_OVERRIDE { }
void feed(const std::vector<Point> &/*corners*/, const std::vector<Mat> &/*images*/,
const std::vector<std::pair<Mat,uchar> > &/*masks*/) {};
void apply(int /*index*/, Point /*corner*/, Mat &/*image*/, const Mat &/*mask*/) {};
};
/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image
intensities, see @cite BL07 and @cite WJ10 for details.
*/
class CV_EXPORTS GainCompensator : public ExposureCompensator
{
public:
void feed(const std::vector<Point> &corners, const std::vector<UMat> &images,
const std::vector<std::pair<UMat,uchar> > &masks) CV_OVERRIDE;
void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE;
void feed(const std::vector<Point> &corners, const std::vector<Mat> &images,
const std::vector<std::pair<Mat,uchar> > &masks);
void apply(int index, Point corner, Mat &image, const Mat &mask);
std::vector<double> gains() const;
private:
Mat_<double> gains_;
};
/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block
intensities, see @cite UES01 for details.
*/
class CV_EXPORTS BlocksGainCompensator : public ExposureCompensator
{
public:
BlocksGainCompensator(int bl_width = 32, int bl_height = 32)
: bl_width_(bl_width), bl_height_(bl_height) {}
void feed(const std::vector<Point> &corners, const std::vector<UMat> &images,
const std::vector<std::pair<UMat,uchar> > &masks) CV_OVERRIDE;
void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE;
void feed(const std::vector<Point> &corners, const std::vector<Mat> &images,
const std::vector<std::pair<Mat,uchar> > &masks);
void apply(int index, Point corner, Mat &image, const Mat &mask);
private:
int bl_width_, bl_height_;
std::vector<UMat> gain_maps_;
std::vector<Mat_<float> > gain_maps_;
};
//! @}
} // namespace detail
} // namespace cv
#endif // OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP
#endif // __OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP__

View File

@ -40,89 +40,44 @@
//
//M*/
#ifndef OPENCV_STITCHING_MATCHERS_HPP
#define OPENCV_STITCHING_MATCHERS_HPP
#ifndef __OPENCV_STITCHING_MATCHERS_HPP__
#define __OPENCV_STITCHING_MATCHERS_HPP__
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/core/gpumat.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/opencv_modules.hpp"
#ifdef HAVE_OPENCV_XFEATURES2D
# include "opencv2/xfeatures2d/cuda.hpp"
#if defined(HAVE_OPENCV_NONFREE)
#include "opencv2/nonfree/gpu.hpp"
#endif
namespace cv {
namespace detail {
//! @addtogroup stitching_match
//! @{
/** @brief Structure containing image keypoints and descriptors. */
struct CV_EXPORTS ImageFeatures
{
int img_idx;
Size img_size;
std::vector<KeyPoint> keypoints;
UMat descriptors;
Mat descriptors;
};
/** @brief Feature finders base class */
class CV_EXPORTS FeaturesFinder
{
public:
virtual ~FeaturesFinder() {}
/** @overload */
void operator ()(InputArray image, ImageFeatures &features);
/** @brief Finds features in the given image.
@param image Source image
@param features Found features
@param rois Regions of interest
@sa detail::ImageFeatures, Rect_
*/
void operator ()(InputArray image, ImageFeatures &features, const std::vector<cv::Rect> &rois);
/** @brief Finds features in the given images in parallel.
@param images Source images
@param features Found features for each image
@param rois Regions of interest for each image
@sa detail::ImageFeatures, Rect_
*/
void operator ()(InputArrayOfArrays images, std::vector<ImageFeatures> &features,
const std::vector<std::vector<cv::Rect> > &rois);
/** @overload */
void operator ()(InputArrayOfArrays images, std::vector<ImageFeatures> &features);
/** @brief Frees unused memory allocated before if there is any. */
void operator ()(const Mat &image, ImageFeatures &features);
void operator ()(const Mat &image, ImageFeatures &features, const std::vector<cv::Rect> &rois);
virtual void collectGarbage() {}
/* TODO OpenCV ABI 4.x
reimplement this as public method similar to FeaturesMatcher and remove private function hack
@return True, if it's possible to use the same finder instance in parallel, false otherwise
bool isThreadSafe() const { return is_thread_safe_; }
*/
protected:
/** @brief This method must implement features finding logic in order to make the wrappers
detail::FeaturesFinder::operator()_ work.
@param image Source image
@param features Found features
@sa detail::ImageFeatures */
virtual void find(InputArray image, ImageFeatures &features) = 0;
/** @brief uses dynamic_cast to determine thread-safety
@return True, if it's possible to use the same finder instance in parallel, false otherwise
*/
bool isThreadSafe() const;
virtual void find(const Mat &image, ImageFeatures &features) = 0;
};
/** @brief SURF features finder.
@sa detail::FeaturesFinder, SURF
*/
class CV_EXPORTS SurfFeaturesFinder : public FeaturesFinder
{
public:
@ -130,241 +85,106 @@ public:
int num_octaves_descr = /*4*/3, int num_layers_descr = /*2*/4);
private:
void find(InputArray image, ImageFeatures &features) CV_OVERRIDE;
void find(const Mat &image, ImageFeatures &features);
Ptr<FeatureDetector> detector_;
Ptr<DescriptorExtractor> extractor_;
Ptr<Feature2D> surf;
};
/** @brief SIFT features finder.
@sa detail::FeaturesFinder, SIFT
*/
class CV_EXPORTS SiftFeaturesFinder : public FeaturesFinder
{
public:
SiftFeaturesFinder();
private:
void find(InputArray image, ImageFeatures &features) CV_OVERRIDE;
Ptr<Feature2D> sift;
};
/** @brief ORB features finder. :
@sa detail::FeaturesFinder, ORB
*/
class CV_EXPORTS OrbFeaturesFinder : public FeaturesFinder
{
public:
OrbFeaturesFinder(Size _grid_size = Size(3,1), int nfeatures=1500, float scaleFactor=1.3f, int nlevels=5);
private:
void find(InputArray image, ImageFeatures &features) CV_OVERRIDE;
void find(const Mat &image, ImageFeatures &features);
Ptr<ORB> orb;
Size grid_size;
};
/** @brief AKAZE features finder. :
@sa detail::FeaturesFinder, AKAZE
*/
class CV_EXPORTS AKAZEFeaturesFinder : public detail::FeaturesFinder
{
public:
AKAZEFeaturesFinder(int descriptor_type = AKAZE::DESCRIPTOR_MLDB,
int descriptor_size = 0,
int descriptor_channels = 3,
float threshold = 0.001f,
int nOctaves = 4,
int nOctaveLayers = 4,
int diffusivity = KAZE::DIFF_PM_G2);
private:
void find(InputArray image, ImageFeatures &features) CV_OVERRIDE;
Ptr<AKAZE> akaze;
};
#ifdef HAVE_OPENCV_XFEATURES2D
#if defined(HAVE_OPENCV_NONFREE)
class CV_EXPORTS SurfFeaturesFinderGpu : public FeaturesFinder
{
public:
SurfFeaturesFinderGpu(double hess_thresh = 300., int num_octaves = 3, int num_layers = 4,
int num_octaves_descr = 4, int num_layers_descr = 2);
void collectGarbage() CV_OVERRIDE;
void collectGarbage();
private:
void find(InputArray image, ImageFeatures &features) CV_OVERRIDE;
void find(const Mat &image, ImageFeatures &features);
cuda::GpuMat image_;
cuda::GpuMat gray_image_;
cuda::SURF_CUDA surf_;
cuda::GpuMat keypoints_;
cuda::GpuMat descriptors_;
gpu::GpuMat image_;
gpu::GpuMat gray_image_;
gpu::SURF_GPU surf_;
gpu::GpuMat keypoints_;
gpu::GpuMat descriptors_;
int num_octaves_, num_layers_;
int num_octaves_descr_, num_layers_descr_;
};
#endif
/** @brief Structure containing information about matches between two images.
It's assumed that there is a transformation between those images. Transformation may be
homography or affine transformation based on selected matcher.
@sa detail::FeaturesMatcher
*/
struct CV_EXPORTS MatchesInfo
{
MatchesInfo();
MatchesInfo(const MatchesInfo &other);
MatchesInfo& operator =(const MatchesInfo &other);
const MatchesInfo& operator =(const MatchesInfo &other);
int src_img_idx, dst_img_idx; //!< Images indices (optional)
int src_img_idx, dst_img_idx; // Images indices (optional)
std::vector<DMatch> matches;
std::vector<uchar> inliers_mask; //!< Geometrically consistent matches mask
int num_inliers; //!< Number of geometrically consistent matches
Mat H; //!< Estimated transformation
double confidence; //!< Confidence two images are from the same panorama
std::vector<uchar> inliers_mask; // Geometrically consistent matches mask
int num_inliers; // Number of geometrically consistent matches
Mat H; // Estimated homography
double confidence; // Confidence two images are from the same panorama
};
/** @brief Feature matchers base class. */
class CV_EXPORTS FeaturesMatcher
{
public:
virtual ~FeaturesMatcher() {}
/** @overload
@param features1 First image features
@param features2 Second image features
@param matches_info Found matches
*/
void operator ()(const ImageFeatures &features1, const ImageFeatures &features2,
MatchesInfo& matches_info) { match(features1, features2, matches_info); }
/** @brief Performs images matching.
@param features Features of the source images
@param pairwise_matches Found pairwise matches
@param mask Mask indicating which image pairs must be matched
The function is parallelized with the TBB library.
@sa detail::MatchesInfo
*/
void operator ()(const std::vector<ImageFeatures> &features, std::vector<MatchesInfo> &pairwise_matches,
const cv::UMat &mask = cv::UMat());
const cv::Mat &mask = cv::Mat());
/** @return True, if it's possible to use the same matcher instance in parallel, false otherwise
*/
bool isThreadSafe() const { return is_thread_safe_; }
/** @brief Frees unused memory allocated before if there is any.
*/
virtual void collectGarbage() {}
protected:
FeaturesMatcher(bool is_thread_safe = false) : is_thread_safe_(is_thread_safe) {}
/** @brief This method must implement matching logic in order to make the wrappers
detail::FeaturesMatcher::operator()_ work.
@param features1 first image features
@param features2 second image features
@param matches_info found matches
*/
virtual void match(const ImageFeatures &features1, const ImageFeatures &features2,
MatchesInfo& matches_info) = 0;
bool is_thread_safe_;
};
/** @brief Features matcher which finds two best matches for each feature and leaves the best one only if the
ratio between descriptor distances is greater than the threshold match_conf
@sa detail::FeaturesMatcher
*/
class CV_EXPORTS BestOf2NearestMatcher : public FeaturesMatcher
{
public:
/** @brief Constructs a "best of 2 nearest" matcher.
@param try_use_gpu Should try to use GPU or not
@param match_conf Match distances ration threshold
@param num_matches_thresh1 Minimum number of matches required for the 2D projective transform
estimation used in the inliers classification step
@param num_matches_thresh2 Minimum number of matches required for the 2D projective transform
re-estimation on inliers
*/
BestOf2NearestMatcher(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6,
int num_matches_thresh2 = 6);
void collectGarbage() CV_OVERRIDE;
void collectGarbage();
protected:
void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE;
void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info);
int num_matches_thresh1_;
int num_matches_thresh2_;
Ptr<FeaturesMatcher> impl_;
};
class CV_EXPORTS BestOf2NearestRangeMatcher : public BestOf2NearestMatcher
{
public:
BestOf2NearestRangeMatcher(int range_width = 5, bool try_use_gpu = false, float match_conf = 0.3f,
int num_matches_thresh1 = 6, int num_matches_thresh2 = 6);
void operator ()(const std::vector<ImageFeatures> &features, std::vector<MatchesInfo> &pairwise_matches,
const cv::UMat &mask = cv::UMat());
protected:
int range_width_;
};
/** @brief Features matcher similar to cv::detail::BestOf2NearestMatcher which
finds two best matches for each feature and leaves the best one only if the
ratio between descriptor distances is greater than the threshold match_conf.
Unlike cv::detail::BestOf2NearestMatcher this matcher uses affine
transformation (affine trasformation estimate will be placed in matches_info).
@sa cv::detail::FeaturesMatcher cv::detail::BestOf2NearestMatcher
*/
class CV_EXPORTS AffineBestOf2NearestMatcher : public BestOf2NearestMatcher
{
public:
/** @brief Constructs a "best of 2 nearest" matcher that expects affine trasformation
between images
@param full_affine whether to use full affine transformation with 6 degress of freedom or reduced
transformation with 4 degrees of freedom using only rotation, translation and uniform scaling
@param try_use_gpu Should try to use GPU or not
@param match_conf Match distances ration threshold
@param num_matches_thresh1 Minimum number of matches required for the 2D affine transform
estimation used in the inliers classification step
@sa cv::estimateAffine2D cv::estimateAffinePartial2D
*/
AffineBestOf2NearestMatcher(bool full_affine = false, bool try_use_gpu = false,
float match_conf = 0.3f, int num_matches_thresh1 = 6) :
BestOf2NearestMatcher(try_use_gpu, match_conf, num_matches_thresh1, num_matches_thresh1),
full_affine_(full_affine) {}
protected:
void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE;
bool full_affine_;
};
//! @} stitching_match
} // namespace detail
} // namespace cv
#endif // OPENCV_STITCHING_MATCHERS_HPP
#endif // __OPENCV_STITCHING_MATCHERS_HPP__

Some files were not shown because too many files have changed in this diff Show More