#pragma once

#include "cvcls.h"
//#include "..\incs\ocv\RectifyFishEye.h"
//#include "..\incs\sst\ucut.h"

//返回FALSE，表示结束。返回TRUE,表示继续
typedef BOOL (WINAPI *LD_LEARN_PROGRESS_FUNC)(HANDLE/*CLensDistortion**/, const RvImage /*image*/, int /*stepIndex*/, double /*percent： 0-1*/, void* /*hUserData*/);

//#define LCR_MIN_IMAGE_COUNT    10
//#define LCR_MIN_PATTERN_SIZE   2

//使用标定板的方法进行畸变矫正

class CVCLS_API CLensDistortion
{
public:
	CLensDistortion(void);
	virtual ~CLensDistortion(void);

	enum {
	    LD_THRES_AUTO =0,
		LD_THRES_MANUAL,
	};


	BOOL Learn( const RvImage image, BOOL* pCancelFlag);
	BOOL Rectify(RvImage image);

	BOOL Serialize(HANDLE hFile, BOOL bIn);

	BOOL IsValid(){ return m_bLearned; };
	
	int  GetId() { return m_nId; };
	int  GetRows()  { return m_nRows; };
	int  GetCols()  { return m_nCols; };
	double  GetSpace()     { return m_nSpace; };
	double  GetDiameter()  { return m_nPatternSize; };
	int  GetMatrixSize(){ return m_nMtxSize; };

	const RvPoint_f64* GetSourceMatrix();
	const RvPoint_f64* GetDestMatrix();

	double  GetScale(bool bRawScale ){ 
		if (!bRawScale) return m_nPixelsPerMm ;
		else return m_nRawScale;
	};
	 
	RvBox2D GetRectifiedBox();

	//二值图像
	void ReleaseBinary();

	//外部程序不可删除
	const RvImage GetBinary();

	void Reset();

public:
	float  m_nRatioThres;   //圆点的最小长宽比;
	float  m_nMinSizeToler; //最小尺寸允许偏差: 0 -1;
	float  m_nMaxSizeToler; //最大尺寸允许偏差: 0 -1;

	int    m_nThresType; //0 - 自动, 1- 简单阈值
	int    m_nThresValue;
	BOOL   m_bReverseBin;

	//临时变量，显示进程
	//BOOL*  m_pCancelFlag;
	//int   m_nTotal;
	//int   m_nCurIndex;
	LD_LEARN_PROGRESS_FUNC m_fnLearnProcess;
	void*  m_pUserData;
protected:

	BOOL  CheckIfNeedAbort(const RvImage image, int total, int& step, BOOL* pCancelFlag);

	RvImage    m_image;
	 

	//标定参数
	RvPoint_f64* m_pSrcMtx;
	RvPoint_f64* m_pDstMtx;
	int          m_nMtxSize;
	RvBox2D      m_rectifiedBox;
	RvPoint_f64* m_pRectifyMtx;  //矫正系数
	
	//标定板模板特征
	int     m_nId;
	double  m_nPatternSize; //圆点大小:毫米
	double  m_nSpace;       //圆点距离:毫米
	int     m_nRows, m_nCols;

	//图像宽度和高度
	int    m_nWidth, m_nHeight;
	double m_nPixelsPerMm; //每毫米多少像素,学习后的比例。
	double m_nRawScale;    //每毫米多少像素.(非校正状态下)

	BOOL  m_bLearned;

private:
	void ReleaseMatrix();
	BOOL GenPairPos(double dosDist);
	BOOL GenRectifyMatrix(BOOL* pCancelFlag);

	//BOOL TransformDotToPos(RvSequence seq,   float minSpaceY,   int& rows, int& cols);
};

