add_definitions(-DJAS_WIN_MSVC_BUILD)
endif()
-ocv_warnings_disable(CMAKE_C_FLAGS -Wno-implicit-function-declaration -Wno-uninitialized -Wmissing-prototypes -Wmissing-declarations -Wunused)
+ocv_warnings_disable(CMAKE_C_FLAGS -Wno-implicit-function-declaration -Wno-uninitialized -Wmissing-prototypes -Wmissing-declarations -Wunused -Wshadow
+ /wd4013 /wd4018 /wd4715 /wd4244 /wd4101 /wd4267)
if(UNIX)
if(CMAKE_COMPILER_IS_GNUCXX OR CV_ICC)
list(APPEND lib_srcs tif_win32.c)
endif(WIN32)
-ocv_warnings_disable(CMAKE_C_FLAGS -Wno-unused-but-set-variable -Wmissing-prototypes -Wmissing-declarations -Wundef -Wcast-align)
-ocv_warnings_disable(CMAKE_CXX_FLAGS -Wmissing-declarations)
+ocv_warnings_disable(CMAKE_C_FLAGS -Wno-unused-but-set-variable -Wmissing-prototypes -Wmissing-declarations -Wundef
+ -Wcast-align -Wshadow -Wno-maybe-uninitialized -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast)
+ocv_warnings_disable(CMAKE_CXX_FLAGS -Wmissing-declarations /wd4100 /wd4244 /wd4706 /wd4127 /wd4701 /wd4018 /wd4267 /wd4306 /wd4305 /wd4312 /wd4311)
if(UNIX AND (CMAKE_COMPILER_IS_GNUCXX OR CV_ICC))
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
#endif
#ifndef _FILE_OFFSET_BITS
-# define _FILE_OFFSET_BITS
+# define _FILE_OFFSET_BITS 0
#endif
#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
{
char xml_path[1024];
int len = (int)strlen(dirname);
- CvHaarClassifierCascade* cascade = 0;
+ CvHaarClassifierCascade* cascade1 = 0;
strcpy( xml_path, dirname );
if( xml_path[len-1] == '\\' || xml_path[len-1] == '/' )
len--;
strcpy( xml_path + len, ".xml" );
- cascade = cvLoadHaarClassifierCascade( dirname, cvSize(winwidth,winheight) );
- if( cascade )
- cvSave( xml_path, cascade );
- cvReleaseHaarClassifierCascade( &cascade );
+ cascade1 = cvLoadHaarClassifierCascade( dirname, cvSize(winwidth,winheight) );
+ if( cascade1 )
+ cvSave( xml_path, cascade1 );
+ cvReleaseHaarClassifierCascade( &cascade1 );
}
}
else
{
CvTreeCascadeNode* single_cluster;
CvTreeCascadeNode* multiple_clusters;
- CvSplit* cur_split;
int single_num;
icvSetNumSamples( training_data, poscount + negcount );
} /* try different number of clusters */
cvReleaseMat( &vals );
- CV_CALL( cur_split = (CvSplit*) cvAlloc( sizeof( *cur_split ) ) );
- CV_ZERO_OBJ( cur_split );
+ CvSplit* curSplit;
+ CV_CALL( curSplit = (CvSplit*) cvAlloc( sizeof( *curSplit ) ) );
+ CV_ZERO_OBJ( curSplit );
- if( last_split ) last_split->next = cur_split;
- else first_split = cur_split;
- last_split = cur_split;
+ if( last_split ) last_split->next = curSplit;
+ else first_split = curSplit;
+ last_split = curSplit;
- cur_split->single_cluster = single_cluster;
- cur_split->multiple_clusters = multiple_clusters;
- cur_split->num_clusters = best_clusters;
- cur_split->parent = parent;
- cur_split->single_multiple_ratio = (float) single_num / best_num;
+ curSplit->single_cluster = single_cluster;
+ curSplit->multiple_clusters = multiple_clusters;
+ curSplit->num_clusters = best_clusters;
+ curSplit->parent = parent;
+ curSplit->single_multiple_ratio = (float) single_num / best_num;
}
if( parent ) parent = parent->next_same_level;
int i00, i10, i01, i11;
i00 = i10 = i01 = i11 = (int) fill_value;
- double i = fill_value;
-
/* linear interpolation using 2x2 neighborhood */
if( isrc_x >= 0 && isrc_x <= src_size.width &&
isrc_y >= 0 && isrc_y <= src_size.height )
double i0 = i00 + (i10 - i00)*delta_x;
double i1 = i01 + (i11 - i01)*delta_x;
- i = i0 + (i1 - i0)*delta_y;
- ((uchar*)(dst_data + y * dst_step))[x] = (uchar) i;
+ ((uchar*)(dst_data + y * dst_step))[x] = (uchar) (i0 + (i1 - i0)*delta_y);
}
x_min += k_left;
x_max += k_right;
totaltime = 0.0;
if( info != NULL )
{
- int x, y, width, height;
+ int x, y;
IplImage* img;
int hits, missed, falseAlarms;
int totalHits, totalMissed, totalFalseAlarms;
ref = (ObjectPos*) cvAlloc( refcount * sizeof( *ref ) );
for( i = 0; i < refcount; i++ )
{
- error = (fscanf( info, "%d %d %d %d", &x, &y, &width, &height ) != 4);
+ int w, h;
+ error = (fscanf( info, "%d %d %d %d", &x, &y, &w, &h ) != 4);
if( error ) break;
- ref[i].x = 0.5F * width + x;
- ref[i].y = 0.5F * height + y;
- ref[i].width = sqrtf( 0.5F * (width * width + height * height) );
+ ref[i].x = 0.5F * w + x;
+ ref[i].y = 0.5F * h + y;
+ ref[i].width = sqrtf( 0.5F * (w * w + h * h) );
ref[i].found = 0;
ref[i].neghbors = 0;
}
endif()
if(MSVC)
+ string(REGEX REPLACE "^ *| * $" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
+ string(REGEX REPLACE "^ *| * $" "" CMAKE_CXX_FLAGS_INIT "${CMAKE_CXX_FLAGS_INIT}")
if(CMAKE_CXX_FLAGS STREQUAL CMAKE_CXX_FLAGS_INIT)
# override cmake default exception handling option
string(REPLACE "/EHsc" "/EHa" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
add_extra_compiler_option(-Wundef)
add_extra_compiler_option(-Winit-self)
add_extra_compiler_option(-Wpointer-arith)
- #add_extra_compiler_option(-Wcast-align)
- #add_extra_compiler_option(-Wstrict-aliasing=2)
- #add_extra_compiler_option(-Wshadow)
- #add_extra_compiler_option(-Wno-unnamed-type-template-args)
+ add_extra_compiler_option(-Wshadow)
+
+ if(ENABLE_NOISY_WARNINGS)
+ add_extra_compiler_option(-Wcast-align)
+ add_extra_compiler_option(-Wstrict-aliasing=2)
+ else()
+ add_extra_compiler_option(-Wno-narrowing)
+ add_extra_compiler_option(-Wno-delete-non-virtual-dtor)
+ #add_extra_compiler_option(-Wno-unnamed-type-template-args)
+ endif()
# The -Wno-long-long is required in 64bit systems when including sytem headers.
if(X86_64)
string(REPLACE "/W3" "/W4" CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
string(REPLACE "/W3" "/W4" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
+ if(NOT ENABLE_NOISY_WARNINGS AND MSVC_VERSION EQUAL 1400)
+ ocv_warnings_disable(CMAKE_CXX_FLAGS /wd4510 /wd4610 /wd4312 /wd4201 /wd4244 /wd4328 /wd4267)
+ endif()
+
# allow extern "C" functions throw exceptions
foreach(flags CMAKE_C_FLAGS CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG)
string(REPLACE "/EHsc-" "/EHs" ${flags} "${${flags}}")
# Try to find the XIMEA API path in registry.
GET_FILENAME_COMPONENT(XIMEA_PATH "[HKEY_CURRENT_USER\\Software\\XIMEA\\CamSupport\\API;Path]" ABSOLUTE)
- if(XIMEA_PATH)
+ if(EXISTS XIMEA_PATH)
set(XIMEA_FOUND 1)
# set LIB folders
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
{
float X0=*(localLuminancePTR++)*_localLuminanceFactor+_localLuminanceAddon;
// TODO : the following line can lead to a divide by zero ! A small offset is added, take care if the offset is too large in case of High Dynamic Range images which can use very small values...
- *(outputFramePTR++) = (_maxInputValue+X0)**inputFramePTR/(*inputFramePTR +X0+0.00000000001);
+ *(outputFramePTR++) = (_maxInputValue+X0)**inputFramePTR/(*inputFramePTR +X0+0.00000000001f);
//std::cout<<"BasicRetinaFilter::inputFrame[IDpixel]=%f, X0=%f, outputFrame[IDpixel]=%f\n", inputFrame[IDpixel], X0, outputFrame[IDpixel]);
}
}
#include "precomp.hpp"
#include <iostream>
-#if defined _MSC_VER && _MSC_VER >= 1400
+#ifdef _MSC_VER
#pragma warning( disable: 4305 )
#endif
{
using std::set;
-
+
// Reads a sequence from a FileNode::SEQ with type _Tp into a result vector.
template<typename _Tp>
inline void readFileNodeList(const FileNode& fn, vector<_Tp>& result) {
}
fs << "]";
}
-
+
static Mat asRowMatrix(InputArrayOfArrays src, int rtype, double alpha=1, double beta=0) {
// make sure the input data is a vector of matrices or vector of vector
if(src.kind() != _InputArray::STD_VECTOR_MAT && src.kind() != _InputArray::STD_VECTOR_VECTOR) {
// dimensionality of (reshaped) samples
size_t d = src.getMat(0).total();
// create data matrix
- Mat data(n, d, rtype);
+ Mat data((int)n, (int)d, rtype);
// now copy data
for(unsigned int i = 0; i < n; i++) {
// make sure data can be reshaped, throw exception if not!
return data;
}
-
+
// Removes duplicate elements in a given vector.
template<typename _Tp>
inline vector<_Tp> remove_dups(const vector<_Tp>& src) {
return elems;
}
-
+
// Turk, M., and Pentland, A. "Eigenfaces for recognition.". Journal of
// Cognitive Neuroscience 3 (1991), 71–86.
class Eigenfaces : public FaceRecognizer
// See FaceRecognizer::save.
void save(FileStorage& fs) const;
-
+
AlgorithmInfo* info() const;
};
-
+
// Belhumeur, P. N., Hespanha, J., and Kriegman, D. "Eigenfaces vs. Fisher-
// faces: Recognition using class specific linear projection.". IEEE
// Transactions on Pattern Analysis and Machine Intelligence 19, 7 (1997),
//
// radius, neighbors are used in the local binary patterns creation.
// grid_x, grid_y control the grid size of the spatial histograms.
- LBPH(int radius=1, int neighbors=8,
- int grid_x=8, int grid_y=8,
+ LBPH(int radius_=1, int neighbors_=8,
+ int gridx=8, int gridy=8,
double threshold = DBL_MAX) :
- _grid_x(grid_x),
- _grid_y(grid_y),
- _radius(radius),
- _neighbors(neighbors),
+ _grid_x(gridx),
+ _grid_y(gridy),
+ _radius(radius_),
+ _neighbors(neighbors_),
_threshold(threshold) {}
// Initializes and computes this LBPH Model. The current implementation is
// (grid_x=8), (grid_y=8) controls the grid size of the spatial histograms.
LBPH(InputArray src,
InputArray labels,
- int radius=1, int neighbors=8,
- int grid_x=8, int grid_y=8,
+ int radius_=1, int neighbors_=8,
+ int gridx=8, int gridy=8,
double threshold = DBL_MAX) :
- _grid_x(grid_x),
- _grid_y(grid_y),
- _radius(radius),
- _neighbors(neighbors),
+ _grid_x(gridx),
+ _grid_y(gridy),
+ _radius(radius_),
+ _neighbors(neighbors_),
_threshold(threshold) {
train(src, labels);
}
double dist = norm(_projections[sampleIdx], q, NORM_L2);
if((dist < minDist) && (dist < _threshold)) {
minDist = dist;
- minClass = _labels.at<int>(sampleIdx);
+ minClass = _labels.at<int>((int)sampleIdx);
}
}
}
double dist = norm(_projections[sampleIdx], q, NORM_L2);
if((dist < minDist) && (dist < _threshold)) {
minDist = dist;
- minClass = _labels.at<int>(sampleIdx);
+ minClass = _labels.at<int>((int)sampleIdx);
}
}
}
return Mat();
}
-
+
static Mat spatial_histogram(InputArray _src, int numPatterns,
- int grid_x, int grid_y, bool normed)
+ int grid_x, int grid_y, bool /*normed*/)
{
Mat src = _src.getMat();
// calculate LBP patch size
elbp(src, dst, radius, neighbors);
return dst;
}
-
+
void LBPH::load(const FileStorage& fs) {
fs["radius"] >> _radius;
fs["neighbors"] >> _neighbors;
double dist = compareHist(_histograms[sampleIdx], query, CV_COMP_CHISQR);
if((dist < minDist) && (dist < _threshold)) {
minDist = dist;
- minClass = _labels.at<int>(sampleIdx);
+ minClass = _labels.at<int>((int)sampleIdx);
}
}
}
return label;
}
-
+
Ptr<FaceRecognizer> createEigenFaceRecognizer(int num_components, double threshold)
{
return new Eigenfaces(num_components, threshold);
}
-
+
Ptr<FaceRecognizer> createFisherFaceRecognizer(int num_components, double threshold)
{
return new Fisherfaces(num_components, threshold);
}
-
+
Ptr<FaceRecognizer> createLBPHFaceRecognizer(int radius, int neighbors,
int grid_x, int grid_y, double threshold)
{
return new LBPH(radius, neighbors, grid_x, grid_y, threshold);
}
-
+
CV_INIT_ALGORITHM(Eigenfaces, "FaceRecognizer.Eigenfaces",
obj.info()->addParam(obj, "ncomponents", obj._num_components);
obj.info()->addParam(obj, "threshold", obj._threshold);
obj.info()->addParam(obj, "labels", obj._labels, true);
obj.info()->addParam(obj, "eigenvectors", obj._eigenvectors, true);
obj.info()->addParam(obj, "eigenvalues", obj._eigenvalues, true);
- obj.info()->addParam(obj, "mean", obj._mean, true));
-
+ obj.info()->addParam(obj, "mean", obj._mean, true));
+
CV_INIT_ALGORITHM(LBPH, "FaceRecognizer.LBPH",
obj.info()->addParam(obj, "radius", obj._radius);
obj.info()->addParam(obj, "neighbors", obj._neighbors);
obj.info()->addParam(obj, "threshold", obj._threshold);
obj.info()->addParam(obj, "histograms", obj._histograms, true);
obj.info()->addParam(obj, "labels", obj._labels, true));
-
+
bool initModule_contrib()
{
Ptr<Algorithm> efaces = createEigenfaces(), ffaces = createFisherfaces(), lbph = createLBPH();
// dimensionality of (reshaped) samples
size_t d = src.getMat(0).total();
// create data matrix
- Mat data(n, d, rtype);
+ Mat data((int)n, (int)d, rtype);
// now copy data
- for(size_t i = 0; i < n; i++) {
+ for(int i = 0; i < (int)n; i++) {
// make sure data can be reshaped, throw exception if not!
if(src.getMat(i).total() != d) {
- string error_message = format("Wrong number of elements in matrix #%d! Expected %d was %d.", i, d, src.getMat(i).total());
+ string error_message = format("Wrong number of elements in matrix #%d! Expected %d was %d.", i, (int)d, (int)src.getMat(i).total());
CV_Error(CV_StsBadArg, error_message);
}
// get a hold of the current row
vector<int> mapped_labels(labels.size());
vector<int> num2label = remove_dups(labels);
map<int, int> label2num;
- for (size_t i = 0; i < num2label.size(); i++)
+ for (int i = 0; i < (int)num2label.size(); i++)
label2num[num2label[i]] = i;
for (size_t i = 0; i < labels.size(); i++)
mapped_labels[i] = label2num[labels[i]];
int N = data.rows;
int D = data.cols;
// number of unique labels
- int C = num2label.size();
+ int C = (int)num2label.size();
// we can't do a LDA on one class, what do you
// want to separate from each other then?
if(C == 1) {
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
subset.resize(setSize);
for(size_t i = 0; i < setSize; ++i)
{
- int pos = rnd.next() % left.size();
+ int pos = rnd.next() % (int)left.size();
subset[i] = (int)left[pos];
left[pos] = left.back();
#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
+#pragma warning( disable: 4127 ) //conditional expression is constant
+#endif
+
namespace cv
{
#if CV_ENABLE_UNROLLED
for(; i <= n - 4; i += 4 )
{
- _AccTp v0 = a[i] - b[i], v1 = a[i+1] - b[i+1], v2 = a[i+2] - b[i+2], v3 = a[i+3] - b[i+3];
+ _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]);
s += v0*v0 + v1*v1 + v2*v2 + v3*v3;
}
#endif
for( ; i < n; i++ )
{
- _AccTp v = (_AccTp)(a[i] - b[i]);
+ _AccTp v = _AccTp(a[i] - b[i]);
s += v*v;
}
return s;
#if CV_ENABLE_UNROLLED
for(; i <= n - 4; i += 4 )
{
- _AccTp v0 = a[i] - b[i], v1 = a[i+1] - b[i+1], v2 = a[i+2] - b[i+2], v3 = a[i+3] - b[i+3];
+ _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]);
s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3);
}
#endif
for( ; i < n; i++ )
{
- _AccTp v = (_AccTp)(a[i] - b[i]);
+ _AccTp v = _AccTp(a[i] - b[i]);
s += std::abs(v);
}
return s;
# define CV_ENABLE_UNROLLED 1
#endif
-#if (defined _M_X64 && _MSC_VER >= 1400) || (__GNUC__ >= 4 && defined __x86_64__)
+#if (defined _M_X64 && defined _MSC_VER && _MSC_VER >= 1400) || (__GNUC__ >= 4 && defined __x86_64__)
# if defined WIN32
# include <intrin.h>
# endif
// On Win64 optimized versions of DFT and DCT fail the tests (fixed in VS2010)
#if defined _MSC_VER && !defined CV_ICC && defined _M_X64 && _MSC_VER < 1600
-#pragma optimize("", off)
-#pragma warning( disable : 4748 )
+# pragma optimize("", off)
+# pragma warning(disable: 4748)
#endif
/****************************************************************************************\
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
- // disable warnings related to inline functions
- #pragma warning( disable: 4251 4711 4710 4514 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
dst.at<double>(0,0) = cvtest::norm(src[0], normType, mask);
dst.at<double>(0,1) = cvtest::norm(src[0], src[1], normType, mask);
}
- void generateScalars(int, RNG& rng)
+ void generateScalars(int, RNG& /*rng*/)
{
}
double getMaxErr(int)
event = "End of procedure";
break;
default:
-#if defined _MSC_VER && _MSC_VER >= 1200
- #pragma warning( push )
- #pragma warning( disable : 4127 )
-#endif
CV_TS_SEQ_CHECK_CONDITION( 0, "Invalid code appeared during graph scan" );
-#if defined _MSC_VER && _MSC_VER >= 1200
- #pragma warning( pop )
-#endif
}
ts->printf( cvtest::TS::LOG, "%s", event );
private:
const Mat mask;
+ MaskPredicate& operator=(const MaskPredicate&);
};
void KeyPointsFilter::runByPixelsMask( vector<KeyPoint>& keypoints, const Mat& mask )
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4512 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
*************************************************************************/
#include "precomp.hpp"
-
-#ifdef _MSC_VER\r
-#pragma warning(disable: 4996)\r
-#endif
#include "opencv2/flann/flann.hpp"
namespace cvflann
#include <cstdarg>\r
#include <sstream>\r
\r
-#ifdef _MSC_VER\r
-#pragma warning(disable: 4996)\r
-#endif\r
-\r
#ifdef HAVE_CVCONFIG_H\r
# include "cvconfig.h"\r
#endif\r
{\r
public:\r
explicit GoodFeaturesToTrackDetector_GPU(int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 0.0,\r
- int blockSize = 3, bool useHarrisDetector = false, double harrisK = 0.04)\r
- {\r
- this->maxCorners = maxCorners;\r
- this->qualityLevel = qualityLevel;\r
- this->minDistance = minDistance;\r
- this->blockSize = blockSize;\r
- this->useHarrisDetector = useHarrisDetector;\r
- this->harrisK = harrisK;\r
- }\r
+ int blockSize = 3, bool useHarrisDetector = false, double harrisK = 0.04);\r
\r
//! return 1 rows matrix with CV_32FC2 type\r
void operator ()(const GpuMat& image, GpuMat& corners, const GpuMat& mask = GpuMat());\r
GpuMat tmpCorners_;\r
};\r
\r
+inline GoodFeaturesToTrackDetector_GPU::GoodFeaturesToTrackDetector_GPU(int maxCorners_, double qualityLevel_, double minDistance_,\r
+ int blockSize_, bool useHarrisDetector_, double harrisK_)\r
+{\r
+ maxCorners = maxCorners_;\r
+ qualityLevel = qualityLevel_;\r
+ minDistance = minDistance_;\r
+ blockSize = blockSize_;\r
+ useHarrisDetector = useHarrisDetector_;\r
+ harrisK = harrisK_;\r
+}\r
+\r
+\r
class CV_EXPORTS PyrLKOpticalFlow\r
{\r
public:\r
bool cv::gpu::VideoReader_GPU::isOpened() const { return false; }\r
void cv::gpu::VideoReader_GPU::close() { }\r
bool cv::gpu::VideoReader_GPU::read(GpuMat&) { throw_nogpu(); return false; }\r
-cv::gpu::VideoReader_GPU::FormatInfo cv::gpu::VideoReader_GPU::format() const { throw_nogpu(); FormatInfo format = {MPEG1,Monochrome,0,0}; return format; }\r
+cv::gpu::VideoReader_GPU::FormatInfo cv::gpu::VideoReader_GPU::format() const { throw_nogpu(); FormatInfo format_ = {MPEG1,Monochrome,0,0}; return format_; }\r
bool cv::gpu::VideoReader_GPU::VideoSource::parseVideoData(const unsigned char*, size_t, bool) { throw_nogpu(); return false; }\r
void cv::gpu::VideoReader_GPU::dumpFormat(std::ostream&) { throw_nogpu(); }\r
\r
bool useRoi;\r
\r
cv::Mat img;\r
- cv::Mat kernel;\r
\r
virtual void SetUp()\r
{\r
cv::gpu::DeviceInfo devInfo;\r
\r
cv::Size size;\r
- cv::Mat src;\r
- cv::Mat hist_gold;\r
\r
virtual void SetUp()\r
{\r
\r
cv::gpu::GpuMat dst;\r
cv::gpu::equalizeHist(loadMat(src), dst);\r
- \r
+\r
cv::Mat dst_gold;\r
cv::equalizeHist(src, dst_gold);\r
\r
cv::gpu::DeviceInfo devInfo;\r
cv::Size size;\r
\r
- cv::Mat src;\r
-\r
virtual void SetUp()\r
{\r
devInfo = GET_PARAM(0);\r
bool useL2gradient;\r
bool useRoi;\r
\r
- cv::Mat edges_gold;\r
-\r
virtual void SetUp()\r
{\r
devInfo = GET_PARAM(0);\r
else\r
img_template = readImage("meanshift/con_result_CC1X.png");\r
ASSERT_FALSE(img_template.empty());\r
- \r
+\r
cv::gpu::GpuMat d_dst;\r
cv::gpu::meanShiftFiltering(loadMat(img), d_dst, spatialRad, colorRad);\r
\r
cv::gpu::meanShiftProc(loadMat(img), rmap, spmap, spatialRad, colorRad);\r
\r
ASSERT_EQ(CV_8UC4, rmap.type());\r
- \r
+\r
EXPECT_MAT_NEAR(rmap_filtered, rmap, 0.0);\r
EXPECT_MAT_NEAR(spmap_template, spmap, 0.0);\r
}\r
int ksize;\r
bool ccorr;\r
\r
- cv::Mat src;\r
- cv::Mat kernel;\r
-\r
- cv::Mat dst_gold;\r
-\r
virtual void SetUp()\r
{\r
devInfo = GET_PARAM(0);\r
\r
cv::gpu::GpuMat dst;\r
cv::gpu::convolve(loadMat(src), loadMat(kernel), dst, ccorr);\r
- \r
+\r
cv::Mat dst_gold;\r
convolveDFT(src, kernel, dst_gold, ccorr);\r
\r
int method;\r
\r
int n, m, h, w;\r
- cv::Mat image, templ;\r
-\r
- cv::Mat dst_gold;\r
\r
virtual void SetUp()\r
{\r
\r
cv::gpu::GpuMat dst;\r
cv::gpu::cornerHarris(loadMat(src), dst, blockSize, apertureSize, k, borderType);\r
- \r
+\r
cv::Mat dst_gold;\r
cv::cornerHarris(src, dst_gold, blockSize, apertureSize, k, borderType);\r
\r
}\r
\r
#ifdef DUMP\r
- void dump(const cv::Mat& block_hists, const std::vector<cv::Point>& locations)\r
+ void dump(const cv::Mat& blockHists, const std::vector<cv::Point>& locations)\r
{\r
- f.write((char*)&block_hists.rows, sizeof(block_hists.rows));\r
- f.write((char*)&block_hists.cols, sizeof(block_hists.cols));\r
+ f.write((char*)&blockHists.rows, sizeof(blockHists.rows));\r
+ f.write((char*)&blockHists.cols, sizeof(blockHists.cols));\r
\r
- for (int i = 0; i < block_hists.rows; ++i)\r
+ for (int i = 0; i < blockHists.rows; ++i)\r
{\r
- for (int j = 0; j < block_hists.cols; ++j)\r
+ for (int j = 0; j < blockHists.cols; ++j)\r
{\r
- float val = block_hists.at<float>(i, j);\r
+ float val = blockHists.at<float>(i, j);\r
f.write((char*)&val, sizeof(val));\r
}\r
}\r
f.write((char*)&locations[i], sizeof(locations[i]));\r
}\r
#else\r
- void compare(const cv::Mat& block_hists, const std::vector<cv::Point>& locations)\r
+ void compare(const cv::Mat& blockHists, const std::vector<cv::Point>& locations)\r
{\r
int rows, cols;\r
f.read((char*)&rows, sizeof(rows));\r
f.read((char*)&cols, sizeof(cols));\r
- ASSERT_EQ(rows, block_hists.rows);\r
- ASSERT_EQ(cols, block_hists.cols);\r
+ ASSERT_EQ(rows, blockHists.rows);\r
+ ASSERT_EQ(cols, blockHists.cols);\r
\r
- for (int i = 0; i < block_hists.rows; ++i)\r
+ for (int i = 0; i < blockHists.rows; ++i)\r
{\r
- for (int j = 0; j < block_hists.cols; ++j)\r
+ for (int j = 0; j < blockHists.cols; ++j)\r
{\r
float val;\r
f.read((char*)&val, sizeof(val));\r
- ASSERT_NEAR(val, block_hists.at<float>(i, j), 1e-3);\r
+ ASSERT_NEAR(val, blockHists.at<float>(i, j), 1e-3);\r
}\r
}\r
\r
endif()
include(${QT_USE_FILE})
+ if(QT_INCLUDE_DIR)
+ ocv_include_directories(${QT_INCLUDE_DIR})
+ endif()
+
QT4_ADD_RESOURCES(_RCC_OUTFILES src/window_QT.qrc)
QT4_WRAP_CPP(_MOC_OUTFILES src/window_QT.h)
#include "precomp.hpp"
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4711 )
-#endif
-
#if defined _M_X64 && defined _MSC_VER && !defined CV_ICC
#pragma optimize("",off)
-#pragma warning( disable: 4748 )
+#pragma warning(disable: 4748)
#endif
namespace cv
#include "precomp.hpp"
#if defined _MSC_VER && _MSC_VER >= 100
+//'sprintf': name was marked as #pragma deprecated
#pragma warning(disable: 4995)
#endif
//
// ----------------------------------------------------------------------
-bool videoInput::setupDevice(int deviceNumber, int connection){
+bool videoInput::setupDevice(int deviceNumber, int _connection){
if(deviceNumber >= VI_MAX_CAMERAS || VDList[deviceNumber]->readyToCapture) return false;
- setPhyCon(deviceNumber, connection);
+ setPhyCon(deviceNumber, _connection);
if(setup(deviceNumber))return true;
return false;
}
//
// ----------------------------------------------------------------------
-bool videoInput::setupDevice(int deviceNumber, int w, int h, int connection){
+bool videoInput::setupDevice(int deviceNumber, int w, int h, int _connection){
if(deviceNumber >= VI_MAX_CAMERAS || VDList[deviceNumber]->readyToCapture) return false;
setAttemptCaptureSize(deviceNumber,w,h);
- setPhyCon(deviceNumber, connection);
+ setPhyCon(deviceNumber, _connection);
if(setup(deviceNumber))return true;
return false;
}
return hr;
}
-HRESULT videoInput::ShowStreamPropertyPages(IAMStreamConfig *pStream){
+HRESULT videoInput::ShowStreamPropertyPages(IAMStreamConfig * /*pStream*/){
HRESULT hr = NOERROR;
return hr;
LONG lInpin, lOutpin;
hr = Crossbar->get_PinCounts(&lOutpin , &lInpin);
- BOOL IPin=TRUE; LONG pIndex=0 , pRIndex=0 , pType=0;
+ BOOL iPin=TRUE; LONG pIndex=0 , pRIndex=0 , pType=0;
while( pIndex < lInpin)
{
- hr = Crossbar->get_CrossbarPinInfo( IPin , pIndex , &pRIndex , &pType);
+ hr = Crossbar->get_CrossbarPinInfo( iPin , pIndex , &pRIndex , &pType);
if( pType == conType){
if(verbose)printf("SETUP: Found Physical Interface");
#include <vfw.h>
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4711 )
-#endif
-
#ifdef __GNUC__
#define WM_CAP_FIRSTA (WM_USER)
#define capSendMessage(hwnd,m,w,l) (IsWindow(hwnd)?SendMessage(hwnd,m,w,l):0)
#endif
-#if defined _M_X64
+#if defined _M_X64 && defined _MSC_VER
#pragma optimize("",off)
#pragma warning(disable: 4748)
#endif
{
size.width = aviinfo.rcFrame.right - aviinfo.rcFrame.left;
size.height = aviinfo.rcFrame.bottom - aviinfo.rcFrame.top;
- BITMAPINFOHEADER bmih = icvBitmapHeader( size.width, size.height, 24 );
+ BITMAPINFOHEADER bmihdr = icvBitmapHeader( size.width, size.height, 24 );
film_range.start_index = (int)aviinfo.dwStart;
film_range.end_index = film_range.start_index + (int)aviinfo.dwLength;
fps = (double)aviinfo.dwRate/aviinfo.dwScale;
pos = film_range.start_index;
- getframe = AVIStreamGetFrameOpen( avistream, &bmih );
+ getframe = AVIStreamGetFrameOpen( avistream, &bmihdr );
if( getframe != 0 )
return true;
}
#ifdef HAVE_JPEG
#ifdef _MSC_VER
-#pragma warning(disable: 4324 4611)
+//interaction between '_setjmp' and C++ object destruction is non-portable
+#pragma warning(disable: 4611)
#endif
#include <stdio.h>
namespace cv
{
+#ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable:4324) //structure was padded due to __declspec(align())
+#endif
struct JpegErrorMgr
{
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
+#ifdef _MSC_VER
+# pragma warning(pop)
+#endif
struct JpegSource
{
#include "grfmt_png.hpp"
#if defined _MSC_VER && _MSC_VER >= 1200
- // disable warnings related to _setjmp
+ // interaction between '_setjmp' and C++ object destruction is non-portable
#pragma warning( disable: 4611 )
#endif
#ifndef __HIGHGUI_H_
#define __HIGHGUI_H_
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 )
-#endif
-
#include "cvconfig.h"
#include "opencv2/highgui/highgui.hpp"
// CvTrackbar\r
\r
\r
-CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* data)\r
+CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)\r
{\r
callback = NULL;\r
callback2 = on_change;\r
userdata = data;\r
\r
- create(arg, name, value, count);\r
+ create(arg, name, value, _count);\r
}\r
\r
\r
-CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int count, CvTrackbarCallback on_change)\r
+CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)\r
{\r
callback = on_change;\r
callback2 = NULL;\r
userdata = NULL;\r
\r
- create(arg, name, value, count);\r
+ create(arg, name, value, _count);\r
}\r
\r
\r
-void CvTrackbar::create(CvWindow* arg, QString name, int* value, int count)\r
+void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)\r
{\r
type = type_CvTrackbar;\r
myparent = arg;\r
slider = new QSlider(Qt::Horizontal);\r
slider->setFocusPolicy(Qt::StrongFocus);\r
slider->setMinimum(0);\r
- slider->setMaximum(count);\r
+ slider->setMaximum(_count);\r
slider->setPageStep(5);\r
slider->setValue(*value);\r
slider->setTickPosition(QSlider::TicksBelow);\r
\r
\r
//here CvWinProperties class\r
-CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* parent)\r
+CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)\r
{\r
//setParent(parent);\r
type = type_CvWinProperties;\r
}\r
\r
\r
-void CvWinProperties::showEvent(QShowEvent* event)\r
+void CvWinProperties::showEvent(QShowEvent* evnt)\r
{\r
//why -1,-1 ?: do this trick because the first time the code is run,\r
//no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).\r
if (mypos.x() >= 0)\r
{\r
move(mypos);\r
- event->accept();\r
+ evnt->accept();\r
}\r
else\r
{\r
- event->ignore();\r
+ evnt->ignore();\r
}\r
}\r
\r
\r
-void CvWinProperties::hideEvent(QHideEvent* event)\r
+void CvWinProperties::hideEvent(QHideEvent* evnt)\r
{\r
QSettings settings("OpenCV2", windowTitle());\r
settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)\r
- event->accept();\r
+ evnt->accept();\r
}\r
\r
\r
//organisation and application's name\r
QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());\r
\r
- QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();\r
- QSize size = settings.value("size", QSize(400, 400)).toSize();\r
+ QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();\r
+ QSize _size = settings.value("size", QSize(400, 400)).toSize();\r
\r
param_flags = settings.value("mode_resize", param_flags).toInt();\r
param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();\r
//trackbar here\r
icvLoadTrackbars(&settings);\r
\r
- resize(size);\r
- move(pos);\r
+ resize(_size);\r
+ move(_pos);\r
\r
if (global_control_panel)\r
{\r
}\r
\r
\r
-void CvWindow::setViewportSize(QSize size)\r
+void CvWindow::setViewportSize(QSize _size)\r
{\r
- myView->getWidget()->resize(size);\r
- myView->setSize(size);\r
+ myView->getWidget()->resize(_size);\r
+ myView->setSize(_size);\r
}\r
\r
\r
\r
\r
//Need more test here !\r
-void CvWindow::keyPressEvent(QKeyEvent *event)\r
+void CvWindow::keyPressEvent(QKeyEvent *evnt)\r
{\r
//see http://doc.trolltech.com/4.6/qt.html#Key-enum\r
- int key = event->key();\r
+ int key = evnt->key();\r
\r
Qt::Key qtkey = static_cast<Qt::Key>(key);\r
char asciiCode = QTest::keyToAscii(qtkey);\r
if (asciiCode != 0)\r
key = static_cast<int>(asciiCode);\r
else\r
- key = event->nativeVirtualKey(); //same codes as returned by GTK-based backend\r
+ key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend\r
\r
//control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions\r
- if (event->modifiers() != Qt::ControlModifier)\r
+ if (evnt->modifiers() != Qt::ControlModifier)\r
{\r
mutexKey.lock();\r
last_key = key;\r
mutexKey.unlock();\r
key_pressed.wakeAll();\r
- //event->accept();\r
+ //evnt->accept();\r
}\r
\r
- QWidget::keyPressEvent(event);\r
+ QWidget::keyPressEvent(evnt);\r
}\r
\r
\r
{\r
QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");\r
\r
- int size = settings.beginReadArray("bars");\r
+ int bsize = settings.beginReadArray("bars");\r
\r
- if (size == global_control_panel->myLayout->layout()->count())\r
+ if (bsize == global_control_panel->myLayout->layout()->count())\r
{\r
- for (int i = 0; i < size; ++i)\r
+ for (int i = 0; i < bsize; ++i)\r
{\r
CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);\r
settings.setArrayIndex(i);\r
\r
void CvWindow::icvLoadTrackbars(QSettings* settings)\r
{\r
- int size = settings->beginReadArray("trackbars");\r
+ int bsize = settings->beginReadArray("trackbars");\r
\r
//trackbar are saved in the same order, so no need to use icvFindTrackbarByName\r
\r
- if (myBarLayout->layout()->count() == size) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)\r
+ if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)\r
{\r
- for (int i = 0; i < size; ++i)\r
+ for (int i = 0; i < bsize; ++i)\r
{\r
settings->setArrayIndex(i);\r
\r
}\r
\r
\r
-void DefaultViewPort::contextMenuEvent(QContextMenuEvent* event)\r
+void DefaultViewPort::contextMenuEvent(QContextMenuEvent* evnt)\r
{\r
if (centralWidget->vect_QActions.size() > 0)\r
{\r
foreach (QAction *a, centralWidget->vect_QActions)\r
menu.addAction(a);\r
\r
- menu.exec(event->globalPos());\r
+ menu.exec(evnt->globalPos());\r
}\r
}\r
\r
\r
-void DefaultViewPort::resizeEvent(QResizeEvent* event)\r
+void DefaultViewPort::resizeEvent(QResizeEvent* evnt)\r
{\r
controlImagePosition();\r
\r
if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio\r
{\r
QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows);\r
- newSize.scale(event->size(), Qt::KeepAspectRatio);\r
+ newSize.scale(evnt->size(), Qt::KeepAspectRatio);\r
\r
//imageWidth/imageHeight = newWidth/newHeight +/- epsilon\r
//ratioX = ratioY +/- epsilon\r
\r
//move to the middle\r
//newSize get the delta offset to place the picture in the middle of its parent\r
- newSize = (event->size() - newSize) / 2;\r
+ newSize = (evnt->size() - newSize) / 2;\r
\r
//if the toolbar is displayed, avoid drawing myview on top of it\r
if (centralWidget->myToolBar)\r
}\r
}\r
\r
- return QGraphicsView::resizeEvent(event);\r
+ return QGraphicsView::resizeEvent(evnt);\r
}\r
\r
\r
-void DefaultViewPort::wheelEvent(QWheelEvent* event)\r
+void DefaultViewPort::wheelEvent(QWheelEvent* evnt)\r
{\r
- scaleView(event->delta() / 240.0, event->pos());\r
+ scaleView(evnt->delta() / 240.0, evnt->pos());\r
viewport()->update();\r
}\r
\r
\r
-void DefaultViewPort::mousePressEvent(QMouseEvent* event)\r
+void DefaultViewPort::mousePressEvent(QMouseEvent* evnt)\r
{\r
int cv_event = -1, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
//icvmouseHandler: pass parameters for cv_event, flags\r
- icvmouseHandler(event, mouse_down, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_down, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
if (param_matrixWorld.m11()>1)\r
{\r
setCursor(Qt::ClosedHandCursor);\r
- positionGrabbing = event->pos();\r
+ positionGrabbing = evnt->pos();\r
}\r
\r
- QWidget::mousePressEvent(event);\r
+ QWidget::mousePressEvent(evnt);\r
}\r
\r
\r
-void DefaultViewPort::mouseReleaseEvent(QMouseEvent* event)\r
+void DefaultViewPort::mouseReleaseEvent(QMouseEvent* evnt)\r
{\r
int cv_event = -1, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
//icvmouseHandler: pass parameters for cv_event, flags\r
- icvmouseHandler(event, mouse_up, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_up, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
if (param_matrixWorld.m11()>1)\r
setCursor(Qt::OpenHandCursor);\r
\r
- QWidget::mouseReleaseEvent(event);\r
+ QWidget::mouseReleaseEvent(evnt);\r
}\r
\r
\r
-void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* event)\r
+void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)\r
{\r
int cv_event = -1, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
//icvmouseHandler: pass parameters for cv_event, flags\r
- icvmouseHandler(event, mouse_dbclick, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
- QWidget::mouseDoubleClickEvent(event);\r
+ QWidget::mouseDoubleClickEvent(evnt);\r
}\r
\r
\r
-void DefaultViewPort::mouseMoveEvent(QMouseEvent* event)\r
+void DefaultViewPort::mouseMoveEvent(QMouseEvent* evnt)\r
{\r
int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
//icvmouseHandler: pass parameters for cv_event, flags\r
- icvmouseHandler(event, mouse_move, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_move, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
- if (param_matrixWorld.m11() > 1 && event->buttons() == Qt::LeftButton)\r
+ if (param_matrixWorld.m11() > 1 && evnt->buttons() == Qt::LeftButton)\r
{\r
QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11();\r
- positionGrabbing = event->pos();\r
+ positionGrabbing = evnt->pos();\r
moveView(dxy);\r
}\r
\r
if (centralWidget->myStatusBar)\r
viewport()->update();\r
\r
- QWidget::mouseMoveEvent(event);\r
+ QWidget::mouseMoveEvent(evnt);\r
}\r
\r
\r
-void DefaultViewPort::paintEvent(QPaintEvent* event)\r
+void DefaultViewPort::paintEvent(QPaintEvent* evnt)\r
{\r
QPainter myPainter(viewport());\r
myPainter.setWorldTransform(param_matrixWorld);\r
if (centralWidget->myStatusBar)\r
drawStatusBar();\r
\r
- QGraphicsView::paintEvent(event);\r
+ QGraphicsView::paintEvent(evnt);\r
}\r
\r
\r
\r
\r
//up, down, dclick, move\r
-void DefaultViewPort::icvmouseHandler(QMouseEvent *event, type_mouse_event category, int &cv_event, int &flags)\r
+void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)\r
{\r
- Qt::KeyboardModifiers modifiers = event->modifiers();\r
- Qt::MouseButtons buttons = event->buttons();\r
+ Qt::KeyboardModifiers modifiers = evnt->modifiers();\r
+ Qt::MouseButtons buttons = evnt->buttons();\r
\r
flags = 0;\r
if(modifiers & Qt::ShiftModifier)\r
flags |= CV_EVENT_FLAG_MBUTTON;\r
\r
cv_event = CV_EVENT_MOUSEMOVE;\r
- switch(event->button())\r
+ switch(evnt->button())\r
{\r
case Qt::LeftButton:\r
cv_event = tableMouseButtons[category][0];\r
\r
QSize view = size();\r
QVarLengthArray<QLineF, 30> linesX;\r
- for (qreal x = offsetX*param_matrixWorld.m11(); x < view.width(); x += param_matrixWorld.m11() )\r
- linesX.append(QLineF(x, 0, x, view.height()));\r
+ for (qreal _x = offsetX*param_matrixWorld.m11(); _x < view.width(); _x += param_matrixWorld.m11() )\r
+ linesX.append(QLineF(_x, 0, _x, view.height()));\r
\r
QVarLengthArray<QLineF, 30> linesY;\r
- for (qreal y = offsetY*param_matrixWorld.m11(); y < view.height(); y += param_matrixWorld.m11() )\r
- linesY.append(QLineF(0, y, view.width(), y));\r
+ for (qreal _y = offsetY*param_matrixWorld.m11(); _y < view.height(); _y += param_matrixWorld.m11() )\r
+ linesY.append(QLineF(0, _y, view.width(), _y));\r
\r
\r
QFont f = painter->font();\r
QFontMetrics metrics = QFontMetrics(font());\r
int border = qMax(4, metrics.leading());\r
\r
- QRect rect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),\r
+ QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),\r
Qt::AlignCenter | Qt::TextWordWrap, infoText);\r
painter->setRenderHint(QPainter::TextAntialiasing);\r
- painter->fillRect(QRect(0, 0, width(), rect.height() + 2*border),\r
+ painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),\r
QColor(0, 0, 0, 127));\r
painter->setPen(Qt::white);\r
- painter->fillRect(QRect(0, 0, width(), rect.height() + 2*border),\r
+ painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),\r
QColor(0, 0, 0, 127));\r
\r
- painter->drawText((width() - rect.width())/2, border,\r
- rect.width(), rect.height(),\r
+ painter->drawText((width() - qrect.width())/2, border,\r
+ qrect.width(), qrect.height(),\r
Qt::AlignCenter | Qt::TextWordWrap, infoText);\r
}\r
\r
\r
#ifdef HAVE_QT_OPENGL\r
\r
-OpenGlViewPort::OpenGlViewPort(QWidget* parent) : QGLWidget(parent), size(-1, -1)\r
+OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)\r
{\r
mouseCallback = 0;\r
mouseData = 0;\r
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);\r
\r
#ifdef Q_WS_WIN\r
- std::auto_ptr<GlFuncTab_QT> glFuncTab(new GlFuncTab_QT(getDC()));\r
+ std::auto_ptr<GlFuncTab_QT> qglFuncTab(new GlFuncTab_QT(getDC()));\r
#else\r
- std::auto_ptr<GlFuncTab_QT> glFuncTab(new GlFuncTab_QT);\r
+ std::auto_ptr<GlFuncTab_QT> qglFuncTab(new GlFuncTab_QT);\r
#endif\r
\r
// Load extensions\r
\r
- glFuncTab->glGenBuffersExt = (PFNGLGENBUFFERSPROC)context()->getProcAddress("glGenBuffers");\r
- glFuncTab->glDeleteBuffersExt = (PFNGLDELETEBUFFERSPROC)context()->getProcAddress("glDeleteBuffers");\r
- glFuncTab->glBufferDataExt = (PFNGLBUFFERDATAPROC)context()->getProcAddress("glBufferData");\r
- glFuncTab->glBufferSubDataExt = (PFNGLBUFFERSUBDATAPROC)context()->getProcAddress("glBufferSubData");\r
- glFuncTab->glBindBufferExt = (PFNGLBINDBUFFERPROC)context()->getProcAddress("glBindBuffer");\r
- glFuncTab->glMapBufferExt = (PFNGLMAPBUFFERPROC)context()->getProcAddress("glMapBuffer");\r
- glFuncTab->glUnmapBufferExt = (PFNGLUNMAPBUFFERPROC)context()->getProcAddress("glUnmapBuffer");\r
+ qglFuncTab->glGenBuffersExt = (PFNGLGENBUFFERSPROC)context()->getProcAddress("glGenBuffers");\r
+ qglFuncTab->glDeleteBuffersExt = (PFNGLDELETEBUFFERSPROC)context()->getProcAddress("glDeleteBuffers");\r
+ qglFuncTab->glBufferDataExt = (PFNGLBUFFERDATAPROC)context()->getProcAddress("glBufferData");\r
+ qglFuncTab->glBufferSubDataExt = (PFNGLBUFFERSUBDATAPROC)context()->getProcAddress("glBufferSubData");\r
+ qglFuncTab->glBindBufferExt = (PFNGLBINDBUFFERPROC)context()->getProcAddress("glBindBuffer");\r
+ qglFuncTab->glMapBufferExt = (PFNGLMAPBUFFERPROC)context()->getProcAddress("glMapBuffer");\r
+ qglFuncTab->glUnmapBufferExt = (PFNGLUNMAPBUFFERPROC)context()->getProcAddress("glUnmapBuffer");\r
\r
- glFuncTab->initialized = true;\r
+ qglFuncTab->initialized = true;\r
\r
- this->glFuncTab = glFuncTab.release();\r
+ glFuncTab = qglFuncTab.release();\r
\r
- icvSetOpenGlFuncTab(this->glFuncTab);\r
+ icvSetOpenGlFuncTab(glFuncTab);\r
}\r
\r
void OpenGlViewPort::resizeGL(int w, int h)\r
CV_CheckGlError();\r
}\r
\r
-void OpenGlViewPort::mousePressEvent(QMouseEvent* event)\r
+void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)\r
{\r
int cv_event = -1, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
- icvmouseHandler(event, mouse_down, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_down, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
- QGLWidget::mousePressEvent(event);\r
+ QGLWidget::mousePressEvent(evnt);\r
}\r
\r
\r
-void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* event)\r
+void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)\r
{\r
int cv_event = -1, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
- icvmouseHandler(event, mouse_up, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_up, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
- QGLWidget::mouseReleaseEvent(event);\r
+ QGLWidget::mouseReleaseEvent(evnt);\r
}\r
\r
\r
-void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* event)\r
+void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)\r
{\r
int cv_event = -1, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
- icvmouseHandler(event, mouse_dbclick, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
- QGLWidget::mouseDoubleClickEvent(event);\r
+ QGLWidget::mouseDoubleClickEvent(evnt);\r
}\r
\r
\r
-void OpenGlViewPort::mouseMoveEvent(QMouseEvent* event)\r
+void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)\r
{\r
int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;\r
- QPoint pt = event->pos();\r
+ QPoint pt = evnt->pos();\r
\r
//icvmouseHandler: pass parameters for cv_event, flags\r
- icvmouseHandler(event, mouse_move, cv_event, flags);\r
+ icvmouseHandler(evnt, mouse_move, cv_event, flags);\r
icvmouseProcessing(QPointF(pt), cv_event, flags);\r
\r
- QGLWidget::mouseMoveEvent(event);\r
+ QGLWidget::mouseMoveEvent(evnt);\r
}\r
\r
-void OpenGlViewPort::icvmouseHandler(QMouseEvent* event, type_mouse_event category, int& cv_event, int& flags)\r
+void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)\r
{\r
- Qt::KeyboardModifiers modifiers = event->modifiers();\r
- Qt::MouseButtons buttons = event->buttons();\r
+ Qt::KeyboardModifiers modifiers = evnt->modifiers();\r
+ Qt::MouseButtons buttons = evnt->buttons();\r
\r
flags = 0;\r
if (modifiers & Qt::ShiftModifier)\r
flags |= CV_EVENT_FLAG_MBUTTON;\r
\r
cv_event = CV_EVENT_MOUSEMOVE;\r
- switch (event->button())\r
+ switch (evnt->button())\r
{\r
case Qt::LeftButton:\r
cv_event = tableMouseButtons[category][0];\r
#include <GL/glu.h>
#endif
-/*#if _MSC_VER >= 1200
-#pragma warning( disable: 4505 )
-#pragma comment(lib,"gtk-win32-2.0.lib")
-#pragma comment(lib,"glib-2.0.lib")
-#pragma comment(lib,"gobject-2.0.lib")
-#pragma comment(lib,"gdk-win32-2.0.lib")
-#pragma comment(lib,"gdk_pixbuf-2.0.lib")
-#endif*/
-
-
// TODO Fix the initial window size when flags=0. Right now the initial window is by default
// 320x240 size. A better default would be actual size of the image. Problem
// is determining desired window size with trackbars while still allowing resizing.
#if defined WIN32 || defined _WIN32
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4710 )
-#endif
-
#define COMPILE_MULTIMON_STUBS // Required for multi-monitor support
#ifndef _MULTIMON_USE_SECURE_CRT
# define _MULTIMON_USE_SECURE_CRT 0 // some MinGW platforms have no strncpy_s
void releaseGlContext(CvWindow* window)
{
- CV_FUNCNAME( "releaseGlContext" );
+ //CV_FUNCNAME( "releaseGlContext" );
__BEGIN__;
if( hg_on_preprocess )
{
int was_processed = 0;
- int ret = hg_on_preprocess(hwnd, uMsg, wParam, lParam, &was_processed);
+ int rethg = hg_on_preprocess(hwnd, uMsg, wParam, lParam, &was_processed);
if( was_processed )
- return ret;
+ return rethg;
}
ret = HighGUIProc(hwnd, uMsg, wParam, lParam);
if(hg_on_postprocess)
{
int was_processed = 0;
- int ret = hg_on_postprocess(hwnd, uMsg, wParam, lParam, &was_processed);
+ int rethg = hg_on_postprocess(hwnd, uMsg, wParam, lParam, &was_processed);
if( was_processed )
- return ret;
+ return rethg;
}
return ret;
return;
}
- int N0 = cap.get(CV_CAP_PROP_FRAME_COUNT);
+ int N0 = (int)cap.get(CV_CAP_PROP_FRAME_COUNT);
cap.set(CV_CAP_PROP_POS_FRAMES, 0);
- int N = cap.get(CV_CAP_PROP_FRAME_COUNT);
+ int N = (int)cap.get(CV_CAP_PROP_FRAME_COUNT);
if (N != n_frames || N != N0)
{
* Multi-Scale variant of Classical Hough Transform *
\****************************************************************************************/
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4714 )
-#endif
-
//DECLARE_AND_IMPLEMENT_LIST( _index, h_ );
IMPLEMENT_LIST( _index, h_ )
assert( k < ssize.width*2 );
xofs[k].di = dx*cn;
xofs[k].si = sx*cn;
- xofs[k++].alpha = 1.f / min(scale_x, src.cols - fsx1);
+ xofs[k++].alpha = float(1.0 / min(scale_x, src.cols - fsx1));
}
if( fsx2 - sx2 > 1e-3 )
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
- // disable warnings related to inline functions
- #pragma warning( disable: 4251 4711 4710 4514 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
namespace cv
{
-
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4244 )
-#endif
-
typedef ushort HT;
/**
for( c = 0; c < cn; c++ )
{
for( j = 0; j < n; j++ )
- COP( c, j, src[cn*j+c], += r+2 );
+ COP( c, j, src[cn*j+c], += (cv::HT)(r+2) );
for( i = 1; i < r; i++ )
{
if ( luc[c][k] <= j-r )
{
memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
- for ( luc[c][k] = j-r; luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
+ for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
histogram_add_simd( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
if ( luc[c][k] < j+r+1 )
if ( luc[c][k] <= j-r )
{
memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
- for ( luc[c][k] = j-r; luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
+ for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
histogram_add( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
if ( luc[c][k] < j+r+1 )
#undef COP
}
-
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( default: 4244 )
-#endif
-
static void
medianBlur_8u_Om( const Mat& _src, Mat& _dst, int m )
{
class CV_EXPORTS BruteForceMatcher : public BFMatcher
{
public:
- BruteForceMatcher( Distance d = Distance() ) : BFMatcher(Distance::normType, false) {}
+ BruteForceMatcher( Distance d = Distance() ) : BFMatcher(Distance::normType, false) {(void)d;}
virtual ~BruteForceMatcher() {}
};
#include "precomp.hpp"
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning(disable:4786) // Disable MSVC warnings in the standard library.
-#pragma warning(disable:4100)
-#pragma warning(disable:4512)
-#endif
#include <stdio.h>
#include <map>
#include <algorithm>
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning(default:4100)
-#pragma warning(default:4512)
-#endif
#define ARRAY_SIZEOF(a) (sizeof(a)/sizeof((a)[0]))
#include "assert.h"
#include "math.h"
-#if defined _MSC_VER && _MSC_VER >= 1400
-#pragma warning(disable: 4512) // suppress "assignment operator could not be generated"
-#endif
-
// J.S. Beis and D.G. Lowe. Shape indexing using approximate nearest-neighbor search
// in highdimensional spaces. In Proc. IEEE Conf. Comp. Vision Patt. Recog.,
// pages 1000--1006, 1997. http://citeseer.ist.psu.edu/beis97shape.html
bool operator() (const __instype & lhs) const {
return deref(ctor(lhs), dim) <= deref(ctor(pivot), dim);
}
+ private:
+ median_pr& operator=(const median_pr&);
};
template < class __instype, class __valuector >
typedef struct DefBlobFVN
{
- CvBlob blob;
- CvBlob BlobSeq[BLOB_NUM];
- int state;
- int LastFrame;
- int FrameNum;
+ CvBlob blob;
+ CvBlob BlobSeq[BLOB_NUM];
+ int state;
+ int LastFrame;
+ int FrameNum;
} DefBlobFVN;
class CvBlobTrackFVGenN: public CvBlobTrackFVGen
{
private:
- CvBlobSeq m_BlobList;
- CvMemStorage* m_pMem;
- CvSeq* m_pFVSeq;
- float m_FVMax[MAX_FV_SIZE];
- float m_FVMin[MAX_FV_SIZE];
- float m_FVVar[MAX_FV_SIZE];
- int m_Dim;
- CvBlob m_BlobSeq[BLOB_NUM];
- int m_Frame;
- int m_State;
- int m_LastFrame;
- int m_ClearFlag;
- void Clear()
- {
- if(m_pMem)
- {
- cvClearMemStorage(m_pMem);
- m_pFVSeq = cvCreateSeq(0,sizeof(CvSeq),sizeof(float)*(m_Dim+1), m_pMem);
- m_ClearFlag = 1;
- }
- }
+ CvBlobSeq m_BlobList;
+ CvMemStorage* m_pMem;
+ CvSeq* m_pFVSeq;
+ float m_FVMax[MAX_FV_SIZE];
+ float m_FVMin[MAX_FV_SIZE];
+ float m_FVVar[MAX_FV_SIZE];
+ int m_Dim;
+ CvBlob m_BlobSeq[BLOB_NUM];
+ int m_Frame;
+ int m_State;
+ int m_LastFrame;
+ int m_ClearFlag;
+ void Clear()
+ {
+ if(m_pMem)
+ {
+ cvClearMemStorage(m_pMem);
+ m_pFVSeq = cvCreateSeq(0,sizeof(CvSeq),sizeof(float)*(m_Dim+1), m_pMem);
+ m_ClearFlag = 1;
+ }
+ }
public:
- CvBlobTrackFVGenN(int dim = 2 ):m_BlobList(sizeof(DefBlobFVN))
- {
- int i;
- assert(dim <= MAX_FV_SIZE);
- m_Dim = dim;
- for(i=0; i<m_Dim; ++i)
- {
- m_FVVar[i] = 0.01f;
- m_FVMax[i] = 1;
- m_FVMin[i] = 0;
- }
- m_Frame = 0;
- m_State = 0;
- m_pMem = cvCreateMemStorage();
- m_pFVSeq = NULL;
- Clear();
-
- switch(dim) {
- case 2: SetModuleName("P"); break;
- case 4: SetModuleName("PV"); break;
- case 5: SetModuleName("PVS"); break;
- }
- };
-
- ~CvBlobTrackFVGenN()
- {
- if(m_pMem)cvReleaseMemStorage(&m_pMem);
- };
-
- void AddBlob(CvBlob* pBlob)
- {
- float FV[MAX_FV_SIZE+1];
- int i;
- DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
-
- if(!m_ClearFlag) Clear();
-
- if(pFVBlob==NULL)
- {
- DefBlobFVN BlobNew;
- BlobNew.blob = pBlob[0];
- BlobNew.LastFrame = m_Frame;
- BlobNew.state = 0;;
- BlobNew.FrameNum = 0;
- m_BlobList.AddBlob((CvBlob*)&BlobNew);
- pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
- } /* Add new record if necessary. */
-
- pFVBlob->blob = pBlob[0];
-
- /* Shift: */
- for(i=(BLOB_NUM-1); i>0; --i)
- {
- pFVBlob->BlobSeq[i] = pFVBlob->BlobSeq[i-1];
- }
-
- pFVBlob->BlobSeq[0] = pBlob[0];
-
- if(m_Dim>0)
- { /* Calculate FV position: */
- FV[0] = CV_BLOB_X(pBlob);
- FV[1] = CV_BLOB_Y(pBlob);
- }
-
- if(m_Dim<=2)
- { /* Add new FV if position is enough: */
- *(int*)(FV+m_Dim) = CV_BLOB_ID(pBlob);
- cvSeqPush( m_pFVSeq, FV );
- }
- else if(pFVBlob->FrameNum > BLOB_NUM)
- { /* Calculate velocity for more complex FV: */
- float AverVx = 0;
- float AverVy = 0;
- { /* Average velocity: */
- CvBlob* pBlobSeq = pFVBlob->BlobSeq;
- int i;
- for(i=1;i<BLOB_NUM;++i)
- {
- AverVx += CV_BLOB_X(pBlobSeq+i-1)-CV_BLOB_X(pBlobSeq+i);
- AverVy += CV_BLOB_Y(pBlobSeq+i-1)-CV_BLOB_Y(pBlobSeq+i);
- }
- AverVx /= BLOB_NUM-1;
- AverVy /= BLOB_NUM-1;
-
- FV[2] = AverVx;
- FV[3] = AverVy;
- }
-
- if(m_Dim>4)
- { /* State duration: */
- float T = (CV_BLOB_WX(pBlob)+CV_BLOB_WY(pBlob))*0.01f;
-
- if( fabs(AverVx) < T && fabs(AverVy) < T)
- pFVBlob->state++;
- else
- pFVBlob->state=0;
- FV[4] = (float)pFVBlob->state;
- } /* State duration. */
-
- /* Add new FV: */
- *(int*)(FV+m_Dim) = CV_BLOB_ID(pBlob);
- cvSeqPush( m_pFVSeq, FV );
-
- } /* If velocity is calculated. */
-
- pFVBlob->FrameNum++;
- pFVBlob->LastFrame = m_Frame;
- }; /* AddBlob */
-
- void Process(IplImage* pImg, IplImage* /*pFG*/)
- {
- int i;
- if(!m_ClearFlag) Clear();
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
- { /* Delete unused blob: */
- DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlob(i-1);
- if(pFVBlob->LastFrame < m_Frame)
- {
- m_BlobList.DelBlob(i-1);
- }
- } /* Check next blob in list. */
-
- m_FVMin[0] = 0;
- m_FVMin[1] = 0;
- m_FVMax[0] = (float)(pImg->width-1);
- m_FVMax[1] = (float)(pImg->height-1);
- m_FVVar[0] = m_FVMax[0]*0.01f;
- m_FVVar[1] = m_FVMax[1]*0.01f;
- m_FVVar[2] = (float)(pImg->width-1)/1440.0f;
- m_FVMax[2] = (float)(pImg->width-1)*0.02f;
- m_FVMin[2] = -m_FVMax[2];
- m_FVVar[3] = (float)(pImg->width-1)/1440.0f;
- m_FVMax[3] = (float)(pImg->height-1)*0.02f;
- m_FVMin[3] = -m_FVMax[3];
- m_FVMax[4] = 25*32.0f; /* max state is 32 sec */
- m_FVMin[4] = 0;
- m_FVVar[4] = 10;
-
- m_Frame++;
- m_ClearFlag = 0;
- };
- virtual void Release(){delete this;};
- virtual int GetFVSize(){return m_Dim;};
- virtual int GetFVNum()
- {
- return m_pFVSeq->total;
- };
-
- virtual float* GetFV(int index, int* pFVID)
- {
- float* pFV = (float*)cvGetSeqElem( m_pFVSeq, index );
- if(pFVID)pFVID[0] = *(int*)(pFV+m_Dim);
- return pFV;
- };
- virtual float* GetFVMin(){return m_FVMin;}; /* returned pointer to array of minimal values of FV, if return 0 then FVrange is not exist */
- virtual float* GetFVMax(){return m_FVMax;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
- virtual float* GetFVVar(){return m_FVVar;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
+ CvBlobTrackFVGenN(int dim = 2 ):m_BlobList(sizeof(DefBlobFVN))
+ {
+ int i;
+ assert(dim <= MAX_FV_SIZE);
+ m_Dim = dim;
+ for(i=0; i<m_Dim; ++i)
+ {
+ m_FVVar[i] = 0.01f;
+ m_FVMax[i] = 1;
+ m_FVMin[i] = 0;
+ }
+ m_Frame = 0;
+ m_State = 0;
+ m_pMem = cvCreateMemStorage();
+ m_pFVSeq = NULL;
+ Clear();
+
+ switch(dim) {
+ case 2: SetModuleName("P"); break;
+ case 4: SetModuleName("PV"); break;
+ case 5: SetModuleName("PVS"); break;
+ }
+ };
+
+ ~CvBlobTrackFVGenN()
+ {
+ if(m_pMem)cvReleaseMemStorage(&m_pMem);
+ };
+
+ void AddBlob(CvBlob* pBlob)
+ {
+ float FV[MAX_FV_SIZE+1];
+ DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
+
+ if(!m_ClearFlag) Clear();
+
+ if(pFVBlob==NULL)
+ {
+ DefBlobFVN BlobNew;
+ BlobNew.blob = pBlob[0];
+ BlobNew.LastFrame = m_Frame;
+ BlobNew.state = 0;;
+ BlobNew.FrameNum = 0;
+ m_BlobList.AddBlob((CvBlob*)&BlobNew);
+ pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
+ } /* Add new record if necessary. */
+
+ pFVBlob->blob = pBlob[0];
+
+ /* Shift: */
+ for(int i=(BLOB_NUM-1); i>0; --i)
+ {
+ pFVBlob->BlobSeq[i] = pFVBlob->BlobSeq[i-1];
+ }
+
+ pFVBlob->BlobSeq[0] = pBlob[0];
+
+ if(m_Dim>0)
+ { /* Calculate FV position: */
+ FV[0] = CV_BLOB_X(pBlob);
+ FV[1] = CV_BLOB_Y(pBlob);
+ }
+
+ if(m_Dim<=2)
+ { /* Add new FV if position is enough: */
+ *(int*)(FV+m_Dim) = CV_BLOB_ID(pBlob);
+ cvSeqPush( m_pFVSeq, FV );
+ }
+ else if(pFVBlob->FrameNum > BLOB_NUM)
+ { /* Calculate velocity for more complex FV: */
+ float AverVx = 0;
+ float AverVy = 0;
+ { /* Average velocity: */
+ CvBlob* pBlobSeq = pFVBlob->BlobSeq;
+ for(int i=1;i<BLOB_NUM;++i)
+ {
+ AverVx += CV_BLOB_X(pBlobSeq+i-1)-CV_BLOB_X(pBlobSeq+i);
+ AverVy += CV_BLOB_Y(pBlobSeq+i-1)-CV_BLOB_Y(pBlobSeq+i);
+ }
+ AverVx /= BLOB_NUM-1;
+ AverVy /= BLOB_NUM-1;
+
+ FV[2] = AverVx;
+ FV[3] = AverVy;
+ }
+
+ if(m_Dim>4)
+ { /* State duration: */
+ float T = (CV_BLOB_WX(pBlob)+CV_BLOB_WY(pBlob))*0.01f;
+
+ if( fabs(AverVx) < T && fabs(AverVy) < T)
+ pFVBlob->state++;
+ else
+ pFVBlob->state=0;
+ FV[4] = (float)pFVBlob->state;
+ } /* State duration. */
+
+ /* Add new FV: */
+ *(int*)(FV+m_Dim) = CV_BLOB_ID(pBlob);
+ cvSeqPush( m_pFVSeq, FV );
+
+ } /* If velocity is calculated. */
+
+ pFVBlob->FrameNum++;
+ pFVBlob->LastFrame = m_Frame;
+ }; /* AddBlob */
+
+ void Process(IplImage* pImg, IplImage* /*pFG*/)
+ {
+ int i;
+ if(!m_ClearFlag) Clear();
+ for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ { /* Delete unused blob: */
+ DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlob(i-1);
+ if(pFVBlob->LastFrame < m_Frame)
+ {
+ m_BlobList.DelBlob(i-1);
+ }
+ } /* Check next blob in list. */
+
+ m_FVMin[0] = 0;
+ m_FVMin[1] = 0;
+ m_FVMax[0] = (float)(pImg->width-1);
+ m_FVMax[1] = (float)(pImg->height-1);
+ m_FVVar[0] = m_FVMax[0]*0.01f;
+ m_FVVar[1] = m_FVMax[1]*0.01f;
+ m_FVVar[2] = (float)(pImg->width-1)/1440.0f;
+ m_FVMax[2] = (float)(pImg->width-1)*0.02f;
+ m_FVMin[2] = -m_FVMax[2];
+ m_FVVar[3] = (float)(pImg->width-1)/1440.0f;
+ m_FVMax[3] = (float)(pImg->height-1)*0.02f;
+ m_FVMin[3] = -m_FVMax[3];
+ m_FVMax[4] = 25*32.0f; /* max state is 32 sec */
+ m_FVMin[4] = 0;
+ m_FVVar[4] = 10;
+
+ m_Frame++;
+ m_ClearFlag = 0;
+ };
+ virtual void Release(){delete this;};
+ virtual int GetFVSize(){return m_Dim;};
+ virtual int GetFVNum()
+ {
+ return m_pFVSeq->total;
+ };
+
+ virtual float* GetFV(int index, int* pFVID)
+ {
+ float* pFV = (float*)cvGetSeqElem( m_pFVSeq, index );
+ if(pFVID)pFVID[0] = *(int*)(pFV+m_Dim);
+ return pFV;
+ };
+ virtual float* GetFVMin(){return m_FVMin;}; /* returned pointer to array of minimal values of FV, if return 0 then FVrange is not exist */
+ virtual float* GetFVMax(){return m_FVMax;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
+ virtual float* GetFVVar(){return m_FVVar;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
};/* CvBlobTrackFVGenN */
inline CvBlobTrackFVGen* cvCreateFVGenP(){return (CvBlobTrackFVGen*)new CvBlobTrackFVGenN(2);}
class CvBlobTrackFVGenSS: public CvBlobTrackFVGen
{
private:
- CvBlobSeq m_BlobList;
- CvMemStorage* m_pMem;
- CvSeq* m_pFVSeq;
- float m_FVMax[MAX_FV_SIZE];
- float m_FVMin[MAX_FV_SIZE];
- float m_FVVar[MAX_FV_SIZE];
- int m_Dim;
- CvBlob m_BlobSeq[BLOB_NUM];
- int m_Frame;
- int m_State;
- int m_LastFrame;
- int m_ClearFlag;
- void Clear()
- {
- cvClearMemStorage(m_pMem);
- m_pFVSeq = cvCreateSeq(0,sizeof(CvSeq),sizeof(float)*(m_Dim+1), m_pMem);
- m_ClearFlag = 1;
- }
+ CvBlobSeq m_BlobList;
+ CvMemStorage* m_pMem;
+ CvSeq* m_pFVSeq;
+ float m_FVMax[MAX_FV_SIZE];
+ float m_FVMin[MAX_FV_SIZE];
+ float m_FVVar[MAX_FV_SIZE];
+ int m_Dim;
+ CvBlob m_BlobSeq[BLOB_NUM];
+ int m_Frame;
+ int m_State;
+ int m_LastFrame;
+ int m_ClearFlag;
+ void Clear()
+ {
+ cvClearMemStorage(m_pMem);
+ m_pFVSeq = cvCreateSeq(0,sizeof(CvSeq),sizeof(float)*(m_Dim+1), m_pMem);
+ m_ClearFlag = 1;
+ }
public:
- CvBlobTrackFVGenSS(int dim = 2 ):m_BlobList(sizeof(DefBlobFVN))
- {
- int i;
- assert(dim <= MAX_FV_SIZE);
- m_Dim = dim;
- for(i=0;i<m_Dim;++i)
- {
- m_FVVar[i] = 0.01f;
- m_FVMax[i] = 1;
- m_FVMin[i] = 0;
- }
- m_Frame = 0;
- m_State = 0;
- m_pMem = cvCreateMemStorage();
- m_pFVSeq = NULL;
-
- SetModuleName("SS");
- };
- ~CvBlobTrackFVGenSS()
- {
- if(m_pMem)cvReleaseMemStorage(&m_pMem);
- };
-
- void AddBlob(CvBlob* pBlob)
- {
- //float FV[MAX_FV_SIZE+1];
- int i;
- DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
-
- if(!m_ClearFlag) Clear();
-
- if(pFVBlob==NULL)
- {
- DefBlobFVN BlobNew;
- BlobNew.blob = pBlob[0];
- BlobNew.LastFrame = m_Frame;
- BlobNew.state = 0;;
- BlobNew.FrameNum = 0;
- m_BlobList.AddBlob((CvBlob*)&BlobNew);
- pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
- } /* Add new record if necessary. */
-
- /* Shift: */
- for(i=(BLOB_NUM-1); i>0; --i)
- {
- pFVBlob->BlobSeq[i] = pFVBlob->BlobSeq[i-1];
- }
-
- pFVBlob->BlobSeq[0] = pBlob[0];
-
- if(pFVBlob->FrameNum > BLOB_NUM)
- { /* Average velocity: */
- CvBlob* pBlobSeq = pFVBlob->BlobSeq;
- float T = (CV_BLOB_WX(pBlob)+CV_BLOB_WY(pBlob))*0.01f;
- float AverVx = 0;
- float AverVy = 0;
- int i;
- for(i=1; i<BLOB_NUM; ++i)
- {
- AverVx += CV_BLOB_X(pBlobSeq+i-1)-CV_BLOB_X(pBlobSeq+i);
- AverVy += CV_BLOB_Y(pBlobSeq+i-1)-CV_BLOB_Y(pBlobSeq+i);
- }
- AverVx /= BLOB_NUM-1;
- AverVy /= BLOB_NUM-1;
-
- if( fabs(AverVx) < T && fabs(AverVy) < T)
- pFVBlob->state++;
- else
- pFVBlob->state=0;
- }
-
- if(pFVBlob->state == 5)
- { /* Object is stopped: */
- float FV[MAX_FV_SIZE];
- FV[0] = pFVBlob->blob.x;
- FV[1] = pFVBlob->blob.y;
- FV[2] = pFVBlob->BlobSeq[0].x;
- FV[3] = pFVBlob->BlobSeq[0].y;
- *(int*)(FV+m_Dim) = CV_BLOB_ID(pBlob);
- cvSeqPush( m_pFVSeq, FV );
- } /* Object is stopped. */
-
- pFVBlob->FrameNum++;
- pFVBlob->LastFrame = m_Frame;
- }; /* AddBlob */
- void Process(IplImage* pImg, IplImage* /*pFG*/)
- {
- int i;
-
- if(!m_ClearFlag) Clear();
-
- for(i=m_BlobList.GetBlobNum();i>0;--i)
- { /* Delete unused blob: */
- DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlob(i-1);
- if(pFVBlob->LastFrame < m_Frame)
- {
- float FV[MAX_FV_SIZE+1];
- FV[0] = pFVBlob->blob.x;
- FV[1] = pFVBlob->blob.y;
- FV[2] = pFVBlob->BlobSeq[0].x;
- FV[3] = pFVBlob->BlobSeq[0].y;
- *(int*)(FV+m_Dim) = CV_BLOB_ID(pFVBlob);
- cvSeqPush( m_pFVSeq, FV );
- m_BlobList.DelBlob(i-1);
- }
- } /* Check next blob in list. */
-
- /* Set max min range: */
- m_FVMin[0] = 0;
- m_FVMin[1] = 0;
- m_FVMin[2] = 0;
- m_FVMin[3] = 0;
- m_FVMax[0] = (float)(pImg->width-1);
- m_FVMax[1] = (float)(pImg->height-1);
- m_FVMax[2] = (float)(pImg->width-1);
- m_FVMax[3] = (float)(pImg->height-1);
- m_FVVar[0] = m_FVMax[0]*0.01f;
- m_FVVar[1] = m_FVMax[1]*0.01f;
- m_FVVar[2] = m_FVMax[2]*0.01f;
- m_FVVar[3] = m_FVMax[3]*0.01f;
-
- m_Frame++;
- m_ClearFlag = 0;
- };
- virtual void Release(){delete this;};
- virtual int GetFVSize(){return m_Dim;};
- virtual int GetFVNum()
- {
- return m_pFVSeq->total;
- };
-
- virtual float* GetFV(int index, int* pFVID)
- {
- float* pFV = (float*)cvGetSeqElem( m_pFVSeq, index );
- if(pFVID)pFVID[0] = *(int*)(pFV+m_Dim);
- return pFV;
- };
-
- virtual float* GetFVMin(){return m_FVMin;}; /* returned pointer to array of minimal values of FV, if return 0 then FVrange is not exist */
- virtual float* GetFVMax(){return m_FVMax;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
- virtual float* GetFVVar(){return m_FVVar;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
+ CvBlobTrackFVGenSS(int dim = 2 ):m_BlobList(sizeof(DefBlobFVN))
+ {
+ int i;
+ assert(dim <= MAX_FV_SIZE);
+ m_Dim = dim;
+ for(i=0;i<m_Dim;++i)
+ {
+ m_FVVar[i] = 0.01f;
+ m_FVMax[i] = 1;
+ m_FVMin[i] = 0;
+ }
+ m_Frame = 0;
+ m_State = 0;
+ m_pMem = cvCreateMemStorage();
+ m_pFVSeq = NULL;
+
+ SetModuleName("SS");
+ };
+ ~CvBlobTrackFVGenSS()
+ {
+ if(m_pMem)cvReleaseMemStorage(&m_pMem);
+ };
+
+ void AddBlob(CvBlob* pBlob)
+ {
+ //float FV[MAX_FV_SIZE+1];
+ DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
+
+ if(!m_ClearFlag) Clear();
+
+ if(pFVBlob==NULL)
+ {
+ DefBlobFVN BlobNew;
+ BlobNew.blob = pBlob[0];
+ BlobNew.LastFrame = m_Frame;
+ BlobNew.state = 0;;
+ BlobNew.FrameNum = 0;
+ m_BlobList.AddBlob((CvBlob*)&BlobNew);
+ pFVBlob = (DefBlobFVN*)m_BlobList.GetBlobByID(CV_BLOB_ID(pBlob));
+ } /* Add new record if necessary. */
+
+ /* Shift: */
+ for(int i=(BLOB_NUM-1); i>0; --i)
+ {
+ pFVBlob->BlobSeq[i] = pFVBlob->BlobSeq[i-1];
+ }
+
+ pFVBlob->BlobSeq[0] = pBlob[0];
+
+ if(pFVBlob->FrameNum > BLOB_NUM)
+ { /* Average velocity: */
+ CvBlob* pBlobSeq = pFVBlob->BlobSeq;
+ float T = (CV_BLOB_WX(pBlob)+CV_BLOB_WY(pBlob))*0.01f;
+ float AverVx = 0;
+ float AverVy = 0;
+ for(int i=1; i<BLOB_NUM; ++i)
+ {
+ AverVx += CV_BLOB_X(pBlobSeq+i-1)-CV_BLOB_X(pBlobSeq+i);
+ AverVy += CV_BLOB_Y(pBlobSeq+i-1)-CV_BLOB_Y(pBlobSeq+i);
+ }
+ AverVx /= BLOB_NUM-1;
+ AverVy /= BLOB_NUM-1;
+
+ if( fabs(AverVx) < T && fabs(AverVy) < T)
+ pFVBlob->state++;
+ else
+ pFVBlob->state=0;
+ }
+
+ if(pFVBlob->state == 5)
+ { /* Object is stopped: */
+ float FV[MAX_FV_SIZE];
+ FV[0] = pFVBlob->blob.x;
+ FV[1] = pFVBlob->blob.y;
+ FV[2] = pFVBlob->BlobSeq[0].x;
+ FV[3] = pFVBlob->BlobSeq[0].y;
+ *(int*)(FV+m_Dim) = CV_BLOB_ID(pBlob);
+ cvSeqPush( m_pFVSeq, FV );
+ } /* Object is stopped. */
+
+ pFVBlob->FrameNum++;
+ pFVBlob->LastFrame = m_Frame;
+ }; /* AddBlob */
+ void Process(IplImage* pImg, IplImage* /*pFG*/)
+ {
+ int i;
+
+ if(!m_ClearFlag) Clear();
+
+ for(i=m_BlobList.GetBlobNum();i>0;--i)
+ { /* Delete unused blob: */
+ DefBlobFVN* pFVBlob = (DefBlobFVN*)m_BlobList.GetBlob(i-1);
+ if(pFVBlob->LastFrame < m_Frame)
+ {
+ float FV[MAX_FV_SIZE+1];
+ FV[0] = pFVBlob->blob.x;
+ FV[1] = pFVBlob->blob.y;
+ FV[2] = pFVBlob->BlobSeq[0].x;
+ FV[3] = pFVBlob->BlobSeq[0].y;
+ *(int*)(FV+m_Dim) = CV_BLOB_ID(pFVBlob);
+ cvSeqPush( m_pFVSeq, FV );
+ m_BlobList.DelBlob(i-1);
+ }
+ } /* Check next blob in list. */
+
+ /* Set max min range: */
+ m_FVMin[0] = 0;
+ m_FVMin[1] = 0;
+ m_FVMin[2] = 0;
+ m_FVMin[3] = 0;
+ m_FVMax[0] = (float)(pImg->width-1);
+ m_FVMax[1] = (float)(pImg->height-1);
+ m_FVMax[2] = (float)(pImg->width-1);
+ m_FVMax[3] = (float)(pImg->height-1);
+ m_FVVar[0] = m_FVMax[0]*0.01f;
+ m_FVVar[1] = m_FVMax[1]*0.01f;
+ m_FVVar[2] = m_FVMax[2]*0.01f;
+ m_FVVar[3] = m_FVMax[3]*0.01f;
+
+ m_Frame++;
+ m_ClearFlag = 0;
+ };
+ virtual void Release(){delete this;};
+ virtual int GetFVSize(){return m_Dim;};
+ virtual int GetFVNum()
+ {
+ return m_pFVSeq->total;
+ };
+
+ virtual float* GetFV(int index, int* pFVID)
+ {
+ float* pFV = (float*)cvGetSeqElem( m_pFVSeq, index );
+ if(pFVID)pFVID[0] = *(int*)(pFV+m_Dim);
+ return pFV;
+ };
+
+ virtual float* GetFVMin(){return m_FVMin;}; /* returned pointer to array of minimal values of FV, if return 0 then FVrange is not exist */
+ virtual float* GetFVMax(){return m_FVMax;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
+ virtual float* GetFVVar(){return m_FVVar;}; /* returned pointer to array of maximal values of FV, if return 0 then FVrange is not exist */
};/* CvBlobTrackFVGenSS */
inline CvBlobTrackFVGen* cvCreateFVGenSS(){return (CvBlobTrackFVGen*)new CvBlobTrackFVGenSS;}
class DefMat
{
private:
- CvSparseMatIterator m_SparseIterator;
- CvSparseNode* m_pSparseNode;
- int* m_IDXs;
- int m_Dim;
+ CvSparseMatIterator m_SparseIterator;
+ CvSparseNode* m_pSparseNode;
+ int* m_IDXs;
+ int m_Dim;
public:
- CvSparseMat* m_pSparse;
- CvMatND* m_pND;
- int m_Volume;
- int m_Max;
- DefMat(int dim = 0, int* sizes = NULL, int type = SPARSE)
- {
- /* Create sparse or ND matrix but not both: */
- m_pSparseNode = NULL;
- m_pSparse = NULL;
- m_pND = NULL;
- m_Volume = 0;
- m_Max = 0;
- m_IDXs = NULL;
- m_Dim = 0;
- if(dim>0 && sizes != 0)
- Realloc(dim, sizes, type);
- }
- ~DefMat()
- {
- if(m_pSparse)cvReleaseSparseMat(&m_pSparse);
- if(m_pND)cvReleaseMatND(&m_pND);
- if(m_IDXs) cvFree(&m_IDXs);
- }
-
- void Realloc(int dim, int* sizes, int type = SPARSE)
- {
- if(m_pSparse)cvReleaseSparseMat(&m_pSparse);
- if(m_pND)cvReleaseMatND(&m_pND);
-
- if(type == BYSIZE )
- {
- int size = 0;
- int i;
- for(size=1,i=0;i<dim;++i)
- {
- size *= sizes[i];
- }
- size *= sizeof(int);
- if(size > (2<<20))
- { /* if size > 1M */
- type = SPARSE;
- }
- else
- {
- type = ND;
- }
- } /* Define matrix type. */
-
- if(type == SPARSE)
- {
- m_pSparse = cvCreateSparseMat( dim, sizes, CV_32SC1 );
- m_Dim = dim;
- }
- if(type == ND )
- {
- m_pND = cvCreateMatND( dim, sizes, CV_32SC1 );
- cvZero(m_pND);
- m_IDXs = (int*)cvAlloc(sizeof(int)*dim);
- m_Dim = dim;
- }
- m_Volume = 0;
- m_Max = 0;
- }
- void Save(const char* File)
- {
- if(m_pSparse)cvSave(File, m_pSparse );
- if(m_pND)cvSave(File, m_pND );
- }
- void Save(CvFileStorage* fs, const char* name)
- {
- if(m_pSparse)
- {
- cvWrite(fs, name, m_pSparse );
- }
- else if(m_pND)
- {
- cvWrite(fs, name, m_pND );
- }
- }
- void Load(const char* File)
- {
- CvFileStorage* fs = cvOpenFileStorage( File, NULL, CV_STORAGE_READ );
- if(fs)
- {
- void* ptr;
- if(m_pSparse) cvReleaseSparseMat(&m_pSparse);
- if(m_pND) cvReleaseMatND(&m_pND);
- m_Volume = 0;
- m_Max = 0;
- ptr = cvLoad(File);
- if(ptr && CV_IS_MATND_HDR(ptr)) m_pND = (CvMatND*)ptr;
- if(ptr && CV_IS_SPARSE_MAT_HDR(ptr)) m_pSparse = (CvSparseMat*)ptr;
- cvReleaseFileStorage(&fs);
- }
- AfterLoad();
- } /* Load. */
-
- void Load(CvFileStorage* fs, CvFileNode* node, const char* name)
- {
- CvFileNode* n = cvGetFileNodeByName(fs,node,name);
- void* ptr = n?cvRead(fs,n):NULL;
- if(ptr)
- {
- if(m_pSparse) cvReleaseSparseMat(&m_pSparse);
- if(m_pND) cvReleaseMatND(&m_pND);
- m_Volume = 0;
- m_Max = 0;
- if(CV_IS_MATND_HDR(ptr)) m_pND = (CvMatND*)ptr;
- if(CV_IS_SPARSE_MAT_HDR(ptr)) m_pSparse = (CvSparseMat*)ptr;
- }
- else
- {
- printf("WARNING!!! Can't load %s matrix\n",name);
- }
- AfterLoad();
- } /* Load. */
-
- void AfterLoad()
- {
- m_Volume = 0;
- m_Max = 0;
- if(m_pSparse)
- { /* Calculate Volume of loaded hist: */
- CvSparseMatIterator mat_iterator;
- CvSparseNode* node = cvInitSparseMatIterator( m_pSparse, &mat_iterator );
-
- for( ; node != 0; node = cvGetNextSparseNode( &mat_iterator ))
- {
- int val = *(int*)CV_NODE_VAL( m_pSparse, node ); /* get value of the element
+ CvSparseMat* m_pSparse;
+ CvMatND* m_pND;
+ int m_Volume;
+ int m_Max;
+ DefMat(int dim = 0, int* sizes = NULL, int type = SPARSE)
+ {
+ /* Create sparse or ND matrix but not both: */
+ m_pSparseNode = NULL;
+ m_pSparse = NULL;
+ m_pND = NULL;
+ m_Volume = 0;
+ m_Max = 0;
+ m_IDXs = NULL;
+ m_Dim = 0;
+ if(dim>0 && sizes != 0)
+ Realloc(dim, sizes, type);
+ }
+ ~DefMat()
+ {
+ if(m_pSparse)cvReleaseSparseMat(&m_pSparse);
+ if(m_pND)cvReleaseMatND(&m_pND);
+ if(m_IDXs) cvFree(&m_IDXs);
+ }
+
+ void Realloc(int dim, int* sizes, int type = SPARSE)
+ {
+ if(m_pSparse)cvReleaseSparseMat(&m_pSparse);
+ if(m_pND)cvReleaseMatND(&m_pND);
+
+ if(type == BYSIZE )
+ {
+ int size = 0;
+ int i;
+ for(size=1,i=0;i<dim;++i)
+ {
+ size *= sizes[i];
+ }
+ size *= sizeof(int);
+ if(size > (2<<20))
+ { /* if size > 1M */
+ type = SPARSE;
+ }
+ else
+ {
+ type = ND;
+ }
+ } /* Define matrix type. */
+
+ if(type == SPARSE)
+ {
+ m_pSparse = cvCreateSparseMat( dim, sizes, CV_32SC1 );
+ m_Dim = dim;
+ }
+ if(type == ND )
+ {
+ m_pND = cvCreateMatND( dim, sizes, CV_32SC1 );
+ cvZero(m_pND);
+ m_IDXs = (int*)cvAlloc(sizeof(int)*dim);
+ m_Dim = dim;
+ }
+ m_Volume = 0;
+ m_Max = 0;
+ }
+ void Save(const char* File)
+ {
+ if(m_pSparse)cvSave(File, m_pSparse );
+ if(m_pND)cvSave(File, m_pND );
+ }
+ void Save(CvFileStorage* fs, const char* name)
+ {
+ if(m_pSparse)
+ {
+ cvWrite(fs, name, m_pSparse );
+ }
+ else if(m_pND)
+ {
+ cvWrite(fs, name, m_pND );
+ }
+ }
+ void Load(const char* File)
+ {
+ CvFileStorage* fs = cvOpenFileStorage( File, NULL, CV_STORAGE_READ );
+ if(fs)
+ {
+ void* ptr;
+ if(m_pSparse) cvReleaseSparseMat(&m_pSparse);
+ if(m_pND) cvReleaseMatND(&m_pND);
+ m_Volume = 0;
+ m_Max = 0;
+ ptr = cvLoad(File);
+ if(ptr && CV_IS_MATND_HDR(ptr)) m_pND = (CvMatND*)ptr;
+ if(ptr && CV_IS_SPARSE_MAT_HDR(ptr)) m_pSparse = (CvSparseMat*)ptr;
+ cvReleaseFileStorage(&fs);
+ }
+ AfterLoad();
+ } /* Load. */
+
+ void Load(CvFileStorage* fs, CvFileNode* node, const char* name)
+ {
+ CvFileNode* n = cvGetFileNodeByName(fs,node,name);
+ void* ptr = n?cvRead(fs,n):NULL;
+ if(ptr)
+ {
+ if(m_pSparse) cvReleaseSparseMat(&m_pSparse);
+ if(m_pND) cvReleaseMatND(&m_pND);
+ m_Volume = 0;
+ m_Max = 0;
+ if(CV_IS_MATND_HDR(ptr)) m_pND = (CvMatND*)ptr;
+ if(CV_IS_SPARSE_MAT_HDR(ptr)) m_pSparse = (CvSparseMat*)ptr;
+ }
+ else
+ {
+ printf("WARNING!!! Can't load %s matrix\n",name);
+ }
+ AfterLoad();
+ } /* Load. */
+
+ void AfterLoad()
+ {
+ m_Volume = 0;
+ m_Max = 0;
+ if(m_pSparse)
+ { /* Calculate Volume of loaded hist: */
+ CvSparseMatIterator mat_iterator;
+ CvSparseNode* node = cvInitSparseMatIterator( m_pSparse, &mat_iterator );
+
+ for( ; node != 0; node = cvGetNextSparseNode( &mat_iterator ))
+ {
+ int val = *(int*)CV_NODE_VAL( m_pSparse, node ); /* get value of the element
(assume that the type is CV_32SC1) */
- m_Volume += val;
- if(m_Max < val)m_Max = val;
- }
- } /* Calculate Volume of loaded hist. */
-
- if(m_pND)
- { /* Calculate Volume of loaded hist: */
- CvMat mat;
- double max_val;
- double vol;
- cvGetMat( m_pND, &mat, NULL, 1 );
-
- vol = cvSum(&mat).val[0];
- m_Volume = cvRound(vol);
- cvMinMaxLoc( &mat, NULL, &max_val);
- m_Max = cvRound(max_val);
- /* MUST BE WRITTEN LATER */
- } /* Calculate Volume of loaded hist. */
- } /* AfterLoad. */
-
- int* GetPtr(int* indx)
- {
- if(m_pSparse) return (int*)cvPtrND( m_pSparse, indx, NULL, 1, NULL);
- if(m_pND) return (int*)cvPtrND( m_pND, indx, NULL, 1, NULL);
- return NULL;
- } /* GetPtr. */
-
- int GetVal(int* indx)
- {
- int* p = GetPtr(indx);
- if(p)return p[0];
- return -1;
- } /* GetVal. */
-
- int Add(int* indx, int val)
- {
- int NewVal;
- int* pVal = GetPtr(indx);
- if(pVal == NULL) return -1;
- pVal[0] += val;
- NewVal = pVal[0];
- m_Volume += val;
- if(m_Max < NewVal)m_Max = NewVal;
- return NewVal;
- } /* Add. */
-
- void Add(DefMat* pMatAdd)
- {
- int* pIDXS = NULL;
- int Val = 0;
- for(Val = pMatAdd->GetNext(&pIDXS, 1 );pIDXS;Val=pMatAdd->GetNext(&pIDXS, 0 ))
- {
- Add(pIDXS,Val);
- }
- } /* Add. */
-
- int SetMax(int* indx, int val)
- {
- int NewVal;
- int* pVal = GetPtr(indx);
- if(pVal == NULL) return -1;
- if(val > pVal[0])
- {
- m_Volume += val-pVal[0];
- pVal[0] = val;
- }
- NewVal = pVal[0];
- if(m_Max < NewVal)m_Max = NewVal;
- return NewVal;
- } /* Add. */
-
- int GetNext(int** pIDXS, int init = 0)
- {
- int Val = 0;
- pIDXS[0] = NULL;
- if(m_pSparse)
- {
- m_pSparseNode = (init || m_pSparseNode==NULL)?
- cvInitSparseMatIterator( m_pSparse, &m_SparseIterator ):
- cvGetNextSparseNode( &m_SparseIterator );
-
- if(m_pSparseNode)
- {
- int* pVal = (int*)CV_NODE_VAL( m_pSparse, m_pSparseNode );
- if(pVal)Val = pVal[0];
- pIDXS[0] = CV_NODE_IDX( m_pSparse, m_pSparseNode );
- }
- }/* Sparse matrix. */
-
- if(m_pND)
- {
- int i;
- if(init)
- {
- for(i=0;i<m_Dim;++i)
- {
- m_IDXs[i] = cvGetDimSize( m_pND, i )-1;
- }
- pIDXS[0] = m_IDXs;
- Val = GetVal(m_IDXs);
- }
- else
- {
- for(i=0;i<m_Dim;++i)
- {
- if((m_IDXs[i]--)>0)
- break;
- m_IDXs[i] = cvGetDimSize( m_pND, i )-1;
- }
- if(i==m_Dim)
- {
- pIDXS[0] = NULL;
- }
- else
- {
- pIDXS[0] = m_IDXs;
- Val = GetVal(m_IDXs);
- }
-
- } /* Get next ND. */
-
- } /* Sparse matrix. */
-
- return Val;
-
- }; /* GetNext. */
+ m_Volume += val;
+ if(m_Max < val)m_Max = val;
+ }
+ } /* Calculate Volume of loaded hist. */
+
+ if(m_pND)
+ { /* Calculate Volume of loaded hist: */
+ CvMat mat;
+ double max_val;
+ double vol;
+ cvGetMat( m_pND, &mat, NULL, 1 );
+
+ vol = cvSum(&mat).val[0];
+ m_Volume = cvRound(vol);
+ cvMinMaxLoc( &mat, NULL, &max_val);
+ m_Max = cvRound(max_val);
+ /* MUST BE WRITTEN LATER */
+ } /* Calculate Volume of loaded hist. */
+ } /* AfterLoad. */
+
+ int* GetPtr(int* indx)
+ {
+ if(m_pSparse) return (int*)cvPtrND( m_pSparse, indx, NULL, 1, NULL);
+ if(m_pND) return (int*)cvPtrND( m_pND, indx, NULL, 1, NULL);
+ return NULL;
+ } /* GetPtr. */
+
+ int GetVal(int* indx)
+ {
+ int* p = GetPtr(indx);
+ if(p)return p[0];
+ return -1;
+ } /* GetVal. */
+
+ int Add(int* indx, int val)
+ {
+ int NewVal;
+ int* pVal = GetPtr(indx);
+ if(pVal == NULL) return -1;
+ pVal[0] += val;
+ NewVal = pVal[0];
+ m_Volume += val;
+ if(m_Max < NewVal)m_Max = NewVal;
+ return NewVal;
+ } /* Add. */
+
+ void Add(DefMat* pMatAdd)
+ {
+ int* pIDXS = NULL;
+ int Val = 0;
+ for(Val = pMatAdd->GetNext(&pIDXS, 1 );pIDXS;Val=pMatAdd->GetNext(&pIDXS, 0 ))
+ {
+ Add(pIDXS,Val);
+ }
+ } /* Add. */
+
+ int SetMax(int* indx, int val)
+ {
+ int NewVal;
+ int* pVal = GetPtr(indx);
+ if(pVal == NULL) return -1;
+ if(val > pVal[0])
+ {
+ m_Volume += val-pVal[0];
+ pVal[0] = val;
+ }
+ NewVal = pVal[0];
+ if(m_Max < NewVal)m_Max = NewVal;
+ return NewVal;
+ } /* Add. */
+
+ int GetNext(int** pIDXS, int init = 0)
+ {
+ int Val = 0;
+ pIDXS[0] = NULL;
+ if(m_pSparse)
+ {
+ m_pSparseNode = (init || m_pSparseNode==NULL)?
+ cvInitSparseMatIterator( m_pSparse, &m_SparseIterator ):
+ cvGetNextSparseNode( &m_SparseIterator );
+
+ if(m_pSparseNode)
+ {
+ int* pVal = (int*)CV_NODE_VAL( m_pSparse, m_pSparseNode );
+ if(pVal)Val = pVal[0];
+ pIDXS[0] = CV_NODE_IDX( m_pSparse, m_pSparseNode );
+ }
+ }/* Sparse matrix. */
+
+ if(m_pND)
+ {
+ int i;
+ if(init)
+ {
+ for(i=0;i<m_Dim;++i)
+ {
+ m_IDXs[i] = cvGetDimSize( m_pND, i )-1;
+ }
+ pIDXS[0] = m_IDXs;
+ Val = GetVal(m_IDXs);
+ }
+ else
+ {
+ for(i=0;i<m_Dim;++i)
+ {
+ if((m_IDXs[i]--)>0)
+ break;
+ m_IDXs[i] = cvGetDimSize( m_pND, i )-1;
+ }
+ if(i==m_Dim)
+ {
+ pIDXS[0] = NULL;
+ }
+ else
+ {
+ pIDXS[0] = m_IDXs;
+ Val = GetVal(m_IDXs);
+ }
+
+ } /* Get next ND. */
+
+ } /* Sparse matrix. */
+
+ return Val;
+
+ }; /* GetNext. */
};
#define FV_NUM 10
#define FV_SIZE 10
typedef struct DefTrackFG
{
- CvBlob blob;
- // CvBlobTrackFVGen* pFVGen;
- int LastFrame;
- float state;
- DefMat* pHist;
+ CvBlob blob;
+ // CvBlobTrackFVGen* pFVGen;
+ int LastFrame;
+ float state;
+ DefMat* pHist;
} DefTrackFG;
class CvBlobTrackAnalysisHist : public CvBlobTrackAnalysis
{
- /*---------------- Internal functions: --------------------*/
+ /*---------------- Internal functions: --------------------*/
private:
- int m_BinNumParam;
- int m_SmoothRadius;
- const char* m_SmoothKernel;
- float m_AbnormalThreshold;
- int m_TrackNum;
- int m_Frame;
- int m_BinNum;
- char m_DataFileName[1024];
- int m_Dim;
- int* m_Sizes;
- DefMat m_HistMat;
- int m_HistVolumeSaved;
- int* m_pFVi;
- int* m_pFViVar;
- int* m_pFViVarRes;
- CvBlobSeq m_TrackFGList;
- //CvBlobTrackFVGen* (*m_CreateFVGen)();
- CvBlobTrackFVGen* m_pFVGen;
- void SaveHist()
- {
- if(m_DataFileName[0])
- {
- m_HistMat.Save(m_DataFileName);
- m_HistVolumeSaved = m_HistMat.m_Volume;
- }
- };
- void LoadHist()
- {
- if(m_DataFileName[0])m_HistMat.Load(m_DataFileName);
- m_HistVolumeSaved = m_HistMat.m_Volume;
- }
- void AllocData()
- { /* AllocData: */
- m_pFVi = (int*)cvAlloc(sizeof(int)*m_Dim);
- m_pFViVar = (int*)cvAlloc(sizeof(int)*m_Dim);
- m_pFViVarRes = (int*)cvAlloc(sizeof(int)*m_Dim);
- m_Sizes = (int*)cvAlloc(sizeof(int)*m_Dim);
-
- { /* Create init sparce matrix: */
- int i;
- for(i=0;i<m_Dim;++i)m_Sizes[i] = m_BinNum;
- m_HistMat.Realloc(m_Dim,m_Sizes,SPARSE);
- m_HistVolumeSaved = 0;
- } /* Create init sparce matrix. */
- } /* AllocData. */
-
- void FreeData()
- { /* FreeData. */
- int i;
- for(i=m_TrackFGList.GetBlobNum();i>0;--i)
- {
- //DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i-1);
- // pF->pFVGen->Release();
- m_TrackFGList.DelBlob(i-1);
- }
- cvFree(&m_pFVi);
- cvFree(&m_pFViVar);
- cvFree(&m_pFViVarRes);
- cvFree(&m_Sizes);
- } /* FreeData. */
-
- virtual void ParamUpdate()
- {
- if(m_BinNum != m_BinNumParam)
- {
- FreeData();
- m_BinNum = m_BinNumParam;
- AllocData();
- }
- }
+ int m_BinNumParam;
+ int m_SmoothRadius;
+ const char* m_SmoothKernel;
+ float m_AbnormalThreshold;
+ int m_TrackNum;
+ int m_Frame;
+ int m_BinNum;
+ char m_DataFileName[1024];
+ int m_Dim;
+ int* m_Sizes;
+ DefMat m_HistMat;
+ int m_HistVolumeSaved;
+ int* m_pFVi;
+ int* m_pFViVar;
+ int* m_pFViVarRes;
+ CvBlobSeq m_TrackFGList;
+ //CvBlobTrackFVGen* (*m_CreateFVGen)();
+ CvBlobTrackFVGen* m_pFVGen;
+ void SaveHist()
+ {
+ if(m_DataFileName[0])
+ {
+ m_HistMat.Save(m_DataFileName);
+ m_HistVolumeSaved = m_HistMat.m_Volume;
+ }
+ };
+ void LoadHist()
+ {
+ if(m_DataFileName[0])m_HistMat.Load(m_DataFileName);
+ m_HistVolumeSaved = m_HistMat.m_Volume;
+ }
+ void AllocData()
+ { /* AllocData: */
+ m_pFVi = (int*)cvAlloc(sizeof(int)*m_Dim);
+ m_pFViVar = (int*)cvAlloc(sizeof(int)*m_Dim);
+ m_pFViVarRes = (int*)cvAlloc(sizeof(int)*m_Dim);
+ m_Sizes = (int*)cvAlloc(sizeof(int)*m_Dim);
+
+ { /* Create init sparce matrix: */
+ int i;
+ for(i=0;i<m_Dim;++i)m_Sizes[i] = m_BinNum;
+ m_HistMat.Realloc(m_Dim,m_Sizes,SPARSE);
+ m_HistVolumeSaved = 0;
+ } /* Create init sparce matrix. */
+ } /* AllocData. */
+
+ void FreeData()
+ { /* FreeData. */
+ int i;
+ for(i=m_TrackFGList.GetBlobNum();i>0;--i)
+ {
+ //DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i-1);
+ // pF->pFVGen->Release();
+ m_TrackFGList.DelBlob(i-1);
+ }
+ cvFree(&m_pFVi);
+ cvFree(&m_pFViVar);
+ cvFree(&m_pFViVarRes);
+ cvFree(&m_Sizes);
+ } /* FreeData. */
+
+ virtual void ParamUpdate()
+ {
+ if(m_BinNum != m_BinNumParam)
+ {
+ FreeData();
+ m_BinNum = m_BinNumParam;
+ AllocData();
+ }
+ }
public:
- CvBlobTrackAnalysisHist(CvBlobTrackFVGen* (*createFVGen)()):m_TrackFGList(sizeof(DefTrackFG))
- {
- m_pFVGen = createFVGen();
- m_Dim = m_pFVGen->GetFVSize();
- m_Frame = 0;
- m_pFVi = 0;
- m_TrackNum = 0;
- m_BinNum = 32;
- m_DataFileName[0] = 0;
-
- m_AbnormalThreshold = 0.02f;
- AddParam("AbnormalThreshold",&m_AbnormalThreshold);
- CommentParam("AbnormalThreshold","If trajectory histogram value is lesst then <AbnormalThreshold*DataBaseTrackNum> then trajectory is abnormal");
-
- m_SmoothRadius = 1;
- AddParam("SmoothRadius",&m_SmoothRadius);
- CommentParam("AbnormalThreshold","Radius (in bins) for histogram smoothing");
-
- m_SmoothKernel = "L";
- AddParam("SmoothKernel",&m_SmoothKernel);
- CommentParam("SmoothKernel","L - Linear, G - Gaussian");
-
-
- m_BinNumParam = m_BinNum;
- AddParam("BinNum",&m_BinNumParam);
- CommentParam("BinNum","Number of bin for each dimention of feature vector");
-
- AllocData();
- SetModuleName("Hist");
-
- } /* Constructor. */
-
- ~CvBlobTrackAnalysisHist()
- {
- SaveHist();
- FreeData();
- m_pFVGen->Release();
- } /* Destructor. */
-
- /*----------------- Interface: --------------------*/
- virtual void AddBlob(CvBlob* pBlob)
- {
- DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(CV_BLOB_ID(pBlob));
- if(pF == NULL)
- { /* create new filter */
- DefTrackFG F;
- F.state = 0;
- F.blob = pBlob[0];
- F.LastFrame = m_Frame;
- // F.pFVGen = m_CreateFVGen();
- F.pHist = new DefMat(m_Dim,m_Sizes,SPARSE);
- m_TrackFGList.AddBlob((CvBlob*)&F);
- pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(CV_BLOB_ID(pBlob));
- }
-
- assert(pF);
- pF->blob = pBlob[0];
- pF->LastFrame = m_Frame;
- m_pFVGen->AddBlob(pBlob);
- };
- virtual void Process(IplImage* pImg, IplImage* pFG)
- {
- int i;
- m_pFVGen->Process(pImg, pFG);
- int SK = m_SmoothKernel[0];
-
- for(i=0; i<m_pFVGen->GetFVNum(); ++i)
- {
- int BlobID = 0;
- float* pFV = m_pFVGen->GetFV(i,&BlobID);
- float* pFVMax = m_pFVGen->GetFVMax();
- float* pFVMin = m_pFVGen->GetFVMin();
- DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(BlobID);
- int HistVal = 1;
-
- if(pFV==NULL) break;
-
- pF->LastFrame = m_Frame;
-
- { /* Binarize FV: */
- int j;
- for(j=0; j<m_Dim; ++j)
- {
- int index;
- float f0 = pFVMin?pFVMin[j]:0;
- float f1 = pFVMax?pFVMax[j]:1;
- assert(f1>f0);
- index = cvRound((m_BinNum-1)*(pFV[j]-f0)/(f1-f0));
- if(index<0)index=0;
- if(index>=m_BinNum)index=m_BinNum-1;
- m_pFVi[j] = index;
- }
- }
-
- HistVal = m_HistMat.GetVal(m_pFVi);/* get bin value*/
- pF->state = 0;
- { /* Calculate state: */
- float T = m_HistMat.m_Max*m_AbnormalThreshold; /* calc threshold */
-
- if(m_TrackNum>0) T = 256.0f * m_TrackNum*m_AbnormalThreshold;
- if(T>0)
- {
- pF->state = (T - HistVal)/(T*0.2f) + 0.5f;
- }
- if(pF->state<0)pF->state=0;
- if(pF->state>1)pF->state=1;
- }
-
- { /* If it is a new FV then add it to trajectory histogram: */
- int i,flag = 1;
- int r = m_SmoothRadius;
-
- // printf("BLob %3d NEW FV [", CV_BLOB_ID(pF));
- // for(i=0;i<m_Dim;++i) printf("%d,", m_pFVi[i]);
- // printf("]");
-
- for(i=0; i<m_Dim; ++i)
- {
- m_pFViVar[i]=-r;
- }
-
- while(flag)
- {
- float dist = 0;
- int HistAdd = 0;
- int i;
- int good = 1;
- for(i=0; i<m_Dim; ++i)
- {
- m_pFViVarRes[i] = m_pFVi[i]+m_pFViVar[i];
- if(m_pFViVarRes[i]<0) good= 0;
- if(m_pFViVarRes[i]>=m_BinNum) good= 0;
- dist += m_pFViVar[i]*m_pFViVar[i];
- }/* Calculate next dimension. */
-
- if(SK=='G' || SK=='g')
- {
- double dist2 = dist/(r*r);
- HistAdd = cvRound(256*exp(-dist2)); /* Hist Add for (dist=1) = 25.6*/
- }
- else if(SK=='L' || SK=='l')
- {
- dist = (float)(sqrt(dist)/(r+1));
- HistAdd = cvRound(256*(1-dist));
- }
- else
- {
- HistAdd = 255; /* Flat smoothing. */
- }
-
- if(good && HistAdd>0)
- { /* Update histogram: */
- assert(pF->pHist);
- pF->pHist->SetMax(m_pFViVarRes, HistAdd);
- } /* Update histogram. */
-
- for(i=0; i<m_Dim; ++i)
- { /* Next config: */
- if((m_pFViVar[i]++) < r)
- break;
- m_pFViVar[i] = -r;
- } /* Increase next dimension variable. */
- if(i==m_Dim)break;
- } /* Next variation. */
- } /* If new FV. */
- } /* Next FV. */
-
- { /* Check all blobs on list: */
- int i;
- for(i=m_TrackFGList.GetBlobNum(); i>0; --i)
- { /* Add histogram and delete blob from list: */
- DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i-1);
- if(pF->LastFrame+3 < m_Frame && pF->pHist)
- {
- m_HistMat.Add(pF->pHist);
- delete pF->pHist;
- m_TrackNum++;
- m_TrackFGList.DelBlob(i-1);
- }
- }/* next blob */
- }
-
- m_Frame++;
-
- if(m_Wnd)
- { /* Debug output: */
- int* idxs = NULL;
- int Val = 0;
- IplImage* pI = cvCloneImage(pImg);
-
- cvZero(pI);
-
- for(Val = m_HistMat.GetNext(&idxs,1); idxs; Val=m_HistMat.GetNext(&idxs,0))
- { /* Draw all elements: */
- float vf;
- int x,y;
-
- if(!idxs) break;
- if(Val == 0) continue;
-
- vf = (float)Val/(m_HistMat.m_Max?m_HistMat.m_Max:1);
- x = cvRound((float)(pI->width-1)*(float)idxs[0] / (float)m_BinNum);
- y = cvRound((float)(pI->height-1)*(float)idxs[1] / (float)m_BinNum);
-
- cvCircle(pI, cvPoint(x,y), cvRound(vf*pI->height/(m_BinNum*2)),CV_RGB(255,0,0),CV_FILLED);
- if(m_Dim > 3)
- {
- int dx = -2*(idxs[2]-m_BinNum/2);
- int dy = -2*(idxs[3]-m_BinNum/2);
- cvLine(pI,cvPoint(x,y),cvPoint(x+dx,y+dy),CV_RGB(0,cvRound(vf*255),1));
- }
- if( m_Dim==4 &&
- m_pFVGen->GetFVMax()[0]==m_pFVGen->GetFVMax()[2] &&
- m_pFVGen->GetFVMax()[1]==m_pFVGen->GetFVMax()[3])
- {
- int x = cvRound((float)(pI->width-1)*(float)idxs[2] / (float)m_BinNum);
- int y = cvRound((float)(pI->height-1)*(float)idxs[3] / (float)m_BinNum);
- cvCircle(pI, cvPoint(x,y), cvRound(vf*pI->height/(m_BinNum*2)),CV_RGB(0,0,255),CV_FILLED);
- }
- } /* Draw all elements. */
-
- for(i=m_TrackFGList.GetBlobNum();i>0;--i)
- {
- DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i-1);
- DefMat* pHist = pF?pF->pHist:NULL;
-
- if(pHist==NULL) continue;
-
- for(Val = pHist->GetNext(&idxs,1);idxs;Val=pHist->GetNext(&idxs,0))
- { /* Draw all elements: */
- float vf;
- int x,y;
-
- if(!idxs) break;
- if(Val == 0) continue;
-
- vf = (float)Val/(pHist->m_Max?pHist->m_Max:1);
- x = cvRound((float)(pI->width-1)*(float)idxs[0] / (float)m_BinNum);
- y = cvRound((float)(pI->height-1)*(float)idxs[1] / (float)m_BinNum);
-
- cvCircle(pI, cvPoint(x,y), cvRound(2*vf),CV_RGB(0,0,cvRound(255*vf)),CV_FILLED);
- if(m_Dim > 3)
- {
- int dx = -2*(idxs[2]-m_BinNum/2);
- int dy = -2*(idxs[3]-m_BinNum/2);
- cvLine(pI,cvPoint(x,y),cvPoint(x+dx,y+dy),CV_RGB(0,0,255));
- }
- if( m_Dim==4 &&
- m_pFVGen->GetFVMax()[0]==m_pFVGen->GetFVMax()[2] &&
- m_pFVGen->GetFVMax()[1]==m_pFVGen->GetFVMax()[3])
- { /* if SS feature vector */
- int x = cvRound((float)(pI->width-1)*(float)idxs[2] / (float)m_BinNum);
- int y = cvRound((float)(pI->height-1)*(float)idxs[3] / (float)m_BinNum);
- cvCircle(pI, cvPoint(x,y), cvRound(vf*pI->height/(m_BinNum*2)),CV_RGB(0,0,255),CV_FILLED);
- }
- } /* Draw all elements. */
- } /* Next track. */
-
- //cvNamedWindow("Hist",0);
- //cvShowImage("Hist", pI);
- cvReleaseImage(&pI);
- }
- };
-
- float GetState(int BlobID)
- {
- DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(BlobID);
- return pF?pF->state:0.0f;
- };
-
- /* Return 0 if trajectory is normal;
+ CvBlobTrackAnalysisHist(CvBlobTrackFVGen* (*createFVGen)()):m_TrackFGList(sizeof(DefTrackFG))
+ {
+ m_pFVGen = createFVGen();
+ m_Dim = m_pFVGen->GetFVSize();
+ m_Frame = 0;
+ m_pFVi = 0;
+ m_TrackNum = 0;
+ m_BinNum = 32;
+ m_DataFileName[0] = 0;
+
+ m_AbnormalThreshold = 0.02f;
+ AddParam("AbnormalThreshold",&m_AbnormalThreshold);
+ CommentParam("AbnormalThreshold","If trajectory histogram value is lesst then <AbnormalThreshold*DataBaseTrackNum> then trajectory is abnormal");
+
+ m_SmoothRadius = 1;
+ AddParam("SmoothRadius",&m_SmoothRadius);
+ CommentParam("AbnormalThreshold","Radius (in bins) for histogram smoothing");
+
+ m_SmoothKernel = "L";
+ AddParam("SmoothKernel",&m_SmoothKernel);
+ CommentParam("SmoothKernel","L - Linear, G - Gaussian");
+
+
+ m_BinNumParam = m_BinNum;
+ AddParam("BinNum",&m_BinNumParam);
+ CommentParam("BinNum","Number of bin for each dimention of feature vector");
+
+ AllocData();
+ SetModuleName("Hist");
+
+ } /* Constructor. */
+
+ ~CvBlobTrackAnalysisHist()
+ {
+ SaveHist();
+ FreeData();
+ m_pFVGen->Release();
+ } /* Destructor. */
+
+ /*----------------- Interface: --------------------*/
+ virtual void AddBlob(CvBlob* pBlob)
+ {
+ DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(CV_BLOB_ID(pBlob));
+ if(pF == NULL)
+ { /* create new filter */
+ DefTrackFG F;
+ F.state = 0;
+ F.blob = pBlob[0];
+ F.LastFrame = m_Frame;
+ // F.pFVGen = m_CreateFVGen();
+ F.pHist = new DefMat(m_Dim,m_Sizes,SPARSE);
+ m_TrackFGList.AddBlob((CvBlob*)&F);
+ pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(CV_BLOB_ID(pBlob));
+ }
+
+ assert(pF);
+ pF->blob = pBlob[0];
+ pF->LastFrame = m_Frame;
+ m_pFVGen->AddBlob(pBlob);
+ };
+ virtual void Process(IplImage* pImg, IplImage* pFG)
+ {
+ m_pFVGen->Process(pImg, pFG);
+ int SK = m_SmoothKernel[0];
+
+ for(int i=0; i<m_pFVGen->GetFVNum(); ++i)
+ {
+ int BlobID = 0;
+ float* pFV = m_pFVGen->GetFV(i,&BlobID);
+ float* pFVMax = m_pFVGen->GetFVMax();
+ float* pFVMin = m_pFVGen->GetFVMin();
+ DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(BlobID);
+ int HistVal = 1;
+
+ if(pFV==NULL) break;
+
+ pF->LastFrame = m_Frame;
+
+ { /* Binarize FV: */
+ int j;
+ for(j=0; j<m_Dim; ++j)
+ {
+ int index;
+ float f0 = pFVMin?pFVMin[j]:0;
+ float f1 = pFVMax?pFVMax[j]:1;
+ assert(f1>f0);
+ index = cvRound((m_BinNum-1)*(pFV[j]-f0)/(f1-f0));
+ if(index<0)index=0;
+ if(index>=m_BinNum)index=m_BinNum-1;
+ m_pFVi[j] = index;
+ }
+ }
+
+ HistVal = m_HistMat.GetVal(m_pFVi);/* get bin value*/
+ pF->state = 0;
+ { /* Calculate state: */
+ float T = m_HistMat.m_Max*m_AbnormalThreshold; /* calc threshold */
+
+ if(m_TrackNum>0) T = 256.0f * m_TrackNum*m_AbnormalThreshold;
+ if(T>0)
+ {
+ pF->state = (T - HistVal)/(T*0.2f) + 0.5f;
+ }
+ if(pF->state<0)pF->state=0;
+ if(pF->state>1)pF->state=1;
+ }
+
+ { /* If it is a new FV then add it to trajectory histogram: */
+ int flag = 1;
+ int r = m_SmoothRadius;
+
+ // printf("BLob %3d NEW FV [", CV_BLOB_ID(pF));
+ // for(i=0;i<m_Dim;++i) printf("%d,", m_pFVi[i]);
+ // printf("]");
+
+ for(int k=0; k<m_Dim; ++k)
+ {
+ m_pFViVar[k]=-r;
+ }
+
+ while(flag)
+ {
+ float dist = 0;
+ int HistAdd = 0;
+ int good = 1;
+ for(int k=0; k<m_Dim; ++k)
+ {
+ m_pFViVarRes[k] = m_pFVi[k]+m_pFViVar[k];
+ if(m_pFViVarRes[k]<0) good= 0;
+ if(m_pFViVarRes[k]>=m_BinNum) good= 0;
+ dist += m_pFViVar[k]*m_pFViVar[k];
+ }/* Calculate next dimension. */
+
+ if(SK=='G' || SK=='g')
+ {
+ double dist2 = dist/(r*r);
+ HistAdd = cvRound(256*exp(-dist2)); /* Hist Add for (dist=1) = 25.6*/
+ }
+ else if(SK=='L' || SK=='l')
+ {
+ dist = (float)(sqrt(dist)/(r+1));
+ HistAdd = cvRound(256*(1-dist));
+ }
+ else
+ {
+ HistAdd = 255; /* Flat smoothing. */
+ }
+
+ if(good && HistAdd>0)
+ { /* Update histogram: */
+ assert(pF->pHist);
+ pF->pHist->SetMax(m_pFViVarRes, HistAdd);
+ } /* Update histogram. */
+
+ int idx = 0;
+ for( ; idx<m_Dim; ++idx)
+ { /* Next config: */
+ if((m_pFViVar[idx]++) < r)
+ break;
+ m_pFViVar[idx] = -r;
+ } /* Increase next dimension variable. */
+ if(idx==m_Dim)break;
+ } /* Next variation. */
+ } /* If new FV. */
+ } /* Next FV. */
+
+ { /* Check all blobs on list: */
+ int i;
+ for(i=m_TrackFGList.GetBlobNum(); i>0; --i)
+ { /* Add histogram and delete blob from list: */
+ DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i-1);
+ if(pF->LastFrame+3 < m_Frame && pF->pHist)
+ {
+ m_HistMat.Add(pF->pHist);
+ delete pF->pHist;
+ m_TrackNum++;
+ m_TrackFGList.DelBlob(i-1);
+ }
+ }/* next blob */
+ }
+
+ m_Frame++;
+
+ if(m_Wnd)
+ { /* Debug output: */
+ int* idxs = NULL;
+ int Val = 0;
+ IplImage* pI = cvCloneImage(pImg);
+
+ cvZero(pI);
+
+ for(Val = m_HistMat.GetNext(&idxs,1); idxs; Val=m_HistMat.GetNext(&idxs,0))
+ { /* Draw all elements: */
+ if(!idxs) break;
+ if(Val == 0) continue;
+
+ float vf = (float)Val/(m_HistMat.m_Max?m_HistMat.m_Max:1);
+ int x = cvRound((float)(pI->width-1)*(float)idxs[0] / (float)m_BinNum);
+ int y = cvRound((float)(pI->height-1)*(float)idxs[1] / (float)m_BinNum);
+
+ cvCircle(pI, cvPoint(x,y), cvRound(vf*pI->height/(m_BinNum*2)),CV_RGB(255,0,0),CV_FILLED);
+ if(m_Dim > 3)
+ {
+ int dx = -2*(idxs[2]-m_BinNum/2);
+ int dy = -2*(idxs[3]-m_BinNum/2);
+ cvLine(pI,cvPoint(x,y),cvPoint(x+dx,y+dy),CV_RGB(0,cvRound(vf*255),1));
+ }
+ if( m_Dim==4 &&
+ m_pFVGen->GetFVMax()[0]==m_pFVGen->GetFVMax()[2] &&
+ m_pFVGen->GetFVMax()[1]==m_pFVGen->GetFVMax()[3])
+ {
+ int x1 = cvRound((float)(pI->width-1)*(float)idxs[2] / (float)m_BinNum);
+ int y1 = cvRound((float)(pI->height-1)*(float)idxs[3] / (float)m_BinNum);
+ cvCircle(pI, cvPoint(x1,y1), cvRound(vf*pI->height/(m_BinNum*2)),CV_RGB(0,0,255),CV_FILLED);
+ }
+ } /* Draw all elements. */
+
+ for(int i=m_TrackFGList.GetBlobNum();i>0;--i)
+ {
+ DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(i-1);
+ DefMat* pHist = pF?pF->pHist:NULL;
+
+ if(pHist==NULL) continue;
+
+ for(Val = pHist->GetNext(&idxs,1);idxs;Val=pHist->GetNext(&idxs,0))
+ { /* Draw all elements: */
+ float vf;
+ int x,y;
+
+ if(!idxs) break;
+ if(Val == 0) continue;
+
+ vf = (float)Val/(pHist->m_Max?pHist->m_Max:1);
+ x = cvRound((float)(pI->width-1)*(float)idxs[0] / (float)m_BinNum);
+ y = cvRound((float)(pI->height-1)*(float)idxs[1] / (float)m_BinNum);
+
+ cvCircle(pI, cvPoint(x,y), cvRound(2*vf),CV_RGB(0,0,cvRound(255*vf)),CV_FILLED);
+ if(m_Dim > 3)
+ {
+ int dx = -2*(idxs[2]-m_BinNum/2);
+ int dy = -2*(idxs[3]-m_BinNum/2);
+ cvLine(pI,cvPoint(x,y),cvPoint(x+dx,y+dy),CV_RGB(0,0,255));
+ }
+ if( m_Dim==4 &&
+ m_pFVGen->GetFVMax()[0]==m_pFVGen->GetFVMax()[2] &&
+ m_pFVGen->GetFVMax()[1]==m_pFVGen->GetFVMax()[3])
+ { /* if SS feature vector */
+ int x1 = cvRound((float)(pI->width-1)*(float)idxs[2] / (float)m_BinNum);
+ int y1 = cvRound((float)(pI->height-1)*(float)idxs[3] / (float)m_BinNum);
+ cvCircle(pI, cvPoint(x1,y1), cvRound(vf*pI->height/(m_BinNum*2)),CV_RGB(0,0,255),CV_FILLED);
+ }
+ } /* Draw all elements. */
+ } /* Next track. */
+
+ //cvNamedWindow("Hist",0);
+ //cvShowImage("Hist", pI);
+ cvReleaseImage(&pI);
+ }
+ };
+
+ float GetState(int BlobID)
+ {
+ DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(BlobID);
+ return pF?pF->state:0.0f;
+ };
+
+ /* Return 0 if trajectory is normal;
rreturn >0 if trajectory abnormal. */
- virtual const char* GetStateDesc(int BlobID)
- {
- if(GetState(BlobID)>0.5) return "abnormal";
- return NULL;
- }
-
- virtual void SetFileName(char* DataBaseName)
- {
- if(m_HistMat.m_Volume!=m_HistVolumeSaved)SaveHist();
- m_DataFileName[0] = m_DataFileName[1000] = 0;
-
- if(DataBaseName)
- {
- strncpy(m_DataFileName,DataBaseName,1000);
- strcat(m_DataFileName, ".yml");
- }
- LoadHist();
- };
-
- virtual void SaveState(CvFileStorage* fs)
- {
- int b, bN = m_TrackFGList.GetBlobNum();
- cvWriteInt(fs,"BlobNum",bN);
- cvStartWriteStruct(fs,"BlobList",CV_NODE_SEQ);
-
- for(b=0; b<bN; ++b)
- {
- DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(b);
- cvStartWriteStruct(fs,NULL,CV_NODE_MAP);
- cvWriteStruct(fs,"Blob", &(pF->blob), "ffffi");
- cvWriteInt(fs,"LastFrame",pF->LastFrame);
- cvWriteReal(fs,"State",pF->state);
- pF->pHist->Save(fs, "Hist");
- cvEndWriteStruct(fs);
- }
- cvEndWriteStruct(fs);
- m_HistMat.Save(fs, "Hist");
- };
-
- virtual void LoadState(CvFileStorage* fs, CvFileNode* node)
- {
- CvFileNode* pBLN = cvGetFileNodeByName(fs,node,"BlobList");
-
- if(pBLN && CV_NODE_IS_SEQ(pBLN->tag))
- {
- int b, bN = pBLN->data.seq->total;
- for(b=0; b<bN; ++b)
- {
- DefTrackFG* pF = NULL;
- CvBlob Blob;
- CvFileNode* pBN = (CvFileNode*)cvGetSeqElem(pBLN->data.seq,b);
-
- assert(pBN);
- cvReadStructByName(fs, pBN, "Blob", &Blob, "ffffi");
- AddBlob(&Blob);
- pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(Blob.ID);
- if(pF==NULL) continue;
- assert(pF);
- pF->state = (float)cvReadIntByName(fs,pBN,"State",cvRound(pF->state));
- assert(pF->pHist);
- pF->pHist->Load(fs,pBN,"Hist");
- }
- }
-
- m_HistMat.Load(fs, node, "Hist");
- }; /* LoadState */
-
-
- virtual void Release(){ delete this; };
+ virtual const char* GetStateDesc(int BlobID)
+ {
+ if(GetState(BlobID)>0.5) return "abnormal";
+ return NULL;
+ }
+
+ virtual void SetFileName(char* DataBaseName)
+ {
+ if(m_HistMat.m_Volume!=m_HistVolumeSaved)SaveHist();
+ m_DataFileName[0] = m_DataFileName[1000] = 0;
+
+ if(DataBaseName)
+ {
+ strncpy(m_DataFileName,DataBaseName,1000);
+ strcat(m_DataFileName, ".yml");
+ }
+ LoadHist();
+ };
+
+ virtual void SaveState(CvFileStorage* fs)
+ {
+ int b, bN = m_TrackFGList.GetBlobNum();
+ cvWriteInt(fs,"BlobNum",bN);
+ cvStartWriteStruct(fs,"BlobList",CV_NODE_SEQ);
+
+ for(b=0; b<bN; ++b)
+ {
+ DefTrackFG* pF = (DefTrackFG*)m_TrackFGList.GetBlob(b);
+ cvStartWriteStruct(fs,NULL,CV_NODE_MAP);
+ cvWriteStruct(fs,"Blob", &(pF->blob), "ffffi");
+ cvWriteInt(fs,"LastFrame",pF->LastFrame);
+ cvWriteReal(fs,"State",pF->state);
+ pF->pHist->Save(fs, "Hist");
+ cvEndWriteStruct(fs);
+ }
+ cvEndWriteStruct(fs);
+ m_HistMat.Save(fs, "Hist");
+ };
+
+ virtual void LoadState(CvFileStorage* fs, CvFileNode* node)
+ {
+ CvFileNode* pBLN = cvGetFileNodeByName(fs,node,"BlobList");
+
+ if(pBLN && CV_NODE_IS_SEQ(pBLN->tag))
+ {
+ int b, bN = pBLN->data.seq->total;
+ for(b=0; b<bN; ++b)
+ {
+ DefTrackFG* pF = NULL;
+ CvBlob Blob;
+ CvFileNode* pBN = (CvFileNode*)cvGetSeqElem(pBLN->data.seq,b);
+
+ assert(pBN);
+ cvReadStructByName(fs, pBN, "Blob", &Blob, "ffffi");
+ AddBlob(&Blob);
+ pF = (DefTrackFG*)m_TrackFGList.GetBlobByID(Blob.ID);
+ if(pF==NULL) continue;
+ assert(pF);
+ pF->state = (float)cvReadIntByName(fs,pBN,"State",cvRound(pF->state));
+ assert(pF->pHist);
+ pF->pHist->Load(fs,pBN,"Hist");
+ }
+ }
+
+ m_HistMat.Load(fs, node, "Hist");
+ }; /* LoadState */
+
+
+ virtual void Release(){ delete this; };
};
typedef struct DefTrackSVM
{
- CvBlob blob;
- // CvBlobTrackFVGen* pFVGen;
- int LastFrame;
- float state;
- CvBlob BlobLast;
- CvSeq* pFVSeq;
- CvMemStorage* pMem;
+ CvBlob blob;
+ // CvBlobTrackFVGen* pFVGen;
+ int LastFrame;
+ float state;
+ CvBlob BlobLast;
+ CvSeq* pFVSeq;
+ CvMemStorage* pMem;
} DefTrackSVM;
class CvBlobTrackAnalysisSVM : public CvBlobTrackAnalysis
{
- /*---------------- Internal functions: --------------------*/
+ /*---------------- Internal functions: --------------------*/
private:
- CvMemStorage* m_pMem;
- int m_TrackNum;
- int m_Frame;
- char m_DataFileName[1024];
- int m_Dim;
- float* m_pFV;
- //CvStatModel* m_pStatModel;
- void* m_pStatModel;
- CvBlobSeq m_Tracks;
- CvMat* m_pTrainData;
- int m_LastTrainDataSize;
- // CvBlobTrackFVGen* (*m_CreateFVGen)();
- CvBlobTrackFVGen* m_pFVGen;
- float m_NU;
- float m_RBFWidth;
- IplImage* m_pStatImg; /* for debug purpose */
- CvSize m_ImgSize;
- void RetrainStatModel()
- {
- ///////// !!!!! TODO !!!!! Repair /////////////
+ CvMemStorage* m_pMem;
+ int m_TrackNum;
+ int m_Frame;
+ char m_DataFileName[1024];
+ int m_Dim;
+ float* m_pFV;
+ //CvStatModel* m_pStatModel;
+ void* m_pStatModel;
+ CvBlobSeq m_Tracks;
+ CvMat* m_pTrainData;
+ int m_LastTrainDataSize;
+ // CvBlobTrackFVGen* (*m_CreateFVGen)();
+ CvBlobTrackFVGen* m_pFVGen;
+ float m_NU;
+ float m_RBFWidth;
+ IplImage* m_pStatImg; /* for debug purpose */
+ CvSize m_ImgSize;
+ void RetrainStatModel()
+ {
+ ///////// !!!!! TODO !!!!! Repair /////////////
#if 0
- float nu = 0;
- CvSVMModelParams SVMParams = {0};
- CvStatModel* pM = NULL;
-
-
- memset(&SVMParams,0,sizeof(SVMParams));
- SVMParams.svm_type = CV_SVM_ONE_CLASS;
- SVMParams.kernel_type = CV_SVM_RBF;
- SVMParams.gamma = 2.0/(m_RBFWidth*m_RBFWidth);
- SVMParams.nu = m_NU;
- SVMParams.degree = 3;
- SVMParams.criteria = cvTermCriteria(CV_TERMCRIT_EPS, 100, 1e-3 );
- SVMParams.C = 1;
- SVMParams.p = 0.1;
-
-
- if(m_pTrainData == NULL) return;
- {
- int64 TickCount = cvGetTickCount();
- printf("Frame: %d\n Retrain SVM\nData Size = %d\n",m_Frame, m_pTrainData->rows);
- pM = cvTrainSVM( m_pTrainData,CV_ROW_SAMPLE, NULL, (CvStatModelParams*)&SVMParams, NULL, NULL);
- TickCount = cvGetTickCount() - TickCount ;
- printf("SV Count = %d\n",((CvSVMModel*)pM)->sv_total);
- printf("Processing Time = %.1f(ms)\n",TickCount/(1000*cvGetTickFrequency()));
-
- }
- if(pM==NULL) return;
- if(m_pStatModel) cvReleaseStatModel(&m_pStatModel);
- m_pStatModel = pM;
-
- if(m_pTrainData && m_Wnd)
- {
- float MaxVal = 0;
- IplImage* pW = cvCreateImage(m_ImgSize,IPL_DEPTH_32F,1);
- IplImage* pI = cvCreateImage(m_ImgSize,IPL_DEPTH_8U,1);
- float* pFVVar = m_pFVGen->GetFVVar();
- int i;
- cvZero(pW);
-
- for(i=0; i<m_pTrainData->rows; ++i)
- { /* Draw all elements: */
- float* pFV = (float*)(m_pTrainData->data.ptr + m_pTrainData->step*i);
- int x = cvRound(pFV[0]*pFVVar[0]);
- int y = cvRound(pFV[1]*pFVVar[1]);
- float r;
-
- if(x<0)x=0;
- if(x>=pW->width)x=pW->width-1;
- if(y<0)y=0;
- if(y>=pW->height)y=pW->height-1;
-
- r = ((float*)(pW->imageData + y*pW->widthStep))[x];
- r++;
- ((float*)(pW->imageData + y*pW->widthStep))[x] = r;
-
- if(r>MaxVal)MaxVal=r;
- } /* Next point. */
-
- if(MaxVal>0)cvConvertScale(pW,pI,255/MaxVal,0);
- cvNamedWindow("SVMData",0);
- cvShowImage("SVMData",pI);
- cvSaveImage("SVMData.bmp",pI);
- cvReleaseImage(&pW);
- cvReleaseImage(&pI);
- } /* Prepare for debug. */
-
- if(m_pStatModel && m_Wnd && m_Dim == 2)
- {
- float* pFVVar = m_pFVGen->GetFVVar();
- int x,y;
- if(m_pStatImg==NULL)
- {
- m_pStatImg = cvCreateImage(m_ImgSize,IPL_DEPTH_8U,1);
- }
- cvZero(m_pStatImg);
-
- for(y=0; y<m_pStatImg->height; y+=1) for(x=0; x<m_pStatImg->width; x+=1)
- { /* Draw all elements: */
- float res;
- uchar* pData = (uchar*)m_pStatImg->imageData + x + y*m_pStatImg->widthStep;
- CvMat FVmat;
- float xy[2] = {x/pFVVar[0],y/pFVVar[1]};
- cvInitMatHeader( &FVmat, 1, 2, CV_32F, xy );
- res = cvStatModelPredict( m_pStatModel, &FVmat, NULL );
- pData[0]=((res>0.5)?255:0);
- } /* Next point. */
-
- cvNamedWindow("SVMMask",0);
- cvShowImage("SVMMask",m_pStatImg);
- cvSaveImage("SVMMask.bmp",m_pStatImg);
- } /* Prepare for debug. */
+ float nu = 0;
+ CvSVMModelParams SVMParams = {0};
+ CvStatModel* pM = NULL;
+
+
+ memset(&SVMParams,0,sizeof(SVMParams));
+ SVMParams.svm_type = CV_SVM_ONE_CLASS;
+ SVMParams.kernel_type = CV_SVM_RBF;
+ SVMParams.gamma = 2.0/(m_RBFWidth*m_RBFWidth);
+ SVMParams.nu = m_NU;
+ SVMParams.degree = 3;
+ SVMParams.criteria = cvTermCriteria(CV_TERMCRIT_EPS, 100, 1e-3 );
+ SVMParams.C = 1;
+ SVMParams.p = 0.1;
+
+
+ if(m_pTrainData == NULL) return;
+ {
+ int64 TickCount = cvGetTickCount();
+ printf("Frame: %d\n Retrain SVM\nData Size = %d\n",m_Frame, m_pTrainData->rows);
+ pM = cvTrainSVM( m_pTrainData,CV_ROW_SAMPLE, NULL, (CvStatModelParams*)&SVMParams, NULL, NULL);
+ TickCount = cvGetTickCount() - TickCount ;
+ printf("SV Count = %d\n",((CvSVMModel*)pM)->sv_total);
+ printf("Processing Time = %.1f(ms)\n",TickCount/(1000*cvGetTickFrequency()));
+
+ }
+ if(pM==NULL) return;
+ if(m_pStatModel) cvReleaseStatModel(&m_pStatModel);
+ m_pStatModel = pM;
+
+ if(m_pTrainData && m_Wnd)
+ {
+ float MaxVal = 0;
+ IplImage* pW = cvCreateImage(m_ImgSize,IPL_DEPTH_32F,1);
+ IplImage* pI = cvCreateImage(m_ImgSize,IPL_DEPTH_8U,1);
+ float* pFVVar = m_pFVGen->GetFVVar();
+ int i;
+ cvZero(pW);
+
+ for(i=0; i<m_pTrainData->rows; ++i)
+ { /* Draw all elements: */
+ float* pFV = (float*)(m_pTrainData->data.ptr + m_pTrainData->step*i);
+ int x = cvRound(pFV[0]*pFVVar[0]);
+ int y = cvRound(pFV[1]*pFVVar[1]);
+ float r;
+
+ if(x<0)x=0;
+ if(x>=pW->width)x=pW->width-1;
+ if(y<0)y=0;
+ if(y>=pW->height)y=pW->height-1;
+
+ r = ((float*)(pW->imageData + y*pW->widthStep))[x];
+ r++;
+ ((float*)(pW->imageData + y*pW->widthStep))[x] = r;
+
+ if(r>MaxVal)MaxVal=r;
+ } /* Next point. */
+
+ if(MaxVal>0)cvConvertScale(pW,pI,255/MaxVal,0);
+ cvNamedWindow("SVMData",0);
+ cvShowImage("SVMData",pI);
+ cvSaveImage("SVMData.bmp",pI);
+ cvReleaseImage(&pW);
+ cvReleaseImage(&pI);
+ } /* Prepare for debug. */
+
+ if(m_pStatModel && m_Wnd && m_Dim == 2)
+ {
+ float* pFVVar = m_pFVGen->GetFVVar();
+ int x,y;
+ if(m_pStatImg==NULL)
+ {
+ m_pStatImg = cvCreateImage(m_ImgSize,IPL_DEPTH_8U,1);
+ }
+ cvZero(m_pStatImg);
+
+ for(y=0; y<m_pStatImg->height; y+=1) for(x=0; x<m_pStatImg->width; x+=1)
+ { /* Draw all elements: */
+ float res;
+ uchar* pData = (uchar*)m_pStatImg->imageData + x + y*m_pStatImg->widthStep;
+ CvMat FVmat;
+ float xy[2] = {x/pFVVar[0],y/pFVVar[1]};
+ cvInitMatHeader( &FVmat, 1, 2, CV_32F, xy );
+ res = cvStatModelPredict( m_pStatModel, &FVmat, NULL );
+ pData[0]=((res>0.5)?255:0);
+ } /* Next point. */
+
+ cvNamedWindow("SVMMask",0);
+ cvShowImage("SVMMask",m_pStatImg);
+ cvSaveImage("SVMMask.bmp",m_pStatImg);
+ } /* Prepare for debug. */
#endif
- };
- void SaveStatModel()
- {
- if(m_DataFileName[0])
- {
- if(m_pTrainData)cvSave(m_DataFileName, m_pTrainData);
- }
- };
- void LoadStatModel()
- {
- if(m_DataFileName[0])
- {
- CvMat* pTrainData = (CvMat*)cvLoad(m_DataFileName);
- if(CV_IS_MAT(pTrainData) && pTrainData->width == m_Dim)
- {
- if(m_pTrainData) cvReleaseMat(&m_pTrainData);
- m_pTrainData = pTrainData;
- RetrainStatModel();
- }
- }
- }
+ };
+ void SaveStatModel()
+ {
+ if(m_DataFileName[0])
+ {
+ if(m_pTrainData)cvSave(m_DataFileName, m_pTrainData);
+ }
+ };
+ void LoadStatModel()
+ {
+ if(m_DataFileName[0])
+ {
+ CvMat* pTrainData = (CvMat*)cvLoad(m_DataFileName);
+ if(CV_IS_MAT(pTrainData) && pTrainData->width == m_Dim)
+ {
+ if(m_pTrainData) cvReleaseMat(&m_pTrainData);
+ m_pTrainData = pTrainData;
+ RetrainStatModel();
+ }
+ }
+ }
public:
- CvBlobTrackAnalysisSVM(CvBlobTrackFVGen* (*createFVGen)()):m_Tracks(sizeof(DefTrackSVM))
- {
- m_pFVGen = createFVGen();
- m_Dim = m_pFVGen->GetFVSize();
- m_pFV = (float*)cvAlloc(sizeof(float)*m_Dim);
- m_Frame = 0;
- m_TrackNum = 0;
- m_pTrainData = NULL;
- m_pStatModel = NULL;
- m_DataFileName[0] = 0;
- m_pStatImg = NULL;
- m_LastTrainDataSize = 0;
-
- m_NU = 0.2f;
- AddParam("Nu",&m_NU);
- CommentParam("Nu","Parameters that tunes SVM border elastic");
-
- m_RBFWidth = 1;
- AddParam("RBFWidth",&m_RBFWidth);
- CommentParam("RBFWidth","Parameters that tunes RBF kernel function width.");
-
- SetModuleName("SVM");
-
- } /* Constructor. */
-
- ~CvBlobTrackAnalysisSVM()
- {
- int i;
- SaveStatModel();
- for(i=m_Tracks.GetBlobNum();i>0;--i)
- {
- DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlob(i-1);
- if(pF->pMem) cvReleaseMemStorage(&pF->pMem);
- //pF->pFVGen->Release();
- }
- if(m_pStatImg)cvReleaseImage(&m_pStatImg);
- cvFree(&m_pFV);
- } /* Destructor. */
-
- /*----------------- Interface: --------------------*/
- virtual void AddBlob(CvBlob* pBlob)
- {
- DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(CV_BLOB_ID(pBlob));
-
- m_pFVGen->AddBlob(pBlob);
-
- if(pF == NULL)
- { /* Create new record: */
- DefTrackSVM F;
- F.state = 0;
- F.blob = pBlob[0];
- F.LastFrame = m_Frame;
- //F.pFVGen = m_CreateFVGen();
- F.pMem = cvCreateMemStorage();
- F.pFVSeq = cvCreateSeq(0,sizeof(CvSeq),sizeof(float)*m_Dim,F.pMem);
-
- F.BlobLast.x = -1;
- F.BlobLast.y = -1;
- F.BlobLast.w = -1;
- F.BlobLast.h = -1;
- m_Tracks.AddBlob((CvBlob*)&F);
- pF = (DefTrackSVM*)m_Tracks.GetBlobByID(CV_BLOB_ID(pBlob));
- }
-
- assert(pF);
- pF->blob = pBlob[0];
- pF->LastFrame = m_Frame;
- };
-
- virtual void Process(IplImage* pImg, IplImage* pFG)
- {
- int i;
- float* pFVVar = m_pFVGen->GetFVVar();
-
- m_pFVGen->Process(pImg, pFG);
- m_ImgSize = cvSize(pImg->width,pImg->height);
-
- for(i=m_pFVGen->GetFVNum(); i>0; --i)
- {
- int BlobID = 0;
- float* pFV = m_pFVGen->GetFV(i,&BlobID);
- DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(BlobID);
-
- if(pF && pFV)
- { /* Process: */
- float dx,dy;
- CvMat FVmat;
-
- pF->state = 0;
-
- if(m_pStatModel)
- {
- int j;
- for(j=0; j<m_Dim; ++j)
- {
- m_pFV[j] = pFV[j]/pFVVar[j];
- }
-
- cvInitMatHeader( &FVmat, 1, m_Dim, CV_32F, m_pFV );
- //pF->state = cvStatModelPredict( m_pStatModel, &FVmat, NULL )<0.5;
- pF->state = 1.f;
- }
-
- dx = (pF->blob.x - pF->BlobLast.x);
- dy = (pF->blob.y - pF->BlobLast.y);
-
- if(pF->BlobLast.x<0 || (dx*dx+dy*dy) >= 2*2)
- { /* Add feature vector to train data base: */
- pF->BlobLast = pF->blob;
- cvSeqPush(pF->pFVSeq,pFV);
- }
- } /* Process one blob. */
- } /* Next FV. */
-
- for(i=m_Tracks.GetBlobNum(); i>0; --i)
- { /* Check each blob record: */
- DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlob(i-1);
-
- if(pF->LastFrame+3 < m_Frame )
- { /* Retrain stat model and delete blob filter: */
- int mult = 1+m_Dim;
- int old_height = m_pTrainData?m_pTrainData->height:0;
- int height = old_height + pF->pFVSeq->total*mult;
- CvMat* pTrainData = cvCreateMat(height, m_Dim, CV_32F);
- int j;
- if(m_pTrainData && pTrainData)
- { /* Create new train data matrix: */
- int h = pTrainData->height;
- pTrainData->height = MIN(pTrainData->height, m_pTrainData->height);
- cvCopy(m_pTrainData,pTrainData);
- pTrainData->height = h;
- }
-
- for(j=0; j<pF->pFVSeq->total; ++j)
- { /* Copy new data to train data: */
- float* pFVVar = m_pFVGen->GetFVVar();
- float* pFV = (float*)cvGetSeqElem(pF->pFVSeq,j);
- int k;
-
- for(k=0; k<mult; ++k)
- {
- int t;
- float* pTD = (float*)CV_MAT_ELEM_PTR( pTrainData[0], old_height+j*mult+k, 0);
- memcpy(pTD,pFV,sizeof(float)*m_Dim);
-
- if(pFVVar)for(t=0;t<m_Dim;++t)
- { /* Scale FV: */
- pTD[t] /= pFVVar[t];
- }
-
- if(k>0)
- { /* Variate: */
- for(t=0; t<m_Dim; ++t)
- {
- pTD[t] += m_RBFWidth*0.5f*(1-2.0f*rand()/(float)RAND_MAX);
- }
- }
- }
- } /* Next new datum. */
-
- if(m_pTrainData) cvReleaseMat(&m_pTrainData);
- m_pTrainData = pTrainData;
-
- /* delete track record */
- cvReleaseMemStorage(&pF->pMem);
- m_TrackNum++;
- m_Tracks.DelBlob(i-1);
-
- } /* End delete. */
- } /* Next track. */
-
- /* Retrain data each 1 minute if new data exist: */
- if(m_Frame%(25*60) == 0 && m_pTrainData && m_pTrainData->rows > m_LastTrainDataSize)
- {
- RetrainStatModel();
- }
-
- m_Frame++;
-
- if(m_Wnd && m_Dim==2)
- { /* Debug output: */
- int x,y;
- IplImage* pI = cvCloneImage(pImg);
-
- if(m_pStatModel && m_pStatImg)
-
- for(y=0; y<pI->height; y+=2)
- {
- uchar* pStatData = (uchar*)m_pStatImg->imageData + y*m_pStatImg->widthStep;
- uchar* pData = (uchar*)pI->imageData + y*pI->widthStep;
-
- for(x=0;x<pI->width;x+=2)
- { /* Draw all elements: */
- int d = pStatData[x];
- d = (d<<8) | (d^0xff);
- *(ushort*)(pData + x*3) = (ushort)d;
- }
- } /* Next line. */
-
- //cvNamedWindow("SVMMap",0);
- //cvShowImage("SVMMap", pI);
- cvReleaseImage(&pI);
- } /* Debug output. */
- };
- float GetState(int BlobID)
- {
- DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(BlobID);
- return pF?pF->state:0.0f;
- };
-
- /* Return 0 if trajectory is normal;
+ CvBlobTrackAnalysisSVM(CvBlobTrackFVGen* (*createFVGen)()):m_Tracks(sizeof(DefTrackSVM))
+ {
+ m_pFVGen = createFVGen();
+ m_Dim = m_pFVGen->GetFVSize();
+ m_pFV = (float*)cvAlloc(sizeof(float)*m_Dim);
+ m_Frame = 0;
+ m_TrackNum = 0;
+ m_pTrainData = NULL;
+ m_pStatModel = NULL;
+ m_DataFileName[0] = 0;
+ m_pStatImg = NULL;
+ m_LastTrainDataSize = 0;
+
+ m_NU = 0.2f;
+ AddParam("Nu",&m_NU);
+ CommentParam("Nu","Parameters that tunes SVM border elastic");
+
+ m_RBFWidth = 1;
+ AddParam("RBFWidth",&m_RBFWidth);
+ CommentParam("RBFWidth","Parameters that tunes RBF kernel function width.");
+
+ SetModuleName("SVM");
+
+ } /* Constructor. */
+
+ ~CvBlobTrackAnalysisSVM()
+ {
+ int i;
+ SaveStatModel();
+ for(i=m_Tracks.GetBlobNum();i>0;--i)
+ {
+ DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlob(i-1);
+ if(pF->pMem) cvReleaseMemStorage(&pF->pMem);
+ //pF->pFVGen->Release();
+ }
+ if(m_pStatImg)cvReleaseImage(&m_pStatImg);
+ cvFree(&m_pFV);
+ } /* Destructor. */
+
+ /*----------------- Interface: --------------------*/
+ virtual void AddBlob(CvBlob* pBlob)
+ {
+ DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(CV_BLOB_ID(pBlob));
+
+ m_pFVGen->AddBlob(pBlob);
+
+ if(pF == NULL)
+ { /* Create new record: */
+ DefTrackSVM F;
+ F.state = 0;
+ F.blob = pBlob[0];
+ F.LastFrame = m_Frame;
+ //F.pFVGen = m_CreateFVGen();
+ F.pMem = cvCreateMemStorage();
+ F.pFVSeq = cvCreateSeq(0,sizeof(CvSeq),sizeof(float)*m_Dim,F.pMem);
+
+ F.BlobLast.x = -1;
+ F.BlobLast.y = -1;
+ F.BlobLast.w = -1;
+ F.BlobLast.h = -1;
+ m_Tracks.AddBlob((CvBlob*)&F);
+ pF = (DefTrackSVM*)m_Tracks.GetBlobByID(CV_BLOB_ID(pBlob));
+ }
+
+ assert(pF);
+ pF->blob = pBlob[0];
+ pF->LastFrame = m_Frame;
+ };
+
+ virtual void Process(IplImage* pImg, IplImage* pFG)
+ {
+ int i;
+ float* pFVVar = m_pFVGen->GetFVVar();
+
+ m_pFVGen->Process(pImg, pFG);
+ m_ImgSize = cvSize(pImg->width,pImg->height);
+
+ for(i=m_pFVGen->GetFVNum(); i>0; --i)
+ {
+ int BlobID = 0;
+ float* pFV = m_pFVGen->GetFV(i,&BlobID);
+ DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(BlobID);
+
+ if(pF && pFV)
+ { /* Process: */
+ float dx,dy;
+ CvMat FVmat;
+
+ pF->state = 0;
+
+ if(m_pStatModel)
+ {
+ int j;
+ for(j=0; j<m_Dim; ++j)
+ {
+ m_pFV[j] = pFV[j]/pFVVar[j];
+ }
+
+ cvInitMatHeader( &FVmat, 1, m_Dim, CV_32F, m_pFV );
+ //pF->state = cvStatModelPredict( m_pStatModel, &FVmat, NULL )<0.5;
+ pF->state = 1.f;
+ }
+
+ dx = (pF->blob.x - pF->BlobLast.x);
+ dy = (pF->blob.y - pF->BlobLast.y);
+
+ if(pF->BlobLast.x<0 || (dx*dx+dy*dy) >= 2*2)
+ { /* Add feature vector to train data base: */
+ pF->BlobLast = pF->blob;
+ cvSeqPush(pF->pFVSeq,pFV);
+ }
+ } /* Process one blob. */
+ } /* Next FV. */
+
+ for(i=m_Tracks.GetBlobNum(); i>0; --i)
+ { /* Check each blob record: */
+ DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlob(i-1);
+
+ if(pF->LastFrame+3 < m_Frame )
+ { /* Retrain stat model and delete blob filter: */
+ int mult = 1+m_Dim;
+ int old_height = m_pTrainData?m_pTrainData->height:0;
+ int height = old_height + pF->pFVSeq->total*mult;
+ CvMat* pTrainData = cvCreateMat(height, m_Dim, CV_32F);
+ int j;
+ if(m_pTrainData && pTrainData)
+ { /* Create new train data matrix: */
+ int h = pTrainData->height;
+ pTrainData->height = MIN(pTrainData->height, m_pTrainData->height);
+ cvCopy(m_pTrainData,pTrainData);
+ pTrainData->height = h;
+ }
+
+ for(j=0; j<pF->pFVSeq->total; ++j)
+ { /* Copy new data to train data: */
+ float* pFVvar = m_pFVGen->GetFVVar();
+ float* pFV = (float*)cvGetSeqElem(pF->pFVSeq,j);
+ int k;
+
+ for(k=0; k<mult; ++k)
+ {
+ int t;
+ float* pTD = (float*)CV_MAT_ELEM_PTR( pTrainData[0], old_height+j*mult+k, 0);
+ memcpy(pTD,pFV,sizeof(float)*m_Dim);
+
+ if(pFVvar)for(t=0;t<m_Dim;++t)
+ { /* Scale FV: */
+ pTD[t] /= pFVvar[t];
+ }
+
+ if(k>0)
+ { /* Variate: */
+ for(t=0; t<m_Dim; ++t)
+ {
+ pTD[t] += m_RBFWidth*0.5f*(1-2.0f*rand()/(float)RAND_MAX);
+ }
+ }
+ }
+ } /* Next new datum. */
+
+ if(m_pTrainData) cvReleaseMat(&m_pTrainData);
+ m_pTrainData = pTrainData;
+
+ /* delete track record */
+ cvReleaseMemStorage(&pF->pMem);
+ m_TrackNum++;
+ m_Tracks.DelBlob(i-1);
+
+ } /* End delete. */
+ } /* Next track. */
+
+ /* Retrain data each 1 minute if new data exist: */
+ if(m_Frame%(25*60) == 0 && m_pTrainData && m_pTrainData->rows > m_LastTrainDataSize)
+ {
+ RetrainStatModel();
+ }
+
+ m_Frame++;
+
+ if(m_Wnd && m_Dim==2)
+ { /* Debug output: */
+ int x,y;
+ IplImage* pI = cvCloneImage(pImg);
+
+ if(m_pStatModel && m_pStatImg)
+
+ for(y=0; y<pI->height; y+=2)
+ {
+ uchar* pStatData = (uchar*)m_pStatImg->imageData + y*m_pStatImg->widthStep;
+ uchar* pData = (uchar*)pI->imageData + y*pI->widthStep;
+
+ for(x=0;x<pI->width;x+=2)
+ { /* Draw all elements: */
+ int d = pStatData[x];
+ d = (d<<8) | (d^0xff);
+ *(ushort*)(pData + x*3) = (ushort)d;
+ }
+ } /* Next line. */
+
+ //cvNamedWindow("SVMMap",0);
+ //cvShowImage("SVMMap", pI);
+ cvReleaseImage(&pI);
+ } /* Debug output. */
+ };
+ float GetState(int BlobID)
+ {
+ DefTrackSVM* pF = (DefTrackSVM*)m_Tracks.GetBlobByID(BlobID);
+ return pF?pF->state:0.0f;
+ };
+
+ /* Return 0 if trajectory is normal;
return >0 if trajectory abnormal. */
- virtual const char* GetStateDesc(int BlobID)
- {
- if(GetState(BlobID)>0.5) return "abnormal";
- return NULL;
- }
-
- virtual void SetFileName(char* DataBaseName)
- {
- if(m_pTrainData)SaveStatModel();
- m_DataFileName[0] = m_DataFileName[1000] = 0;
- if(DataBaseName)
- {
- strncpy(m_DataFileName,DataBaseName,1000);
- strcat(m_DataFileName, ".yml");
- }
- LoadStatModel();
- };
-
-
- virtual void Release(){ delete this; };
+ virtual const char* GetStateDesc(int BlobID)
+ {
+ if(GetState(BlobID)>0.5) return "abnormal";
+ return NULL;
+ }
+
+ virtual void SetFileName(char* DataBaseName)
+ {
+ if(m_pTrainData)SaveStatModel();
+ m_DataFileName[0] = m_DataFileName[1000] = 0;
+ if(DataBaseName)
+ {
+ strncpy(m_DataFileName,DataBaseName,1000);
+ strcat(m_DataFileName, ".yml");
+ }
+ LoadStatModel();
+ };
+
+
+ virtual void Release(){ delete this; };
}; /* CvBlobTrackAnalysisSVM. */
void CvBlobTrackerAuto1::Process(IplImage* pImg, IplImage* pMask)
{
int CurBlobNum = 0;
- int i;
IplImage* pFG = pMask;
/* Bump frame counter: */
TIME_BEGIN()
if(m_pBT)
{
- int i;
m_pBT->Process(pImg, pFG);
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Update data of tracked blob list: */
CvBlob* pB = m_BlobList.GetBlob(i-1);
int BlobID = CV_BLOB_ID(pB);
- int i = m_pBT->GetBlobIndexByID(BlobID);
- m_pBT->ProcessBlob(i, pB, pImg, pFG);
+ int idx = m_pBT->GetBlobIndexByID(BlobID);
+ m_pBT->ProcessBlob(idx, pB, pImg, pFG);
pB->ID = BlobID;
}
CurBlobNum = m_pBT->GetBlobNum();
/* This part should be removed: */
if(m_BTReal && m_pBT)
{ /* Update blob list (detect new blob for real blob tracker): */
- int i;
-
- for(i=m_pBT->GetBlobNum(); i>0; --i)
+ for(int i=m_pBT->GetBlobNum(); i>0; --i)
{ /* Update data of tracked blob list: */
CvBlob* pB = m_pBT->GetBlob(i-1);
if(pB && m_BlobList.GetBlobByID(CV_BLOB_ID(pB)) == NULL )
} /* Next blob. */
/* Delete blobs: */
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Update tracked-blob list: */
CvBlob* pB = m_BlobList.GetBlob(i-1);
if(pB && m_pBT->GetBlobByID(CV_BLOB_ID(pB)) == NULL )
TIME_BEGIN()
if(m_pBTPostProc)
{ /* Post-processing module: */
- int i;
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Update tracked-blob list: */
CvBlob* pB = m_BlobList.GetBlob(i-1);
m_pBTPostProc->AddBlob(pB);
}
m_pBTPostProc->Process();
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Update tracked-blob list: */
CvBlob* pB = m_BlobList.GetBlob(i-1);
int BlobID = CV_BLOB_ID(pB);
if(m_pBD->DetectNewBlob(pImg, pFG, &NewBlobList, &m_BlobList))
{ /* Add new blob to tracker and blob list: */
int i;
- IplImage* pMask = pFG;
+ IplImage* pmask = pFG;
/*if(0)if(NewBlobList.GetBlobNum()>0 && pFG )
{// erode FG mask (only for FG_0 and MS1||MS2)
- pMask = cvCloneImage(pFG);
- cvErode(pFG,pMask,NULL,2);
+ pmask = cvCloneImage(pFG);
+ cvErode(pFG,pmask,NULL,2);
}*/
for(i=0; i<NewBlobList.GetBlobNum(); ++i)
if(pBN && pBN->w >= CV_BLOB_MINW && pBN->h >= CV_BLOB_MINH)
{
- CvBlob* pB = m_pBT->AddBlob(pBN, pImg, pMask );
+ CvBlob* pB = m_pBT->AddBlob(pBN, pImg, pmask );
if(pB)
{
NewB.blob = pB[0];
}
} /* Add next blob from list of detected blob. */
- if(pMask != pFG) cvReleaseImage(&pMask);
+ if(pmask != pFG) cvReleaseImage(&pmask);
} /* Create and add new blobs and trackers. */
TIME_BEGIN()
if(m_pBTGen)
{ /* Run track generator: */
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Update data of tracked blob list: */
CvBlob* pB = m_BlobList.GetBlob(i-1);
m_pBTGen->AddBlob(pB);
{
CvSeq* cnts;
CvSeq* cnt;
- int i;
//CvMat* pMC = NULL;
if(m_BlobList.GetBlobNum() <= 0 ) return;
cvReleaseImage(&pBin);
}
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Predict new blob position. */
CvBlob* pB = NULL;
DefBlobTrackerCR* pBT = (DefBlobTrackerCR*)m_BlobList.GetBlob(i-1);
if(m_BlobList.GetBlobNum()>0 && m_BlobListNew.GetBlobNum()>0)
{ /* Resolve new blob to old: */
- int i,j;
int NOld = m_BlobList.GetBlobNum();
int NNew = m_BlobListNew.GetBlobNum();
- for(i=0; i<NOld; i++)
+ for(int i=0; i<NOld; i++)
{ /* Set 0 collision and clear all hyp: */
DefBlobTrackerCR* pF = (DefBlobTrackerCR*)m_BlobList.GetBlob(i);
pF->Collision = 0;
} /* Set 0 collision. */
/* Create correspondence records: */
- for(j=0; j<NNew; ++j)
+ for(int j=0; j<NNew; ++j)
{
CvBlob* pB1 = m_BlobListNew.GetBlob(j);
DefBlobTrackerCR* pFLast = NULL;
- for(i=0; i<NOld; i++)
+ for(int i=0; i<NOld; i++)
{ /* Check intersection: */
int Intersection = 0;
DefBlobTrackerCR* pF = (DefBlobTrackerCR*)m_BlobList.GetBlob(i);
} /* Check next new blob. */
} /* Resolve new blob to old. */
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Track each blob. */
CvBlob* pB = m_BlobList.GetBlob(i-1);
DefBlobTrackerCR* pBT = (DefBlobTrackerCR*)pB;
int BlobID = CV_BLOB_ID(pB);
//CvBlob* pBBest = NULL;
//double DistBest = -1;
- int j;
if(pBT->pResolver)
{
CvBlob* pBBest = NULL;
double DistBest = -1;
double CMax = 0;
- for(j=pBT->pBlobHyp->GetBlobNum();j>0;--j)
+ for(int j=pBT->pBlobHyp->GetBlobNum();j>0;--j)
{ /* Find best CC: */
CvBlob* pBNew = pBT->pBlobHyp->GetBlob(j-1);
if(pBT->pResolver)
if(m_Wnd)
{
IplImage* pI = cvCloneImage(pImg);
- int i;
- for(i=m_BlobListNew.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobListNew.GetBlobNum(); i>0; --i)
{ /* Draw each new CC: */
CvBlob* pB = m_BlobListNew.GetBlob(i-1);
CvPoint p = cvPointFrom32f(CV_BLOB_CENTER(pB));
CV_RGB(255,255,0), 1 );
}
- for(i=m_BlobList.GetBlobNum(); i>0; --i)
+ for(int i=m_BlobList.GetBlobNum(); i>0; --i)
{ /* Draw each new CC: */
DefBlobTrackerCR* pF = (DefBlobTrackerCR*)m_BlobList.GetBlob(i-1);
CvBlob* pB = &(pF->BlobPredict);
{ /* Mean shift in scale space: */
float news = 0;
- float sum = 0;
+ float sum1 = 0;
float scale;
Center = cvPoint(cvRound(m_Blob.x),cvRound(m_Blob.y));
{
double W = cvDotProduct(m_Weights, m_KernelMeanShiftG[si]);;
int s = si-SCALE_RANGE;
- sum += (float)fabs(W);
+ sum1 += (float)fabs(W);
news += (float)(s*W);
}
- if(sum>0)
+ if(sum1>0)
{
- news /= sum;
+ news /= sum1;
}
scale = (float)pow((double)SCALE_BASE,(double)news);
{
float WSum = 0;
int i;
- int index = m_Frame % TIME_WND;
+ int idx = m_Frame % TIME_WND;
int size = MIN((m_Frame+1), TIME_WND);
- m_pBlobs[index] = pBlob[0];
+ m_pBlobs[idx] = pBlob[0];
m_Blob.x = m_Blob.y = m_Blob.w = m_Blob.h = 0;
for(i=0; i<size; ++i)
#undef quad
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4701 )
-#endif
-
CvCalibFilter::CvCalibFilter()
{
/* etalon data */
bool CvCalibFilter::SetEtalon( CvCalibEtalonType type, double* params,
- int pointCount, CvPoint2D32f* points )
+ int pointCount, CvPoint2D32f* _points )
{
int i, arrSize;
case CV_CALIB_ETALON_USER:
etalonParamCount = 0;
- if( !points || pointCount < 4 )
+ if( !_points || pointCount < 4 )
{
assert(0);
return false;
{
memcpy( etalonParams, params, arrSize );
}
- if (points != NULL)
+ if (_points != NULL)
{
- memcpy( etalonPoints, points, arrSize );
+ memcpy( etalonPoints, _points, arrSize );
}
break;
CvCalibEtalonType
CvCalibFilter::GetEtalon( int* paramCount, const double** params,
- int* pointCount, const CvPoint2D32f** points ) const
+ int* pointCount, const CvPoint2D32f** _points ) const
{
if( paramCount )
*paramCount = etalonParamCount;
if( pointCount )
*pointCount = etalonPointCount;
- if( points )
- *points = etalonPoints;
+ if( _points )
+ *_points = etalonPoints;
return etalonType;
}
}
void RandomizedTree::train(std::vector<BaseKeypoint> const& base_set,
- RNG &rng, int depth, int views, size_t reduced_num_dim,
+ RNG &rng, int _depth, int views, size_t reduced_num_dim,
int num_quant_bits)
{
PatchGenerator make_patch;
- train(base_set, rng, make_patch, depth, views, reduced_num_dim, num_quant_bits);
+ train(base_set, rng, make_patch, _depth, views, reduced_num_dim, num_quant_bits);
}
void RandomizedTree::train(std::vector<BaseKeypoint> const& base_set,
RNG &rng, PatchGenerator &make_patch,
- int depth, int views, size_t reduced_num_dim,
+ int _depth, int views, size_t reduced_num_dim,
int num_quant_bits)
{
- init((int)base_set.size(), depth, rng);
+ init((int)base_set.size(), _depth, rng);
Mat patch;
classes_ = -1;
}
-void RandomizedTree::init(int num_classes, int depth, RNG &rng)
+void RandomizedTree::init(int num_classes, int _depth, RNG &rng)
{
- depth_ = depth;
- num_leaves_ = 1 << depth; // 2**d
+ depth_ = _depth;
+ num_leaves_ = 1 << _depth; // 2**d
int num_nodes = num_leaves_ - 1; // 2**d - 1
// Initialize probabilities and counts to 0
for (int i=0; i<num_leaves_; i++) {
float *post = posteriors_[i];
char buf[20];
- for (int i=0; i<classes_; i++) {
+ for (int j=0; j<classes_; j++) {
sprintf(buf, "%.10e", *post++);
- file << buf << ((i<classes_-1) ? " " : "");
+ file << buf << ((j<classes_-1) ? " " : "");
}
file << std::endl;
}
std::ofstream file(url.c_str(), (append?std::ios::app:std::ios::out));
for (int i=0; i<num_leaves_; i++) {
uchar *post = posteriors2_[i];
- for (int i=0; i<classes_; i++)
- file << int(*post++) << (i<classes_-1?" ":"");
+ for (int j=0; j<classes_; j++)
+ file << int(*post++) << (j<classes_-1?" ":"");
file << std::endl;
}
file.close();
for( x = 1; x < imgW; x++ )
{
- int d = MIN( x + 1, maxDisparity + 1);
+ int dp = MIN( x + 1, maxDisparity + 1);
uchar* _edges = edges + y*imgW + x;
int e0 = _edges[0] & 1;
_CvDPCell* _cell = cells + x*dispH;
do
{
- int s = dsi[d*imgW+x];
+ int _s = dsi[dp*imgW+x];
int sum[3];
//check left step
- sum[0] = _cell[d-dispH].sum - param2;
+ sum[0] = _cell[dp-dispH].sum - param2;
//check up step
- if( _cell[d+1].step != ICV_DP_STEP_DIAG && e0 )
+ if( _cell[dp+1].step != ICV_DP_STEP_DIAG && e0 )
{
- sum[1] = _cell[d+1].sum + param1;
+ sum[1] = _cell[dp+1].sum + param1;
- if( _cell[d-1-dispH].step != ICV_DP_STEP_UP && (_edges[1-d] & 2) )
+ if( _cell[dp-1-dispH].step != ICV_DP_STEP_UP && (_edges[1-dp] & 2) )
{
int t;
- sum[2] = _cell[d-1-dispH].sum + param1;
+ sum[2] = _cell[dp-1-dispH].sum + param1;
t = sum[1] < sum[0];
//choose local-optimal pass
if( sum[t] <= sum[2] )
{
- _cell[d].step = (uchar)t;
- _cell[d].sum = sum[t] + s;
+ _cell[dp].step = (uchar)t;
+ _cell[dp].sum = sum[t] + _s;
}
else
{
- _cell[d].step = ICV_DP_STEP_DIAG;
- _cell[d].sum = sum[2] + s;
+ _cell[dp].step = ICV_DP_STEP_DIAG;
+ _cell[dp].sum = sum[2] + _s;
}
}
else
{
if( sum[0] <= sum[1] )
{
- _cell[d].step = ICV_DP_STEP_LEFT;
- _cell[d].sum = sum[0] + s;
+ _cell[dp].step = ICV_DP_STEP_LEFT;
+ _cell[dp].sum = sum[0] + _s;
}
else
{
- _cell[d].step = ICV_DP_STEP_UP;
- _cell[d].sum = sum[1] + s;
+ _cell[dp].step = ICV_DP_STEP_UP;
+ _cell[dp].sum = sum[1] + _s;
}
}
}
- else if( _cell[d-1-dispH].step != ICV_DP_STEP_UP && (_edges[1-d] & 2) )
+ else if( _cell[dp-1-dispH].step != ICV_DP_STEP_UP && (_edges[1-dp] & 2) )
{
- sum[2] = _cell[d-1-dispH].sum + param1;
+ sum[2] = _cell[dp-1-dispH].sum + param1;
if( sum[0] <= sum[2] )
{
- _cell[d].step = ICV_DP_STEP_LEFT;
- _cell[d].sum = sum[0] + s;
+ _cell[dp].step = ICV_DP_STEP_LEFT;
+ _cell[dp].sum = sum[0] + _s;
}
else
{
- _cell[d].step = ICV_DP_STEP_DIAG;
- _cell[d].sum = sum[2] + s;
+ _cell[dp].step = ICV_DP_STEP_DIAG;
+ _cell[dp].sum = sum[2] + _s;
}
}
else
{
- _cell[d].step = ICV_DP_STEP_LEFT;
- _cell[d].sum = sum[0] + s;
+ _cell[dp].step = ICV_DP_STEP_LEFT;
+ _cell[dp].sum = sum[0] + _s;
}
}
- while( --d );
+ while( --dp );
}// for x
//extract optimal way and fill disparity image
//
// Returns: CV_NO_ERR or error code
//
-// Notes:
+// Notes:
//F*/
static CvStatus CV_STDCALL
icvCalcCovarMatrixEx_8u32fR( int nObjects, void *input, int objStep1,
/* Buffer size determination */
if( ioFlags )
{
- int size = icvDefaultBufferSize();
- ioBufSize = MIN( size, n );
+ ioBufSize = MIN( icvDefaultBufferSize(), n );
}
/* memory allocation (if necesseay) */
for( igr = 0; igr < ngr; igr++ )
{
- int i, io, ie, imin = igr * nio, imax = imin + nio;
+ int io, ie, imin = igr * nio, imax = imin + nio;
if( imax > m1 )
imax = m1;
- for( i = 0; i < eigSize.width * (imax - imin); i++ )
- ((float *) buffer)[i] = 0.f;
+ for(int k = 0; k < eigSize.width * (imax - imin); k++ )
+ ((float *) buffer)[k] = 0.f;
for( io = 0; io < nObjects; io++ )
{
int ioBufSize,
void* userData,
CvTermCriteria* calcLimit,
- IplImage* avg,
+ IplImage* avg,
float* eigVals )
{
float *avg_data;
avg_data, avg_step, obj_size );
__END__;
-
+
return coeff;
}
cvEigenDecomposite( IplImage* obj,
int nEigObjs,
void* eigInput,
- int ioFlags,
- void* userData,
- IplImage* avg,
+ int ioFlags,
+ void* userData,
+ IplImage* avg,
float* coeffs )
{
float *avg_data;
int nEigObjs,
int ioFlags,
void* userData,
- float* coeffs,
+ float* coeffs,
IplImage* avg,
IplImage* proj )
{
Mat samples = cvarrToMat(_samples), labels0, labels;
if( _labels )
labels0 = labels = cvarrToMat(_labels);
-
+
bool isOk = train(samples, Mat(), _params, _labels ? &labels : 0);
CV_Assert( labels0.data == labels.data );
{
CV_Assert(_sample_idx.empty());
Mat prbs, weights, means, logLikelihoods;
- std::vector<Mat> covsHdrs;
- init_params(_params, prbs, weights, means, covsHdrs);
+ std::vector<Mat> covshdrs;
+ init_params(_params, prbs, weights, means, covshdrs);
emObj = EM(_params.nclusters, _params.cov_mat_type, _params.term_crit);
bool isOk = false;
isOk = emObj.train(_samples,
logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
else if( _params.start_step == EM::START_E_STEP )
- isOk = emObj.trainE(_samples, means, covsHdrs, weights,
+ isOk = emObj.trainE(_samples, means, covshdrs, weights,
logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
else if( _params.start_step == EM::START_M_STEP )
isOk = emObj.trainM(_samples, prbs,
logLikelihoods, _labels ? _OutputArray(*_labels) : cv::noArray(), probs);
else
CV_Error(CV_StsBadArg, "Bad start type of EM algorithm");
-
+
if(isOk)
{
logLikelihood = sum(logLikelihoods).val[0];
for(cnt_cur=0; cnt_cur<clasters->total; ++cnt_cur)
{
CvRect rect;
- CvSeq* cnt;
+ CvSeq* cont;
int k = *(int*)cvGetSeqElem( clasters, cnt_cur );
if(k!=claster_cur) continue;
- cnt = *(CvSeq**)cvGetSeqElem( cnt_list, cnt_cur );
- rect = ((CvContour*)cnt)->rect;
+ cont = *(CvSeq**)cvGetSeqElem( cnt_list, cnt_cur );
+ rect = ((CvContour*)cont)->rect;
if(rect_res.height<0)
{
if(Good)
do{ /* For each configuration: */
CvBlob* pBL[EBD_FRAME_NUM];
- int Good = 1;
+ int good = 1;
double Error = 0;
CvBlob* pBNew = m_pBlobLists[EBD_FRAME_NUM-1]->GetBlob(pBLIndex[EBD_FRAME_NUM-1]);
Count++;
/* Check intersection last blob with existed: */
- if(Good && pOldBlobList)
+ if(good && pOldBlobList)
{ /* Check intersection last blob with existed: */
int k;
for(k=pOldBlobList->GetBlobNum(); k>0; --k)
CvBlob* pBOld = pOldBlobList->GetBlob(k-1);
if((fabs(pBOld->x-pBNew->x) < (CV_BLOB_RX(pBOld)+CV_BLOB_RX(pBNew))) &&
(fabs(pBOld->y-pBNew->y) < (CV_BLOB_RY(pBOld)+CV_BLOB_RY(pBNew))))
- Good = 0;
+ good = 0;
}
} /* Check intersection last blob with existed. */
/* Check distance to image border: */
- if(Good)
+ if(good)
{ /* Check distance to image border: */
CvBlob* pB = pBNew;
float dx = MIN(pB->x,S.width-pB->x)/CV_BLOB_RX(pB);
float dy = MIN(pB->y,S.height-pB->y)/CV_BLOB_RY(pB);
- if(dx < 1.1 || dy < 1.1) Good = 0;
+ if(dx < 1.1 || dy < 1.1) good = 0;
} /* Check distance to image border. */
/* Check uniform motion: */
- if(Good)
+ if(good)
{
int N = EBD_FRAME_NUM;
float sum[2] = {0,0};
if( Error > S.width*0.01 ||
fabs(a[0])>S.width*0.1 ||
fabs(a[1])>S.height*0.1)
- Good = 0;
+ good = 0;
} /* Check configuration. */
/* New best trajectory: */
- if(Good && (BestError == -1 || BestError > Error))
+ if(good && (BestError == -1 || BestError > Error))
{
for(i=0; i<EBD_FRAME_NUM; ++i)
{
if(i==EBD_FRAME_NUM)finish=1;
- } while(!finish); /* Check next time configuration of connected components. */
+ } while(!finish); /* Check next time configuration of connected components. */
#if 0
{/**/
/* allocate memory for 64d data */
int totalNum = 0;
- int i;
- for( i = 0; i < numImages; i++ )
+ for(int i = 0; i < numImages; i++ )
{
totalNum += numPoints[i];
}
points2 = (CvPoint3D64d*)calloc(numberPnt,sizeof(CvPoint3D64d));
/* Transform object points to first camera position */
- int i;
- for( i = 0; i < numberPnt; i++ )
+ for(int i = 0; i < numberPnt; i++ )
{
/* Create second camera point */
CvPoint3D64d tmpPoint;
dy = tmpPoint2.y - points1[i].y;
dz = tmpPoint2.z - points1[i].z;
err = sqrt(dx*dx + dy*dy + dz*dz);*/
-
-
}
#if 0
corns[3].x = 0;
corns[3].y = (float)(stereoparams->camera[0]->imgSize[1]-1);
- int i;
- for( i = 0; i < 4; i++ )
+ for(int i = 0; i < 4; i++ )
{
/* For first camera */
icvConvertWarpCoordinates( stereoparams->coeffs[0],
m_iNumLayers = 16;
assert(m_iNumLayers <= MAX_LAYERS);
m_pFaceList = new FaceDetectionList();
-
+
m_bBoosting = false;
if (m_mstgRects)
cvReleaseMemStorage(&m_mstgRects);
-
+
}// ~FaceDetection()
m_mstgRects = cvCreateMemStorage();
if (NULL == m_mstgRects)
return;
- m_seqRects = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvContourRect), m_mstgRects);
+ m_seqRects = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvContourRect), m_mstgRects);
if (NULL == m_seqRects)
return;
// find contours
buffImg += imgGray->widthStep;
}
// params
-
+
for (i = 0; i <= GIST_NUM; i ++)
{
if (gistImg[i] >= GIST_MIN)
break;
}
-
+
iMinLevel = i * GIST_STEP;
-
+
for (i = GIST_NUM; i >= 0; i --)
{
if (gistImg[i] >= GIST_MIN)
break;
}
-
+
iMaxLevel = i * GIST_STEP;
-
+
int dLevels = iMaxLevel - iMinLevel;
if (dLevels <= 0)
{
void FaceDetection::CreateResults(CvSeq * lpSeq)
{
-
+
Face * tmp;
-
+
double Max = 0;
double CurStat = 0;
-
+
FaceData tmpData;
if (m_bBoosting)
{
if (CurStat > Max)
Max = CurStat;
}
-
+
while ( (tmp = m_pFaceList->GetData()) != 0 )
{
tmp->CreateFace(&tmpData);
CurStat = tmp->GetWeight();
-
+
if (CurStat == Max)
{
CvFace tmpFace;
tmpFace.RightEyeRect = tmpData.RightEyeRect;
cvSeqPush(lpSeq,&tmpFace);
-
+
}
}
}
cvSeqPush(m_seqRects, &cr);
for (CvSeq* internal = external->v_next; internal; internal = internal->h_next)
{
- cr.r = cvContourBoundingRect(internal, 0);
+ cr.r = cvContourBoundingRect(internal, 0);
cr.pCenter.x = cr.r.x + cr.r.width / 2;
cr.pCenter.y = cr.r.y + cr.r.height / 2;
cr.iNumber = iLayer;
if (m_bBoosting)
PostBoostingFindCandidats(img);
else
- FindCandidats();
-
+ FindCandidats();
+
}// void FaceDetection::FindFace(IplImage *img)
RFace * lpFace1 = 0;
bool bInvalidRect1 = false;
CvRect * lpRect1 = NULL;
-
+
try
{
for (int i = 0; i < m_seqRects->total; i++)
3*(double)rect.width/(double)4,
(double)rect.width/(double)2,
(double)rect.width/(double)2);
-
+
lpFace1 = new RFace(lpFaceTemplate1);
-
+
for (int j = 0; j < m_seqRects->total; j++)
{
- CvContourRect* pRect = (CvContourRect*)cvGetSeqElem(m_seqRects, j);
-
+ CvContourRect* prect = (CvContourRect*)cvGetSeqElem(m_seqRects, j);
+
if ( !bInvalidRect1 )
{
lpRect1 = NULL;
lpRect1 = new CvRect();
- *lpRect1 = pRect->r;
+ *lpRect1 = prect->r;
}else
{
delete lpRect1;
lpRect1 = new CvRect();
- *lpRect1 = pRect->r;
+ *lpRect1 = prect->r;
}
-
-
+
+
if ( lpFace1->isFeature(lpRect1) )
- {
+ {
bFound1 = true;
bInvalidRect1 = false;
}else
bInvalidRect1 = true;
-
+
}
-
+
if (bFound1)
{
m_pFaceList->AddElem(lpFace1);
lpFace1 = NULL;
}
-
+
delete lpFaceTemplate1;
}
-
+
}
}
catch(...)
void FaceDetection::PostBoostingFindCandidats(IplImage * FaceImage)
{
BoostingFaceTemplate * lpFaceTemplate1 = 0;
- RFace * lpFace1 = 0;
+ RFace * lpFace1 = 0;
bool bInvalidRect1 = false;
CvRect * lpRect1 = NULL;
-
+
try
{
if ( ( !FaceImage->roi ) )
else
lpFaceTemplate1 = new BoostingFaceTemplate(3,cvRect(FaceImage->roi->xOffset,FaceImage->roi->yOffset,
FaceImage->roi->width,FaceImage->roi->height));
-
+
lpFace1 = new RFace(lpFaceTemplate1);
for (int i = 0; i < m_seqRects->total; i++)
{
CvContourRect* pRect = (CvContourRect*)cvGetSeqElem(m_seqRects, i);
-
+
if ( !bInvalidRect1 )
{
lpRect1 = NULL;
lpRect1 = new CvRect();
*lpRect1 = pRect->r;
}
-
-
+
+
if ( lpFace1->isFeature(lpRect1) )
- {
+ {
//bFound1 = true;
bInvalidRect1 = false;
}else
bInvalidRect1 = true;
-
+
}
-
+
m_pFaceList->AddElem(lpFace1);
lpFace1 = NULL;
-
+
delete lpFaceTemplate1;
}
catch(...)
#define _CV_CAUSAL 2
#define _CV_LAST_STATE 1
-#define _CV_BEST_STATE 2
+#define _CV_BEST_STATE 2
//*F///////////////////////////////////////////////////////////////////////////////////////
// Name: _cvCreateObsInfo
-// Purpose: The function allocates memory for CvImgObsInfo structure
+// Purpose: The function allocates memory for CvImgObsInfo structure
// and its inner stuff
// Context:
// Parameters: obs_info - addres of pointer to CvImgObsInfo structure
//
// Returns: error status
//
-// Notes:
-//F*/
-static CvStatus CV_STDCALL icvCreateObsInfo( CvImgObsInfo** obs_info,
+// Notes:
+//F*/
+static CvStatus CV_STDCALL icvCreateObsInfo( CvImgObsInfo** obs_info,
CvSize num_obs, int obs_size )
{
int total = num_obs.height * num_obs.width;
-
+
CvImgObsInfo* obs = (CvImgObsInfo*)cvAlloc( sizeof( CvImgObsInfo) );
-
+
obs->obs_x = num_obs.width;
obs->obs_y = num_obs.height;
obs->obs = (float*)cvAlloc( total * obs_size * sizeof(float) );
obs->state = (int*)cvAlloc( 2 * total * sizeof(int) );
- obs->mix = (int*)cvAlloc( total * sizeof(int) );
-
+ obs->mix = (int*)cvAlloc( total * sizeof(int) );
+
obs->obs_size = obs_size;
obs_info[0] = obs;
-
+
return CV_NO_ERR;
}
cvFree( &(obs_info->obs) );
cvFree( &(obs_info->mix) );
- cvFree( &(obs_info->state) );
+ cvFree( &(obs_info->state) );
cvFree( &(obs_info) );
p_obs_info[0] = NULL;
return CV_NO_ERR;
-}
+}
+
-
//*F///////////////////////////////////////////////////////////////////////////////////////
// Name: icvCreate2DHMM
-// Purpose: The function allocates memory for 2-dimensional embedded HMM model
+// Purpose: The function allocates memory for 2-dimensional embedded HMM model
// and its inner stuff
// Context:
// Parameters: hmm - addres of pointer to CvEHMM structure
// state_number - array of hmm sizes (size of array == state_number[0]+1 )
-// num_mix - number of gaussian mixtures in low-level HMM states
+// num_mix - number of gaussian mixtures in low-level HMM states
// size of array is defined by previous array values
// obs_size - length of observation vectors
//
//
// Notes: state_number[0] - number of states in external HMM.
// state_number[i] - number of states in embedded HMM
-//
+//
// example for face recognition: state_number = { 5 3 6 6 6 3 },
// length of num_mix array = 3+6+6+6+3 = 24//
//
/* allocate memory for all hmms (from all levels) */
hmm = (CvEHMM*)cvAlloc( (state_number[0] + 1) * sizeof(CvEHMM) );
-
+
/* set number of superstates */
hmm[0].num_states = state_number[0];
hmm[0].level = 1;
-
+
/* allocate memory for all states */
all_states = (CvEHMMState *)cvAlloc( real_states * sizeof( CvEHMMState ) );
for( i = 0; i < real_states; i++ )
{
total_mix += num_mix[i];
- }
+ }
/* allocate memory for states stuff */
- pointers = (float*)cvAlloc( total_mix * (2/*for mu invvar */ * obs_size +
+ pointers = (float*)cvAlloc( total_mix * (2/*for mu invvar */ * obs_size +
2/*for weight and log_var_val*/ ) * sizeof( float) );
-
+
/* organize memory */
for( i = 0; i < real_states; i++ )
{
- all_states[i].mu = pointers; pointers += num_mix[i] * obs_size;
+ all_states[i].mu = pointers; pointers += num_mix[i] * obs_size;
all_states[i].inv_var = pointers; pointers += num_mix[i] * obs_size;
all_states[i].log_var_val = pointers; pointers += num_mix[i];
all_states[i].weight = pointers; pointers += num_mix[i];
- }
-
+ }
+
/* set pointer to embedded hmm array */
hmm->u.ehmm = hmm + 1;
-
+
for( i = 0; i < hmm[0].num_states; i++ )
{
hmm[i+1].u.state = all_states;
all_states += state_number[i+1];
hmm[i+1].num_states = state_number[i+1];
- }
-
+ }
+
for( i = 0; i <= state_number[0]; i++ )
{
hmm[i].transP = icvCreateMatrix_32f( hmm[i].num_states, hmm[i].num_states );
hmm[i].obsProb = NULL;
hmm[i].level = i ? 0 : 1;
}
-
+
/* if all ok - return pointer */
*this_hmm = hmm;
return CV_NO_ERR;
-}
+}
static CvStatus CV_STDCALL icvRelease2DHMM( CvEHMM** phmm )
{
- CvEHMM* hmm = phmm[0];
+ CvEHMM* hmm = phmm[0];
int i;
for( i = 0; i < hmm[0].num_states + 1; i++ )
{
icvDeleteMatrix( hmm[i].transP );
- }
+ }
if (hmm->obsProb != NULL)
{
phmm[0] = NULL;
return CV_NO_ERR;
-}
+}
/* distance between 2 vectors */
static float icvSquareDistance( CvVect32f v1, CvVect32f v2, int len )
}
return (float)(dist0 + dist1);
-}
+}
/*can be used in CHMM & DHMM */
static CvStatus CV_STDCALL
if ( !obs_info || !hmm ) return CV_NULLPTR_ERR;
first_state = hmm->u.ehmm->u.state;
-
+
for (i = 0; i < obs_info->obs_y; i++)
{
//bad line (division )
int superstate = (int)((i * hmm->num_states)*inv_y);/* /obs_info->obs_y; */
-
+
int index = (int)(hmm->u.ehmm[superstate].u.state - first_state);
for (j = 0; j < obs_info->obs_x; j++, counter++)
{
int state = (int)((j * hmm->u.ehmm[superstate].num_states)* inv_x); /* / obs_info->obs_x; */
-
+
obs_info->state[2 * counter] = superstate;
obs_info->state[2 * counter + 1] = state + index;
}
- }
+ }
#else
//this is not ready yet
int i,j,k,m;
- CvEHMMState* first_state = hmm->u.ehmm->u.state;
+ CvEHMMState* first_state = hmm->u.ehmm->u.state;
/* check bad arguments */
if ( hmm->num_states > obs_info->obs_y ) return CV_BADSIZE_ERR;
//compute vertical subdivision
float row_per_state = (float)obs_info->obs_y / hmm->num_states;
float col_per_state[1024]; /* maximum 1024 superstates */
-
+
//for every horizontal band compute subdivision
for( i = 0; i < hmm->num_states; i++ )
{
obs_info->state[row * obs_info->obs_x + 2 * k] = i;
obs_info->state[row * obs_info->obs_x + 2 * k + 1] = j + index;
}
- col = es_bound[j];
+ col = es_bound[j];
}
//copy the same to other rows of superstate
for( m = row; m < ss_bound[i]; m++ )
{
- memcpy( &(obs_info->state[m * obs_info->obs_x * 2]),
+ memcpy( &(obs_info->state[m * obs_info->obs_x * 2]),
&(obs_info->state[row * obs_info->obs_x * 2]), obs_info->obs_x * 2 * sizeof(int) );
}
- row = ss_bound[i];
- }
+ row = ss_bound[i];
+ }
#endif
return CV_NO_ERR;
}
-
+
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: InitMixSegm
// Context: used with the Viterbi training of the embedded HMM
// Function uses K-Means algorithm for clustering
//
-// Parameters: obs_info_array - array of pointers to image observations
+// Parameters: obs_info_array - array of pointers to image observations
// num_img - length of above array
-// hmm - pointer to HMM structure
-//
+// hmm - pointer to HMM structure
+//
// Returns: error status
//
-// Notes:
+// Notes:
//F*/
static CvStatus CV_STDCALL
icvInitMixSegm( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm )
-{
- int k, i, j;
+{
+ int k, i, j;
int* num_samples; /* number of observations in every state */
int* counter; /* array of counters for every state */
-
+
int** a_class; /* for every state - characteristic array */
-
+
CvVect32f** samples; /* for every state - pointer to observation vectors */
- int*** samples_mix; /* for every state - array of pointers to vectors mixtures */
-
+ int*** samples_mix; /* for every state - array of pointers to vectors mixtures */
+
CvTermCriteria criteria = cvTermCriteria( CV_TERMCRIT_EPS|CV_TERMCRIT_ITER,
1000, /* iter */
0.01f ); /* eps */
-
+
int total = 0;
-
- CvEHMMState* first_state = hmm->u.ehmm->u.state;
-
+
+ CvEHMMState* first_state = hmm->u.ehmm->u.state;
+
for( i = 0 ; i < hmm->num_states; i++ )
{
total += hmm->u.ehmm[i].num_states;
- }
-
+ }
+
/* for every state integer is allocated - number of vectors in state */
num_samples = (int*)cvAlloc( total * sizeof(int) );
-
+
/* integer counter is allocated for every state */
counter = (int*)cvAlloc( total * sizeof(int) );
-
- samples = (CvVect32f**)cvAlloc( total * sizeof(CvVect32f*) );
- samples_mix = (int***)cvAlloc( total * sizeof(int**) );
-
+
+ samples = (CvVect32f**)cvAlloc( total * sizeof(CvVect32f*) );
+ samples_mix = (int***)cvAlloc( total * sizeof(int**) );
+
/* clear */
memset( num_samples, 0 , total*sizeof(int) );
memset( counter, 0 , total*sizeof(int) );
-
-
+
+
/* for every state the number of vectors which belong to it is computed (smth. like histogram) */
for (k = 0; k < num_img; k++)
- {
+ {
CvImgObsInfo* obs = obs_info_array[k];
int count = 0;
-
+
for (i = 0; i < obs->obs_y; i++)
{
for (j = 0; j < obs->obs_x; j++, count++)
num_samples[state] += 1;
}
}
- }
-
+ }
+
/* for every state int* is allocated */
a_class = (int**)cvAlloc( total*sizeof(int*) );
-
+
for (i = 0; i < total; i++)
{
a_class[i] = (int*)cvAlloc( num_samples[i] * sizeof(int) );
samples[i] = (CvVect32f*)cvAlloc( num_samples[i] * sizeof(CvVect32f) );
samples_mix[i] = (int**)cvAlloc( num_samples[i] * sizeof(int*) );
}
-
+
/* for every state vectors which belong to state are gathered */
for (k = 0; k < num_img; k++)
- {
+ {
CvImgObsInfo* obs = obs_info_array[k];
int num_obs = ( obs->obs_x ) * ( obs->obs_y );
float* vector = obs->obs;
for (i = 0; i < num_obs; i++, vector+=obs->obs_size )
{
int state = obs->state[2*i+1];
-
+
samples[state][counter[state]] = vector;
samples_mix[state][counter[state]] = &(obs->mix[i]);
- counter[state]++;
+ counter[state]++;
}
- }
-
+ }
+
/* clear counters */
memset( counter, 0, total*sizeof(int) );
-
+
/* do the actual clustering using the K Means algorithm */
for (i = 0; i < total; i++)
{
if ( first_state[i].num_mix == 1)
- {
+ {
for (k = 0; k < num_samples[i]; k++)
- {
+ {
/* all vectors belong to one mixture */
a_class[i][k] = 0;
}
- }
+ }
else if( num_samples[i] )
{
/* clusterize vectors */
- cvKMeans( first_state[i].num_mix, samples[i], num_samples[i],
+ cvKMeans( first_state[i].num_mix, samples[i], num_samples[i],
obs_info_array[0]->obs_size, criteria, a_class[i] );
- }
+ }
}
-
+
/* for every vector number of mixture is assigned */
for( i = 0; i < total; i++ )
{
samples_mix[i][j][0] = a_class[i][j];
}
}
-
+
for (i = 0; i < total; i++)
{
cvFree( &(a_class[i]) );
cvFree( &samples );
cvFree( &samples_mix );
cvFree( &counter );
- cvFree( &num_samples );
-
+ cvFree( &num_samples );
+
return CV_NO_ERR;
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: ComputeUniModeGauss
-// Purpose: The function computes the Gaussian pdf for a sample vector
+// Purpose: The function computes the Gaussian pdf for a sample vector
// Context:
// Parameters: obsVeq - pointer to the sample vector
// mu - pointer to the mean vector of the Gaussian pdf
// var - pointer to the variance vector of the Gaussian pdf
// VecSize - the size of sample vector
-//
-// Returns: the pdf of the sample vector given the specified Gaussian
//
-// Notes:
+// Returns: the pdf of the sample vector given the specified Gaussian
+//
+// Notes:
//F*/
-/*static float icvComputeUniModeGauss(CvVect32f vect, CvVect32f mu,
- CvVect32f inv_var, float log_var_val, int vect_size)
+/*static float icvComputeUniModeGauss(CvVect32f vect, CvVect32f mu,
+ CvVect32f inv_var, float log_var_val, int vect_size)
{
- int n;
+ int n;
double tmp;
double prob;
prob = prob - tmp * tmp;
}
//prob *= 0.5f;
-
+
return (float)prob;
-}*/
+}*/
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: ComputeGaussMixture
-// Purpose: The function computes the mixture Gaussian pdf of a sample vector.
+// Purpose: The function computes the mixture Gaussian pdf of a sample vector.
// Context:
// Parameters: obsVeq - pointer to the sample vector
// mu - two-dimensional pointer to the mean vector of the Gaussian pdf;
-// the first dimension is indexed over the number of mixtures and
+// the first dimension is indexed over the number of mixtures and
// the second dimension is indexed along the size of the mean vector
// var - two-dimensional pointer to the variance vector of the Gaussian pdf;
-// the first dimension is indexed over the number of mixtures and
+// the first dimension is indexed over the number of mixtures and
// the second dimension is indexed along the size of the variance vector
// VecSize - the size of sample vector
// weight - pointer to the wights of the Gaussian mixture
// NumMix - the number of Gaussian mixtures
-//
-// Returns: the pdf of the sample vector given the specified Gaussian mixture.
//
-// Notes:
+// Returns: the pdf of the sample vector given the specified Gaussian mixture.
+//
+// Notes:
//F*/
/* Calculate probability of observation at state in logarithmic scale*/
/*static float
-icvComputeGaussMixture( CvVect32f vect, float* mu,
- float* inv_var, float* log_var_val,
+icvComputeGaussMixture( CvVect32f vect, float* mu,
+ float* inv_var, float* log_var_val,
int vect_size, float* weight, int num_mix )
-{
+{
double prob, l_prob;
-
- prob = 0.0f;
+
+ prob = 0.0f;
if (num_mix == 1)
{
- return icvComputeUniModeGauss( vect, mu, inv_var, log_var_val[0], vect_size);
+ return icvComputeUniModeGauss( vect, mu, inv_var, log_var_val[0], vect_size);
}
else
{
for (m = 0; m < num_mix; m++)
{
if ( weight[m] > 0.0)
- {
- l_prob = icvComputeUniModeGauss(vect, mu + m*vect_size,
+ {
+ l_prob = icvComputeUniModeGauss(vect, mu + m*vect_size,
inv_var + m * vect_size,
- log_var_val[m],
- vect_size);
+ log_var_val[m],
+ vect_size);
prob = prob + weight[m]*exp((double)l_prob);
}
- }
- prob = log(prob);
- }
- return (float)prob;
-}*/
+ }
+ prob = log(prob);
+ }
+ return (float)prob;
+}*/
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: EstimateObsProb
-// Purpose: The function computes the probability of every observation in every state
+// Purpose: The function computes the probability of every observation in every state
// Context:
// Parameters: obs_info - observations
// hmm - hmm
-// Returns: error status
+// Returns: error status
//
-// Notes:
+// Notes:
//F*/
static CvStatus CV_STDCALL icvEstimateObsProb( CvImgObsInfo* obs_info, CvEHMM* hmm )
{
/* check if matrix exist and check current size
if not sufficient - realloc */
- int status = 0; /* 1 - not allocated, 2 - allocated but small size,
+ int status = 0; /* 1 - not allocated, 2 - allocated but small size,
3 - size is enough, but distribution is bad, 0 - all ok */
for( j = 0; j < hmm->num_states; j++ )
total_states += hmm->u.ehmm[j].num_states;
}
- if ( hmm->obsProb == NULL )
+ if ( hmm->obsProb == NULL )
{
/* allocare memory */
int need_size = ( obs_info->obs_x * obs_info->obs_y * total_states * sizeof(float) +
buffer[2] = obs_info->obs_x;
hmm->obsProb = (float**) (buffer + 3);
status = 3;
-
+
}
else
- {
+ {
/* check current size */
int* total= (int*)(((int*)(hmm->obsProb)) - 3);
int need_size = ( obs_info->obs_x * obs_info->obs_y * total_states * sizeof(float) +
assert( sizeof(float*) == sizeof(int) );
- if ( need_size > (*total) )
+ if ( need_size > (*total) )
{
int* buffer = ((int*)(hmm->obsProb)) - 3;
cvFree( &buffer);
buffer[2] = obs_info->obs_x;
hmm->obsProb = (float**)(buffer + 3);
-
+
status = 3;
- }
+ }
}
if (!status)
{
int* obsx = ((int*)(hmm->obsProb)) - 1;
int* obsy = ((int*)(hmm->obsProb)) - 2;
-
+
assert( (*obsx > 0) && (*obsy > 0) );
/* is good distribution? */
- if ( (obs_info->obs_x > (*obsx) ) || (obs_info->obs_y > (*obsy) ) )
- status = 3;
+ if ( (obs_info->obs_x > (*obsx) ) || (obs_info->obs_y > (*obsy) ) )
+ status = 3;
}
-
+
/* if bad status - do reallocation actions */
assert( (status == 0) || (status == 3) );
/* distribute pointers of ehmm->obsProb */
for( i = 0; i < hmm->num_states; i++ )
{
- hmm->u.ehmm[i].obsProb = tmp;
+ hmm->u.ehmm[i].obsProb = tmp;
tmp += obs_info->obs_y;
}
for( i = 0; i < hmm->num_states; i++ )
{
CvEHMM* ehmm = &( hmm->u.ehmm[i] );
-
+
for( j = 0; j < obs_info->obs_y; j++ )
{
ehmm->obsProb[j] = tmpf;
tmpf += ehmm->num_states * obs_info->obs_x;
- }
+ }
}
- }/* end of pointer distribution */
+ }/* end of pointer distribution */
-#if 1
+#if 1
{
#define MAX_BUF_SIZE 1200
float local_log_mix_prob[MAX_BUF_SIZE];
float* log_mix_prob = local_log_mix_prob;
double* mix_prob = local_mix_prob;
-
+
int max_size = 0;
int obs_x = obs_info->obs_x;
}
max_size *= obs_x * vect_size;
-
+
/* allocate buffer */
if( max_size > MAX_BUF_SIZE )
{
memset( log_mix_prob, 0, max_size*sizeof(float));
/*****************computing probabilities***********************/
-
+
/* loop through external states */
for( i = 0; i < hmm->num_states; i++ )
{
CvEHMM* ehmm = &(hmm->u.ehmm[i]);
CvEHMMState* state = ehmm->u.state;
-
+
int max_mix = 0;
int n_states = ehmm->num_states;
for( j = 0; j < obs_info->obs_y; j++ )
{
int m, n;
-
+
float* obs = obs_info->obs + j * obs_x * vect_size;
float* log_mp = max_mix > 1 ? log_mix_prob : ehmm->obsProb[j];
double* mp = mix_prob;
-
+
/* several passes are done below */
-
+
/* 1. calculate logarithms of probabilities for each mixture */
/* loop through mixtures */
for( j = 0; j < obs_info->obs_y; j++ )
{
int k,m;
-
+
int obs_index = j * obs_info->obs_x;
float* B = ehmm->obsProb[j];
-
+
/* cycles through obs and states */
for( k = 0; k < obs_info->obs_x; k++ )
{
CvVect32f vect = (obs_info->obs) + (obs_index + k) * vect_size;
-
+
float* matr_line = B + k * ehmm->num_states;
for( m = 0; m < ehmm->num_states; m++ )
{
- matr_line[m] = icvComputeGaussMixture( vect, state[m].mu, state[m].inv_var,
+ matr_line[m] = icvComputeGaussMixture( vect, state[m].mu, state[m].inv_var,
state[m].log_var_val, vect_size, state[m].weight,
state[m].num_mix );
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: EstimateTransProb
-// Purpose: The function calculates the state and super state transition probabilities
-// of the model given the images,
+// Purpose: The function calculates the state and super state transition probabilities
+// of the model given the images,
// the state segmentation and the input parameters
// Context:
-// Parameters: obs_info_array - array of pointers to image observations
+// Parameters: obs_info_array - array of pointers to image observations
// num_img - length of above array
-// hmm - pointer to HMM structure
+// hmm - pointer to HMM structure
// Returns: void
//
-// Notes:
+// Notes:
//F*/
static CvStatus CV_STDCALL
icvEstimateTransProb( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm )
CvEHMMState* first_state = hmm->u.ehmm->u.state;
/* as a counter we will use transP matrix */
-
+
/* initialization */
-
+
/* clear transP */
icvSetZero_32f( hmm->transP, hmm->num_states, hmm->num_states );
for (i = 0; i < hmm->num_states; i++ )
{
icvSetZero_32f( hmm->u.ehmm[i].transP , hmm->u.ehmm[i].num_states, hmm->u.ehmm[i].num_states );
}
-
+
/* compute the counters */
for (i = 0; i < num_img; i++)
{
int counter = 0;
CvImgObsInfo* info = obs_info_array[i];
-
+
for (j = 0; j < info->obs_y; j++)
{
for (k = 0; k < info->obs_x; k++, counter++)
{
/* compute how many transitions from state to state
- occured both in horizontal and vertical direction */
+ occured both in horizontal and vertical direction */
int superstate, state;
int nextsuperstate, nextstate;
int begin_ind;
superstate = info->state[2 * counter];
begin_ind = (int)(hmm->u.ehmm[superstate].u.state - first_state);
- state = info->state[ 2 * counter + 1] - begin_ind;
-
+ state = info->state[ 2 * counter + 1] - begin_ind;
+
if (j < info->obs_y - 1)
{
int transP_size = hmm->num_states;
-
+
nextsuperstate = info->state[ 2*(counter + info->obs_x) ];
hmm->transP[superstate * transP_size + nextsuperstate] += 1;
}
-
+
if (k < info->obs_x - 1)
- {
+ {
int transP_size = hmm->u.ehmm[superstate].num_states;
nextstate = info->state[2*(counter+1) + 1] - begin_ind;
//assert( total );
inv_total = total ? 1.f/total : 0;
-
+
for( j = 0; j < hmm->num_states; j++)
- {
- hmm->transP[i * hmm->num_states + j] =
- hmm->transP[i * hmm->num_states + j] ?
+ {
+ hmm->transP[i * hmm->num_states + j] =
+ hmm->transP[i * hmm->num_states + j] ?
(float)log( hmm->transP[i * hmm->num_states + j] * inv_total ) : -BIG_FLT;
}
}
-
+
/* estimate other matrices */
for( k = 0; k < hmm->num_states; k++ )
{
}
//assert( total );
inv_total = total ? 1.f/total : 0;
-
+
for( j = 0; j < ehmm->num_states; j++)
- {
- ehmm->transP[i * ehmm->num_states + j] =
+ {
+ ehmm->transP[i * ehmm->num_states + j] =
(ehmm->transP[i * ehmm->num_states + j]) ?
(float)log( ehmm->transP[i * ehmm->num_states + j] * inv_total) : -BIG_FLT ;
}
}
}
return CV_NO_ERR;
-}
-
+}
+
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: MixSegmL2
// embedded HMM
// Context: used with the Viterbi training of the embedded HMM
//
-// Parameters:
+// Parameters:
// obs_info_array
// num_img
// hmm
// Returns: void
//
-// Notes:
+// Notes:
//F*/
static CvStatus CV_STDCALL
icvMixSegmL2( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm )
{
int k, i, j, m;
-
+
CvEHMMState* state = hmm->u.ehmm[0].u.state;
-
-
+
+
for (k = 0; k < num_img; k++)
- {
+ {
int counter = 0;
CvImgObsInfo* info = obs_info_array[k];
{
int e_state = info->state[2 * counter + 1];
float min_dist;
-
- min_dist = icvSquareDistance((info->obs) + (counter * info->obs_size),
+
+ min_dist = icvSquareDistance((info->obs) + (counter * info->obs_size),
state[e_state].mu, info->obs_size);
- info->mix[counter] = 0;
-
+ info->mix[counter] = 0;
+
for (m = 1; m < state[e_state].num_mix; m++)
{
float dist=icvSquareDistance( (info->obs) + (counter * info->obs_size),
if (dist < min_dist)
{
min_dist = dist;
- /* assign mixture with smallest distance */
+ /* assign mixture with smallest distance */
info->mix[counter] = m;
}
}
}
}
return CV_NO_ERR;
-}
+}
/*
CvStatus icvMixSegmProb(CvImgObsInfo* obs_info, int num_img, CvEHMM* hmm )
{
int k, i, j, m;
-
+
CvEHMMState* state = hmm->ehmm[0].state_info;
-
-
+
+
for (k = 0; k < num_img; k++)
- {
+ {
int counter = 0;
CvImgObsInfo* info = obs_info + k;
{
int e_state = info->in_state[counter];
float max_prob;
-
- max_prob = icvComputeUniModeGauss( info->obs[counter], state[e_state].mu[0],
- state[e_state].inv_var[0],
+
+ max_prob = icvComputeUniModeGauss( info->obs[counter], state[e_state].mu[0],
+ state[e_state].inv_var[0],
state[e_state].log_var[0],
info->obs_size );
- info->mix[counter] = 0;
-
+ info->mix[counter] = 0;
+
for (m = 1; m < state[e_state].num_mix; m++)
{
float prob=icvComputeUniModeGauss(info->obs[counter], state[e_state].mu[m],
- state[e_state].inv_var[m],
+ state[e_state].inv_var[m],
state[e_state].log_var[m],
info->obs_size);
if (prob > max_prob)
{
max_prob = prob;
- // assign mixture with greatest probability.
+ // assign mixture with greatest probability.
info->mix[counter] = m;
}
}
}
}
- }
+ }
return CV_NO_ERR;
-}
+}
*/
static CvStatus CV_STDCALL
icvViterbiSegmentation( int num_states, int /*num_obs*/, CvMatr32f transP,
int** q, int min_num_obs, int max_num_obs,
float* prob )
{
- // memory allocation
+ // memory allocation
int i, j, last_obs;
int m_HMMType = _CV_ERGODIC; /* _CV_CAUSAL or _CV_ERGODIC */
-
+
int m_ProbType = prob_type; /* _CV_LAST_STATE or _CV_BEST_STATE */
-
+
int m_minNumObs = min_num_obs; /*??*/
int m_maxNumObs = max_num_obs; /*??*/
-
+
int m_numStates = num_states;
-
+
float* m_pi = (float*)cvAlloc( num_states* sizeof(float) );
CvMatr32f m_a = transP;
- // offset brobability matrix to starting observation
+ // offset brobability matrix to starting observation
CvMatr32f m_b = B + start_obs * num_states;
//so m_xl will not be used more
- //m_xl = start_obs;
+ //m_xl = start_obs;
- /* if (muDur != NULL){
+ /* if (muDur != NULL){
m_d = new int[m_numStates];
m_l = new double[m_numStates];
for (i = 0; i < m_numStates; i++){
- m_l[i] = muDur[i];
+ m_l[i] = muDur[i];
+ }
}
- }
else{
m_d = NULL;
m_l = NULL;
}
*/
-
+
CvMatr32f m_Gamma = icvCreateMatrix_32f( num_states, m_maxNumObs );
int* m_csi = (int*)cvAlloc( num_states * m_maxNumObs * sizeof(int) );
-
+
//stores maximal result for every ending observation */
CvVect32f m_MaxGamma = prob;
-
+
// assert( m_xl + max_num_obs <= num_obs );
m_pi[i] = -BIG_FLT;
}
m_pi[0] = 0.0f;
-
+
for (i = 0; i < num_states; i++)
{
m_Gamma[0 * num_states + i] = m_pi[i] + m_b[0 * num_states + i];
- m_csi[0 * num_states + i] = 0;
+ m_csi[0 * num_states + i] = 0;
}
-
+
/******************************************************************/
/* Viterbi recursion */
-
+
if ( m_HMMType == _CV_CAUSAL ) //causal model
{
- int t,j;
-
+ int t;
+
for (t = 1 ; t < m_maxNumObs; t++)
{
// evaluate self-to-self transition for state 0
m_Gamma[t * num_states + 0] = m_Gamma[(t-1) * num_states + 0] + m_a[0];
m_csi[t * num_states + 0] = 0;
-
+
for (j = 1; j < num_states; j++)
- {
+ {
float self = m_Gamma[ (t-1) * num_states + j] + m_a[ j * num_states + j];
float prev = m_Gamma[ (t-1) * num_states +(j-1)] + m_a[ (j-1) * num_states + j];
-
+
if ( prev > self )
{
m_csi[t * num_states + j] = j-1;
m_csi[t * num_states + j] = j;
m_Gamma[t * num_states + j] = self;
}
-
- m_Gamma[t * num_states + j] = m_Gamma[t * num_states + j] + m_b[t * num_states + j];
- }
+
+ m_Gamma[t * num_states + j] = m_Gamma[t * num_states + j] + m_b[t * num_states + j];
+ }
}
}
- else if ( m_HMMType == _CV_ERGODIC ) //ergodic model
- {
+ else if ( m_HMMType == _CV_ERGODIC ) //ergodic model
+ {
int t;
for (t = 1 ; t < m_maxNumObs; t++)
- {
+ {
for (j = 0; j < num_states; j++)
- {
- int i;
+ {
m_Gamma[ t*num_states + j] = m_Gamma[(t-1) * num_states + 0] + m_a[0*num_states+j];
m_csi[t *num_states + j] = 0;
-
+
for (i = 1; i < num_states; i++)
{
- float currGamma = m_Gamma[(t-1) *num_states + i] + m_a[i *num_states + j];
+ float currGamma = m_Gamma[(t-1) *num_states + i] + m_a[i *num_states + j];
if (currGamma > m_Gamma[t *num_states + j])
- {
+ {
m_Gamma[t * num_states + j] = currGamma;
m_csi[t * num_states + j] = i;
}
- }
+ }
m_Gamma[t *num_states + j] = m_Gamma[t *num_states + j] + m_b[t * num_states + j];
- }
- }
+ }
+ }
}
for( last_obs = m_minNumObs-1, i = 0; last_obs < m_maxNumObs; last_obs++, i++ )
/******************************************************************/
/* Viterbi termination */
-
+
if ( m_ProbType == _CV_LAST_STATE )
{
m_MaxGamma[i] = m_Gamma[last_obs * num_states + num_states - 1];
else if( m_ProbType == _CV_BEST_STATE )
{
int k;
- q[i][last_obs] = 0;
- m_MaxGamma[i] = m_Gamma[last_obs * num_states + 0];
-
+ q[i][last_obs] = 0;
+ m_MaxGamma[i] = m_Gamma[last_obs * num_states + 0];
+
for(k = 1; k < num_states; k++)
- {
+ {
if ( m_Gamma[last_obs * num_states + k] > m_MaxGamma[i] )
{
m_MaxGamma[i] = m_Gamma[last_obs * num_states + k];
q[i][last_obs] = k;
- }
+ }
}
- }
-
+ }
+
/******************************************************************/
/* Viterbi backtracking */
for (t = last_obs-1; t >= 0; t--)
{
- q[i][t] = m_csi[(t+1) * num_states + q[i][t+1] ];
- }
- }
-
+ q[i][t] = m_csi[(t+1) * num_states + q[i][t+1] ];
+ }
+ }
+
/* memory free */
cvFree( &m_pi );
cvFree( &m_csi );
- icvDeleteMatrix( m_Gamma );
-
+ icvDeleteMatrix( m_Gamma );
+
return CV_NO_ERR;
-}
+}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: icvEViterbi
// Purpose: The function calculates the embedded Viterbi algorithm
-// for 1 image
+// for 1 image
// Context:
-// Parameters:
+// Parameters:
// obs_info - observations
// hmm - HMM
-//
-// Returns: the Embedded Viterbi probability (float)
+//
+// Returns: the Embedded Viterbi probability (float)
// and do state segmentation of observations
//
-// Notes:
+// Notes:
//F*/
static float CV_STDCALL icvEViterbi( CvImgObsInfo* obs_info, CvEHMM* hmm )
{
float inv_obs_x = 1.f / obs_info->obs_x;
CvEHMMState* first_state = hmm->u.ehmm->u.state;
-
+
/* memory allocation for superB */
CvMatr32f superB = icvCreateMatrix_32f(hmm->num_states, obs_info->obs_y );
-
+
/* memory allocation for q */
int*** q = (int***)cvAlloc( hmm->num_states * sizeof(int**) );
int* super_q = (int*)cvAlloc( obs_info->obs_y * sizeof(int) );
-
+
for (i = 0; i < hmm->num_states; i++)
{
q[i] = (int**)cvAlloc( obs_info->obs_y * sizeof(int*) );
-
+
for (j = 0; j < obs_info->obs_y ; j++)
{
q[i][j] = (int*)cvAlloc( obs_info->obs_x * sizeof(int) );
}
- }
-
+ }
+
/* start Viterbi segmentation */
for (i = 0; i < hmm->num_states; i++)
{
CvEHMM* ehmm = &(hmm->u.ehmm[i]);
-
+
for (j = 0; j < obs_info->obs_y; j++)
{
float max_gamma;
-
+
/* 1D HMM Viterbi segmentation */
- icvViterbiSegmentation( ehmm->num_states, obs_info->obs_x,
- ehmm->transP, ehmm->obsProb[j], 0,
+ icvViterbiSegmentation( ehmm->num_states, obs_info->obs_x,
+ ehmm->transP, ehmm->obsProb[j], 0,
_CV_LAST_STATE, &q[i][j], obs_info->obs_x,
obs_info->obs_x, &max_gamma);
-
+
superB[j * hmm->num_states + i] = max_gamma * inv_obs_x;
}
}
-
+
/* perform global Viterbi segmentation (i.e. process higher-level HMM) */
-
- icvViterbiSegmentation( hmm->num_states, obs_info->obs_y,
- hmm->transP, superB, 0,
+
+ icvViterbiSegmentation( hmm->num_states, obs_info->obs_y,
+ hmm->transP, superB, 0,
_CV_LAST_STATE, &super_q, obs_info->obs_y,
obs_info->obs_y, &log_likelihood );
-
- log_likelihood /= obs_info->obs_y ;
-
-
+
+ log_likelihood /= obs_info->obs_y ;
+
+
counter = 0;
/* assign new state to observation vectors */
for (i = 0; i < obs_info->obs_y; i++)
- {
+ {
for (j = 0; j < obs_info->obs_x; j++, counter++)
{
int superstate = super_q[i];
int state = (int)(hmm->u.ehmm[superstate].u.state - first_state);
-
+
obs_info->state[2 * counter] = superstate;
obs_info->state[2 * counter + 1] = state + q[superstate][i][j];
}
}
-
+
/* memory deallocation for superB */
icvDeleteMatrix( superB );
-
+
/*memory deallocation for q */
for (i = 0; i < hmm->num_states; i++)
{
}
cvFree( &q[i] );
}
-
+
cvFree( &q );
cvFree( &super_q );
-
+
return log_likelihood;
-}
+}
static CvStatus CV_STDCALL
icvEstimateHMMStateParams( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm )
float start_log_var_val = LN2PI * vect_len;
CvVect32f tmp_vect = icvCreateVector_32f( vect_len );
-
+
CvEHMMState* first_state = hmm->u.ehmm[0].u.state;
assert( sizeof(float) == sizeof(int) );
for (m = 0; m < first_state[i].num_mix; m++)
{
((int*)(first_state[i].weight))[m] = 0;
- }
+ }
}
-
+
/* maybe gamma must be computed in mixsegm process ?? */
/* compute gamma */
int state, mixture;
state = info->state[2*i + 1];
mixture = info->mix[i];
- /* computes gamma - number of observations corresponding
- to every mixture of every state */
- ((int*)(first_state[state].weight))[mixture] += 1;
+ /* computes gamma - number of observations corresponding
+ to every mixture of every state */
+ ((int*)(first_state[state].weight))[mixture] += 1;
}
- }
+ }
/***************Mean and Var***********************/
/* compute means and variances of every item */
/* initially variance placed to inv_var */
/* zero mean and variance */
for (i = 0; i < total; i++)
{
- memset( (void*)first_state[i].mu, 0, first_state[i].num_mix * vect_len *
+ memset( (void*)first_state[i].mu, 0, first_state[i].num_mix * vect_len *
sizeof(float) );
- memset( (void*)first_state[i].inv_var, 0, first_state[i].num_mix * vect_len *
+ memset( (void*)first_state[i].inv_var, 0, first_state[i].num_mix * vect_len *
sizeof(float) );
}
-
+
/* compute sums */
for (i = 0; i < num_img; i++)
{
float* vector = info->obs;
for (j = 0; j < total_obs; j++, vector+=vect_len )
- {
+ {
int state = info->state[2 * j + 1];
- int mixture = info->mix[j];
-
+ int mixture = info->mix[j];
+
CvVect32f mean = first_state[state].mu + mixture * vect_len;
CvVect32f mean2 = first_state[state].inv_var + mixture * vect_len;
-
+
icvAddVector_32f( mean, vector, mean, vect_len );
for( k = 0; k < vect_len; k++ )
mean2[k] += vector[k]*vector[k];
- }
+ }
}
-
+
/*compute the means and variances */
/* assume gamma already computed */
for (i = 0; i < total; i++)
- {
+ {
CvEHMMState* state = &(first_state[i]);
for (m = 0; m < state->num_mix; m++)
{
- int k;
CvVect32f mu = state->mu + m * vect_len;
- CvVect32f invar = state->inv_var + m * vect_len;
-
+ CvVect32f invar = state->inv_var + m * vect_len;
+
if ( ((int*)state->weight)[m] > 1)
{
float inv_gamma = 1.f/((int*)(state->weight))[m];
-
+
icvScaleVector_32f( mu, mu, vect_len, inv_gamma);
icvScaleVector_32f( invar, invar, vect_len, inv_gamma);
}
icvMulVectors_32f(mu, mu, tmp_vect, vect_len);
- icvSubVector_32f( invar, tmp_vect, invar, vect_len);
-
+ icvSubVector_32f( invar, tmp_vect, invar, vect_len);
+
/* low bound of variance - 100 (Ara's experimental result) */
for( k = 0; k < vect_len; k++ )
{
for( k = 0; k < vect_len; k++ )
{
state->log_var_val[m] += (float)log( invar[k] );
- }
+ }
/* SMOLI 27.10.2000 */
state->log_var_val[m] *= 0.5;
cvbInvSqrt( invar, invar, vect_len );
}
}
-
+
/***************Weights***********************/
/* normilize gammas - i.e. compute mixture weights */
-
+
//compute weights
for (i = 0; i < total; i++)
- {
+ {
int gamma_total = 0;
float norm;
for (m = 0; m < first_state[i].num_mix; m++)
{
- gamma_total += ((int*)(first_state[i].weight))[m];
+ gamma_total += ((int*)(first_state[i].weight))[m];
}
norm = gamma_total ? (1.f/(float)gamma_total) : 0.f;
-
+
for (m = 0; m < first_state[i].num_mix; m++)
{
first_state[i].weight[m] = ((int*)(first_state[i].weight))[m] * norm;
- }
- }
+ }
+ }
icvDeleteVector( tmp_vect);
- return CV_NO_ERR;
-}
+ return CV_NO_ERR;
+}
/*
CvStatus icvLightingCorrection8uC1R( uchar* img, CvSize roi, int src_step )
int i, j;
int width = roi.width;
int height = roi.height;
-
+
float x1, x2, y1, y2;
int f[3] = {0, 0, 0};
float a[3] = {0, 0, 0};
-
+
float h1;
float h2;
-
+
float c1,c2;
-
+
float min = FLT_MAX;
float max = -FLT_MAX;
float correction;
-
+
float* float_img = icvAlloc( width * height * sizeof(float) );
-
+
x1 = width * (width + 1) / 2.0f; // Sum (1, ... , width)
x2 = width * (width + 1 ) * (2 * width + 1) / 6.0f; // Sum (1^2, ... , width^2)
y1 = height * (height + 1)/2.0f; // Sum (1, ... , width)
y2 = height * (height + 1 ) * (2 * height + 1) / 6.0f; // Sum (1^2, ... , width^2)
-
-
+
+
// extract grayvalues
for (i = 0; i < height; i++)
{
f[0] = f[0] + img[i*src_step + j];
}
}
-
+
h1 = (float)f[0] * (float)x1 / (float)width;
h2 = (float)f[0] * (float)y1 / (float)height;
-
+
a[2] = ((float)f[2] - h1) / (float)(x2*height - x1*x1*height/(float)width);
a[1] = ((float)f[1] - h2) / (float)(y2*width - y1*y1*width/(float)height);
- a[0] = (float)f[0]/(float)(width*height) - (float)y1*a[1]/(float)height -
+ a[0] = (float)f[0]/(float)(width*height) - (float)y1*a[1]/(float)height -
(float)x1*a[2]/(float)width;
-
- for (i = 0; i < height; i++)
- {
+
+ for (i = 0; i < height; i++)
+ {
for (j = 0; j < width; j++)
{
-
+
correction = a[0] + a[1]*(float)i + a[2]*(float)j;
-
+
float_img[i*width + j] = img[i*src_step + j] - correction;
-
+
if (float_img[i*width + j] < min) min = float_img[i*width+j];
if (float_img[i*width + j] > max) max = float_img[i*width+j];
}
}
-
+
//rescaling to the range 0:255
c2 = 0;
if (max == min)
c2 = 255.0f;
else
c2 = 255.0f/(float)(max - min);
-
+
c1 = (-(float)min)*c2;
-
+
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
cvFree( &float_img );
return CV_NO_ERR;
}
-
-CvStatus icvLightingCorrection( icvImage* img )
+
+CvStatus icvLightingCorrection( icvImage* img )
{
CvSize roi;
if ( img->type != IPL_DEPTH_8U || img->channels != 1 )
return CV_BADFACTOR_ERR;
roi = _cvSize( img->roi.width, img->roi.height );
-
- return _cvLightingCorrection8uC1R( img->data + img->roi.y * img->step + img->roi.x,
+
+ return _cvLightingCorrection8uC1R( img->data + img->roi.y * img->step + img->roi.x,
roi, img->step );
}
/////////////////////////////// CvMatrix implementation //////////////////////////////////
-CvMatrix::CvMatrix( int rows, int cols, int type, CvMemStorage* storage, bool alloc_data )
+CvMatrix::CvMatrix( int _rows, int _cols, int _type, CvMemStorage* storage, bool alloc_data )
{
if( storage )
{
matrix = (CvMat*)cvMemStorageAlloc( storage, sizeof(*matrix) );
- cvInitMatHeader( matrix, rows, cols, type, alloc_data ?
- cvMemStorageAlloc( storage, rows*cols*CV_ELEM_SIZE(type) ) : 0 );
+ cvInitMatHeader( matrix, _rows, _cols, _type, alloc_data ?
+ cvMemStorageAlloc( storage, _rows*_cols*CV_ELEM_SIZE(_type) ) : 0 );
}
else
matrix = 0;
#include "_kdtree.hpp"
#include "_featuretree.h"
-#if defined _MSC_VER && _MSC_VER >= 1400
-#pragma warning(disable:4996) // suppress "function call with parameters may be unsafe" in std::copy
-#endif
-
class CvKDTreeWrap : public CvFeatureTree {
template <class __scalartype, int __cvtype>
struct deref {
}
/* ----- End test ----- */
- int i;
-
/* Allocate memory for derivates */
double p[12];
/* Copy projection matrix */
- for( i = 0; i < 12; i++ )
+ for(int i = 0; i < 12; i++ )
{
p[i] = cvmGet(projMatr,i/4,i%4);
}
piX[1] = X[0]*p[4] + X[1]*p[5] + X[2]*p[6] + X[3]*p[7];
piX[2] = X[0]*p[8] + X[1]*p[9] + X[2]*p[10] + X[3]*p[11];
- int i;
/* fill derivate by point */
double tmp3 = 1/(piX[2]*piX[2]);
double tmp2 = -piX[1]*tmp3;
/* fill derivate by projection matrix */
- for( i = 0; i < 4; i++ )
+ for(int i = 0; i < 4; i++ )
{
/* derivate for x */
cvmSet(derivProj,currVisPoint*2,i,X[i]/piX[2]);//x' p1i
/* Compute derivates by points */
double p[12];
- int i;
- for( i = 0; i < 12; i++ )
+ for(int i = 0; i < 12; i++ )
{
p[i] = cvmGet(projMatr,i/4,i%4);
}
piX[1] = X[0]*p[4] + X[1]*p[5] + X[2]*p[6] + X[3]*p[7];
piX[2] = X[0]*p[8] + X[1]*p[9] + X[2]*p[10] + X[3]*p[11];
- int i,j;
-
double tmp3 = 1/(piX[2]*piX[2]);
- for( j = 0; j < 2; j++ )//for x and y
+ for(int j = 0; j < 2; j++ )//for x and y
{
- for( i = 0; i < 4; i++ )// for X,Y,Z,W
+ for(int i = 0; i < 4; i++ )// for X,Y,Z,W
{
cvmSet( derivPoint,
j, currVisPoint*4+i,
double point3D_dat[3];
point3D = cvMat(3,1,CV_64F,point3D_dat);
- int currPoint;
int numVis = 0;
double totalError = 0;
- for( currPoint = 0; currPoint < numPoints; currPoint++ )
+ for(int curPoint = 0; curPoint < numPoints; curPoint++ )
{
- if( cvmGet(presPoints[currImage],0,currPoint) > 0)
+ if( cvmGet(presPoints[currImage],0,curPoint) > 0)
{
double dx,dy;
- cvGetCol(points4D,&point4D,currPoint);
+ cvGetCol(points4D,&point4D,curPoint);
cvmMul(projMatrs[currImage],&point4D,&point3D);
double w = point3D_dat[2];
double x = point3D_dat[0] / w;
double y = point3D_dat[1] / w;
- dx = cvmGet(projPoints[currImage],0,currPoint) - x;
- dy = cvmGet(projPoints[currImage],1,currPoint) - y;
+ dx = cvmGet(projPoints[currImage],0,curPoint) - x;
+ dy = cvmGet(projPoints[currImage],1,curPoint) - y;
if( projError )
{
- cvmSet(projError[currImage],0,currPoint,dx);
- cvmSet(projError[currImage],1,currPoint,dy);
+ cvmSet(projError[currImage],0,curPoint,dx);
+ cvmSet(projError[currImage],1,curPoint,dy);
}
totalError += sqrt(dx*dx+dy*dy);
numVis++;
CV_CALL( changeVectorX_points4D = cvCreateMat(4,numPoints,CV_64F));
CV_CALL( changeVectorX_projMatrs = cvCreateMat(3,4,CV_64F));
- int currImage;
-
/* ----- Test input params ----- */
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
/* Test size of input initial and result projection matrices */
if( !CV_IS_MAT(projMatrs[currImage]) )
/* ----- End test ----- */
/* Copy projection matrices to vectorX0 */
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
CV_CALL( vectorX_projMatrs[currImage] = cvCreateMat(3,4,CV_64F));
CV_CALL( newVectorX_projMatrs[currImage] = cvCreateMat(3,4,CV_64F));
CV_CALL( workMatrsInvVi[i] = cvCreateMat(4,4,CV_64F) );
}
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
CV_CALL( matrsUk[currImage] = cvCreateMat(12,12,CV_64F) );
CV_CALL( workMatrsUk[currImage] = cvCreateMat(12,12,CV_64F) );
/* Compute error with observed value and computed projection */
double prevError;
prevError = 0;
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
cvSub(observVisPoints[currImage],projVisPoints[currImage],errorProjPoints[currImage]);
double currNorm = cvNorm(errorProjPoints[currImage]);
fprintf(file,"projection errors\n");
/* Print all proejction errors */
- int currImage;
- for( currImage = 0; currImage < numImages; currImage++)
+ for(int currImage = 0; currImage < numImages; currImage++)
{
fprintf(file,"\nImage=%d\n",currImage);
int numPn = errorProjPoints[currImage]->cols;
}
#endif
/* Copy matrices Uk to work matrices Uk */
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
cvCopy(matrsUk[currImage],workMatrsUk[currImage]);
}
{
cvCopy(matrsVi[currV],workMatrVi);
- for( int i = 0; i < 4; i++ )
+ for( i = 0; i < 4; i++ )
{
cvmSet(workMatrVi,i,i,cvmGet(matrsVi[currV],i,i)*(1+alpha) );
}
}
/* Add alpha to matrUk and make matrix workMatrsUk */
- for( currImage = 0; currImage< numImages; currImage++ )
+ for(int currImage = 0; currImage< numImages; currImage++ )
{
for( i = 0; i < 12; i++ )
int currRowV;
for( currRowV = 0; currRowV < 4; currRowV++ )
{
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
for( int currCol = 0; currCol < 12; currCol++ )/* For each column of transposed matrix W */
{
cvmMul(matrW,matrTmpSys1,matrSysDeltaP);
/* need to compute U-matrTmpSys2. But we compute matTmpSys2-U */
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
CvMat subMatr;
cvGetSubRect(matrSysDeltaP,&subMatr,cvRect(currImage*12,currImage*12,12,12));
FILE* file;
file = fopen( TRACK_BUNDLE_FILE_DELTAP ,"w");
- int currImage;
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
fprintf(file,"\nImage=%d\n",currImage);
int i;
/* We know delta and compute new value of vector X: nextVectX = vectX + deltas */
/* Compute new P */
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
for( i = 0; i < 3; i++ )
{
icvProjPointsStatusFunc(numImages, newVectorX_points4D, newVectorX_projMatrs, pointsPres, projVisPoints);
/* Compute error with observed value and computed projection */
double newError = 0;
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
cvSub(observVisPoints[currImage],projVisPoints[currImage],errorProjPoints[currImage]);
double currNorm = cvNorm(errorProjPoints[currImage]);
/* Print all projection errors */
#if 0
fprintf(file,"projection errors\n");
- int currImage;
- for( currImage = 0; currImage < numImages; currImage++)
+ for(int currImage = 0; currImage < numImages; currImage++)
{
fprintf(file,"\nImage=%d\n",currImage);
int numPn = errorProjPoints[currImage]->cols;
double currNorm1 = 0;
double currNorm2 = 0;
/* compute norm for projection matrices */
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
currNorm1 = cvNorm(newVectorX_projMatrs[currImage],vectorX_projMatrs[currImage]);
currNorm2 = cvNorm(newVectorX_projMatrs[currImage]);
}
alpha /= 10;
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
cvCopy(newVectorX_projMatrs[currImage],vectorX_projMatrs[currImage]);
}
/*--------------------------------------------*/
/* Optimization complete copy computed params */
/* Copy projection matrices */
- for( currImage = 0; currImage < numImages; currImage++ )
+ for(int currImage = 0; currImage < numImages; currImage++ )
{
cvCopy(newVectorX_projMatrs[currImage],resultProjMatrs[currImage]);
}
}
cvAdd(pca_descriptors[0].GetPatch(i), m_samples[i], m_samples[i]);
- double sum = cvSum(m_samples[i]).val[0];
- cvConvertScale(m_samples[i], m_samples[i], 1.0/sum);
+ double sm = cvSum(m_samples[i]).val[0];
+ cvConvertScale(m_samples[i], m_samples[i], 1.0/sm);
#if 0
IplImage* test = cvCreateImage(cvSize(12, 12), IPL_DEPTH_8U, 1);
if (! m_pca_descriptors[i].ReadByName(fn, buf))
{
- char buf[1024];
sprintf(buf, "descriptor for pca component %d", i);
m_pca_descriptors[i].ReadByName(fn, buf);
}
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
int norphans = 0, maxOrphans = _maxOrphans;
GCVtx** orphans = _orphans;
stub.next = nilNode;
-
+
// initialize the active queue and the graph vertices
for( i = 0; i < nvtx; i++ )
{
GCVtx* v, *u;
int e0 = -1, ei = 0, ej = 0, min_weight, weight;
uchar vt;
-
+
// grow S & T search trees, find an edge connecting them
while( first != nilNode )
{
v->parent = ORPHAN;
}
}
-
+
v->weight = (short)(v->weight + min_weight*(1-k*2));
if( v->weight == 0 )
{
curr_ts++;
while( norphans > 0 )
{
- GCVtx* v = orphans[--norphans];
+ GCVtx* v1 = orphans[--norphans];
int d, min_dist = INT_MAX;
e0 = 0;
- vt = v->t;
+ vt = v1->t;
- for( ei = v->first; ei != 0; ei = edges[ei].next )
+ for( ei = v1->first; ei != 0; ei = edges[ei].next )
{
if( edges[ei^(vt^1)].weight == 0 )
continue;
}
}
- if( (v->parent = e0) > 0 )
+ if( (v1->parent = e0) > 0 )
{
- v->ts = curr_ts;
- v->dist = min_dist;
+ v1->ts = curr_ts;
+ v1->dist = min_dist;
continue;
}
/* no parent is found */
- v->ts = 0;
- for( ei = v->first; ei != 0; ei = edges[ei].next )
+ v1->ts = 0;
+ for( ei = v1->first; ei != 0; ei = edges[ei].next )
{
u = edges[ei].dst;
ej = u->parent;
u->next = nilNode;
last = last->next = u;
}
- if( ej > 0 && edges[ej].dst == v )
+ if( ej > 0 && edges[ej].dst == v1 )
{
if( norphans >= maxOrphans )
maxOrphans = icvGCResizeOrphansBuf( orphans, norphans );
void cvReleaseStereoGCState( CvStereoGCState** _state )
{
CvStereoGCState* state;
-
+
if( !_state && !*_state )
return;
CvMat* left3, CvMat* right3 )
{
int k, x, y, rows = left->rows, cols = left->cols;
-
+
for( k = 0; k < 2; k++ )
{
const CvMat* src = k == 0 ? left : right;
const uchar* sptr_next = y < rows-1 ? sptr + sstep : sptr;
uchar* dptr = dst->data.ptr + dst->step*y;
int v_prev = sptr[0];
-
+
for( x = 0; x < cols; x++, dptr += 3 )
{
int v = sptr[x], v1, minv = v, maxv = v;
-
+
v1 = (v + v_prev)/2;
minv = MIN(minv, v1); maxv = MAX(maxv, v1);
v1 = (v + sptr_prev[x])/2;
{
const uchar* lptr = state->left->data.ptr + state->left->step*y;
const uchar* rptr = state->right->data.ptr + state->right->step*y;
-
+
for( x = 0; x < cols; x++ )
{
for( d = maxd-1, i = 0; d >= mind; d-- )
GCVtx** pright = pright0 + pstep*y;
const uchar* lr[] = { left, right };
const short* dlr[] = { dleft, dright };
- GCVtx** plr[] = { pleft, pright };
+ GCVtx** plr[] = { pleft, pright };
for( k = 0; k < 2; k++ )
{
GCVtx** pright = pright0 + pstep*y;
for( x = 0; x < cols; x++ )
{
- GCVtx* var = pleft[x];
- if( var && var->parent && var->t )
- dleft[x] = (short)alpha;
+ GCVtx* var2 = pleft[x];
+ if( var2 && var2->parent && var2->t )
+ dleft[x] = (short)alpha;
- var = pright[x];
- if( var && var->parent && var->t )
+ var2 = pright[x];
+ if( var2 && var2->parent && var2->t )
dright[x] = (short)-alpha;
}
}
icvInitStereoConstTabs();
icvInitGraySubpix( left, right, state->left, state->right );
-
+
std::vector<int> disp(state->numberOfDisparities);
CvMat _disp = cvMat( 1, (int)disp.size(), CV_32S, &disp[0] );
cvRange( &_disp, state->minDisparity, state->minDisparity + state->numberOfDisparities );
int y0=0, y1=pFG->height-1;
for(y0=0; y0<pFG->height; ++y0)
{
- CvMat m;
- CvScalar s = cvSum(cvGetRow(pFG, &m, y0));
+ CvMat tmp;
+ CvScalar s = cvSum(cvGetRow(pFG, &tmp, y0));
if(s.val[0] > 255*7) break;
}
for(y1=pFG->height-1; y1>0; --y1)
{
- CvMat m;
- CvScalar s = cvSum(cvGetRow(pFG, &m, y1));
+ CvMat tmp;
+ CvScalar s = cvSum(cvGetRow(pFG, &tmp, y1));
if(s.val[0] > 255*7) break;
}
p->FrameNum = cvReadIntByName( fs, node, "FrameNum", p->FrameNum );
p->FrameNum = cvReadIntByName( fs, node, "Dur", p->FrameNum );
{
- int LastFrame = cvReadIntByName( fs, node, "LastFrame", p->FrameBegin+p->FrameNum-1 );
- p->FrameNum = MIN(p->FrameNum,LastFrame - p->FrameBegin+1);
+ int lastFrame = cvReadIntByName( fs, node, "LastFrame", p->FrameBegin+p->FrameNum-1 );
+ p->FrameNum = MIN(p->FrameNum,lastFrame - p->FrameBegin+1);
}
icvTestSeqAllocTrans(p);
if(pTransSeq&&KeyFrameNum>1)
{
- int i0,i1,i;
- for(i=0; i<KeyFrameNum; ++i)
+ int i0,i1;
+ for(int i=0; i<KeyFrameNum; ++i)
{
CvFileNode* pTN = (CvFileNode*)cvGetSeqElem(pTransSeq,i);
KeyFrames[i] = cvReadIntByName(fs,pTN,"frame",-1);
for(i0=0, i1=1; i1<KeyFrameNum;)
{
- int i;
-
for(i1=i0+1; i1<KeyFrameNum && KeyFrames[i1]<0; i1++);
assert(i1<KeyFrameNum);
assert(i1>i0);
- for(i=i0+1; i<i1; ++i)
+ for(int i=i0+1; i<i1; ++i)
{
KeyFrames[i] = cvRound(KeyFrames[i0] + (float)(i-i0)*(float)(KeyFrames[i1] - KeyFrames[i0])/(float)(i1-i0));
}
{ /* Only one transform record: */
int i;
double val;
- CvFileNode* node = cvGetFileNodeByName( fs, pTN,name);
- if(node == NULL) continue;
- val = cvReadReal(node,defv);
+ CvFileNode* fnode = cvGetFileNodeByName( fs, pTN,name);
+ if(fnode == NULL) continue;
+ val = cvReadReal(fnode,defv);
for(i=0; i<p->TransNum; ++i)
{
double v0;
double v1;
- CvFileNode* pTN = (CvFileNode*)cvGetSeqElem(pTransSeq,0);
- v0 = cvReadRealByName(fs, pTN,name,defv);
+ CvFileNode* pTN1 = (CvFileNode*)cvGetSeqElem(pTransSeq,0);
+ v0 = cvReadRealByName(fs, pTN1,name,defv);
for(i1=1,i0=0; i1<KeyFrameNum; ++i1)
{
int f0,f1;
int i;
- CvFileNode* pTN = (CvFileNode*)cvGetSeqElem(pTransSeq,i1);
- CvFileNode* pVN = cvGetFileNodeByName(fs,pTN,name);
+ CvFileNode* pTN2 = (CvFileNode*)cvGetSeqElem(pTransSeq,i1);
+ CvFileNode* pVN = cvGetFileNodeByName(fs,pTN2,name);
if(pVN)v1 = cvReadReal(pVN,defv);
else if(pVN == NULL && i1 == KeyFrameNum-1) v1 = defv;
projMatrs[1] = projMatr2;
projMatrs[2] = projMatr3;
- int i;
- for( i = 0; i < 3; i++ )
+ for(int i = 0; i < 3; i++ )
{
if( projMatrs[i]->cols != 4 || projMatrs[i]->rows != 3 )
{
}
}
- for( i = 0; i < 3; i++ )
+ for(int i = 0; i < 3; i++ )
{
if( points[i]->rows != 2)
{
icvProject4DPoints(recPoints4D,&proj6[2],tmpProjPoints[2]);
/* Compute distances and number of good points (inliers) */
- int i;
int currImage;
numGoodPoints = 0;
- for( i = 0; i < numPoints; i++ )
+ for(int i = 0; i < numPoints; i++ )
{
double dist=-1;
dist = 0;
CvMat *optStatus;
optStatus = cvCreateMat(1,numPoints,CV_64F);
int testNumber = 0;
- for( i=0;i<numPoints;i++ )
+ for(int i=0;i<numPoints;i++ )
{
cvmSet(optStatus,0,i,(double)bestFlags[i]);
testNumber += bestFlags[i];
CvMat *gPresPoints;
gPresPoints = cvCreateMat(1,maxGoodPoints,CV_64F);
- for( i = 0; i < maxGoodPoints; i++)
+ for(int i = 0; i < maxGoodPoints; i++)
{
cvmSet(gPresPoints,0,i,1.0);
}
int currImage;
finalGoodPoints = 0;
- for( i = 0; i < numPoints; i++ )
+ for(int i = 0; i < numPoints; i++ )
{
double dist=-1;
/* Choose max distance for each of three points */
/* Create status */
CvMat *optStatus;
optStatus = cvCreateMat(1,numPoints,CV_64F);
- for( i=0;i<numPoints;i++ )
+ for(int i=0;i<numPoints;i++ )
{
cvmSet(optStatus,0,i,(double)bestFlags[i]);
}
int currImage;
finalGoodPoints = 0;
- for( i = 0; i < numPoints; i++ )
+ for(int i = 0; i < numPoints; i++ )
{
double dist=-1;
/* Choose max distance for each of three points */
matrA_dat[7] = s;
matrA_dat[8] = -(p+q+r+s+t);
- CvMat matrU;
CvMat matrW;
CvMat matrV;
- double matrU_dat[3*3];
double matrW_dat[3*3];
double matrV_dat[3*3];
- matrU = cvMat(3,3,CV_64F,matrU_dat);
matrW = cvMat(3,3,CV_64F,matrW_dat);
matrV = cvMat(3,3,CV_64F,matrV_dat);
matrK_dat[4*6+5] = -B2;
matrK_dat[5*6+5] = -C2;
- CvMat matrU;
- CvMat matrW;
- CvMat matrV;
+ CvMat matrW1;
+ CvMat matrV1;
- double matrU_dat[36];
- double matrW_dat[36];
- double matrV_dat[36];
+ double matrW_dat1[36];
+ double matrV_dat1[36];
- matrU = cvMat(6,6,CV_64F,matrU_dat);
- matrW = cvMat(6,6,CV_64F,matrW_dat);
- matrV = cvMat(6,6,CV_64F,matrV_dat);
+ matrW1 = cvMat(6,6,CV_64F,matrW_dat1);
+ matrV1 = cvMat(6,6,CV_64F,matrV_dat1);
/* From svd we need just last vector of V or last row V' */
/* We get transposed matrixes U and V */
- cvSVD(&matrK,&matrW,0,&matrV,CV_SVD_V_T);
+ cvSVD(&matrK,&matrW1,0,&matrV1,CV_SVD_V_T);
- a = matrV_dat[6*5+0];
- b = matrV_dat[6*5+1];
- c = matrV_dat[6*5+2];
- d = matrV_dat[6*5+3];
+ a = matrV_dat1[6*5+0];
+ b = matrV_dat1[6*5+1];
+ c = matrV_dat1[6*5+2];
+ d = matrV_dat1[6*5+3];
/* we don't need last two coefficients. Because it just a k1,k2 */
cvmSet(projMatrCoefs,0,0,a);
if (NULL != mstgContours)
cvReleaseMemStorage(&mstgContours);
};
- int Init(CvRect* pRects, IplImage* imgGray)
+ int Init(CvRect* pRects, IplImage* imgray)
{
for (int i = 0; i < NUM_FACE_ELEMENTS; i++)
{
ptTempl[i] = face[i].ptCenter;
rTempl[i] = face[i].r;
}
- imgGray = cvCreateImage(cvSize(imgGray->width, imgGray->height), 8, 1);
- imgThresh = cvCreateImage(cvSize(imgGray->width, imgGray->height), 8, 1);
+ imgray = cvCreateImage(cvSize(imgray->width, imgray->height), 8, 1);
+ imgThresh = cvCreateImage(cvSize(imgray->width, imgray->height), 8, 1);
mstgContours = cvCreateMemStorage();
- if ((NULL == imgGray) ||
+ if ((NULL == imgray) ||
(NULL == imgThresh) ||
(NULL == mstgContours))
return FALSE;
assert(fn.isSeq());
for( int i = 0; i < (int)fn.size(); i+=3 )
{
- string name = fn[i];
+ string nm = fn[i];
DatasetParams params;
string sf = fn[i+1]; params.dispScaleFactor = atoi(sf.c_str());
string uv = fn[i+2]; params.dispUnknVal = atoi(uv.c_str());
- datasetsParams[name] = params;
+ datasetsParams[nm] = params;
}
return cvtest::TS::OK;
}
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4514 4710 4711 4710 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
#include <stdarg.h>
#include <ctype.h>
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4514 ) /* unreferenced inline functions */
-#endif
-
#if 1
typedef float Qfloat;
#define QFLOAT_TYPE CV_32F
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4512 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
// Only accept the quantization if majority of pixels in the patch agree
static const int NEIGHBOR_THRESHOLD = 5;
if (max_votes >= NEIGHBOR_THRESHOLD)
- quantized_angle.at<uchar>(r, c) = 1 << index;
+ quantized_angle.at<uchar>(r, c) = uchar(1 << index);
}
}
}
}
#endif
for ( ; j < template_positions; ++j)
- dst_ptr[j] += lm_ptr[j];
+ dst_ptr[j] = uchar(dst_ptr[j] + lm_ptr[j]);
}
}
for (int row = 0; row < 16; ++row)
{
for (int col = 0; col < 16; ++col)
- dst_ptr[col] += lm_ptr[col];
+ dst_ptr[col] = uchar(dst_ptr[col] + lm_ptr[col]);
dst_ptr += 16;
lm_ptr += W;
}
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4512 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
}
#define cvReleaseIplConvKernel(x) cvReleaseStructuringElement(x)
+
+#if defined _MSC_VER && _MSC_VER >= 1200
+ #pragma warning( push )
+ #pragma warning( disable : 4244 )
+#endif
+
#include "generated3.i"
+#if defined _MSC_VER && _MSC_VER >= 1200
+ #pragma warning( pop )
+#endif
+
/* iplimage */
static void iplimage_dealloc(PyObject *self)
bps = CV_MAT_CN(m->type) * 8;
break;
default:
- return failmsg("Unrecognised depth %d", CV_MAT_DEPTH(m->type)), (PyObject*)0;
+ failmsg("Unrecognized depth %d", CV_MAT_DEPTH(m->type));
+ return (PyObject*)0;
}
int bpl = m->cols * bps; // bytes per line
#define CVPY_VALIDATE_DrawChessboardCorners() do { \
if ((patternSize.width * patternSize.height) != corners.count) \
- return (PyObject*)failmsg("Size is %dx%d, but corner list is length %d", patternSize.width, patternSize.height, corners.count); \
+ return (PyObject*)0; \
} while (0)
#define cvGetRotationMatrix2D cv2DRotationMatrix
#define cvKMeans2(samples, nclusters, labels, termcrit, attempts, flags, centers) \
cppKMeans(samples, nclusters, labels, termcrit, attempts, flags, centers)
+#if defined _MSC_VER && _MSC_VER >= 1200
+ #pragma warning( push )
+ #pragma warning( disable : 4244 )
+#endif
+
#include "generated0.i"
+#if defined _MSC_VER && _MSC_VER >= 1200
+ #pragma warning( pop )
+#endif
+
static PyMethodDef old_methods[] = {
#if PYTHON_USE_NUMPY
endif()
set(OPENCV_MODULE_IS_PART_OF_WORLD FALSE)
-
+
ocv_add_module(ts opencv_core)
ocv_glob_module_sources()
ocv_module_include_directories()
if(BUILD_SHARED_LIBS AND NOT MINGW)
add_definitions(-DGTEST_CREATE_SHARED_LIBRARY=1)
- if (MSVC AND NOT ENABLE_NOISY_WARNINGS)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4275")
- endif()
else()
add_definitions(-DGTEST_CREATE_SHARED_LIBRARY=0)
endif()
#include <stdarg.h> // for va_list
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4275 4355 4127 )
+#ifdef _MSC_VER
+#pragma warning( disable: 4127 )
#endif
#define GTEST_DONT_DEFINE_FAIL 0
};
// This interface knows how to report a test part result.
-class TestPartResultReporterInterface {
+class GTEST_API_ TestPartResultReporterInterface {
public:
virtual ~TestPartResultReporterInterface() {}
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4127 4251)
-#endif
-
#include "opencv2/core/core_c.h"
#include "opencv2/ts/ts.hpp"
// This line ensures that gtest.h can be compiled on its own, even
// when it's fused.
-#include "opencv2/ts/ts.hpp"
+#include "precomp.hpp"
+
+#ifdef __GNUC__
+# pragma GCC diagnostic ignored "-Wmissing-declarations"
+#endif
// The following lines pull in the real gtest *.cc files.
// Copyright 2005, Google Inc.
return (int64)compensation;\r
}\r
\r
+#ifdef _MSC_VER\r
+# pragma warning(push)\r
+# pragma warning(disable:4355) // 'this' : used in base member initializer list\r
+#endif\r
TestBase::TestBase(): declare(this)\r
{\r
}\r
+#ifdef _MSC_VER\r
+# pragma warning(pop)\r
+#endif\r
+\r
\r
void TestBase::declareArray(SizeVector& sizes, cv::InputOutputArray a, int wtype)\r
{\r
}
//set the number of modes
- modesUsed[x] = nmodes;
+ modesUsed[x] = uchar(nmodes);
mask[x] = background ? 0 :
detectShadows && detectShadowGMM(data, nchannels, nmodes, gmm, mean, Tb, TB, tau) ?
shadowVal : 255;
bgmodelUsedModes.data, nmixtures, (float)learningRate,
(float)varThreshold,
backgroundRatio, varThresholdGen,
- fVarInit, fVarMin, fVarMax, -learningRate*fCT, fTau,
+ fVarInit, fVarMin, fVarMax, float(-learningRate*fCT), fTau,
bShadowDetection, nShadowDetection));
}
}
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
-#if defined _MSC_VER && _MSC_VER >= 1200
-#pragma warning( disable: 4251 4710 4711 4514 4996 )
-#endif
-
#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif
// perform outlier rejection
- IOutlierRejector *outlierRejector = static_cast<IOutlierRejector*>(outlierRejector_);
- if (!dynamic_cast<NullOutlierRejector*>(outlierRejector))
+ IOutlierRejector *rejector = static_cast<IOutlierRejector*>(outlierRejector_);
+ if (!dynamic_cast<NullOutlierRejector*>(rejector))
{
outlierRejector_->process(frame0.size(), hostPointsPrev_, hostPoints_, rejectionStatus_);
}
}
- hostPointsPrev_ = Mat(1, hostPointsPrevTmp_.size(), CV_32FC2, &hostPointsPrevTmp_[0]);
- hostPoints_ = Mat(1, hostPointsTmp_.size(), CV_32FC2, &hostPointsTmp_[0]);
+ hostPointsPrev_ = Mat(1, (int)hostPointsPrevTmp_.size(), CV_32FC2, &hostPointsPrevTmp_[0]);
+ hostPoints_ = Mat(1, (int)hostPointsTmp_.size(), CV_32FC2, &hostPointsTmp_[0]);
}
// estimate motion
{
void NullOutlierRejector::process(
- Size frameSize, InputArray points0, InputArray points1, OutputArray mask)
+ Size /*frameSize*/, InputArray points0, InputArray points1, OutputArray mask)
{
CV_Assert(points0.type() == points1.type());
CV_Assert(points0.getMat().checkVector(2) == points1.getMat().checkVector(2));
yl = ML(1,0)*x + ML(1,1)*y + ML(1,2);
zl = ML(2,0)*x + ML(2,1)*y + ML(2,2);
xl /= zl; yl /= zl;
- wl = idx - k1;
+ wl = float(idx - k1);
xr = MR(0,0)*x + MR(0,1)*y + MR(0,2);
yr = MR(1,0)*x + MR(1,1)*y + MR(1,2);
zr = MR(2,0)*x + MR(2,1)*y + MR(2,2);
xr /= zr; yr /= zr;
- wr = k2 - idx;
+ wr = float(k2 - idx);
mapx_(y,x) = (wr * xl + wl * xr) / (wl + wr);
mapy_(y,x) = (wr * yl + wl * yr) / (wl + wr);
// define whether to use approximate nearest-neighbor search
#define USE_FLANN
-
-IplImage* image = 0;
-
#ifdef USE_FLANN
static void
flannFindPairs( const CvSeq*, const CvSeq* objectDescriptors,
const CvSeq*, const CvSeq* imageDescriptors, vector<int>& ptpairs )
{
- int length = (int)(objectDescriptors->elem_size/sizeof(float));
+ int length = (int)(objectDescriptors->elem_size/sizeof(float));
cv::Mat m_object(objectDescriptors->total, length, CV_32F);
- cv::Mat m_image(imageDescriptors->total, length, CV_32F);
+ cv::Mat m_image(imageDescriptors->total, length, CV_32F);
- // copy descriptors
+ // copy descriptors
CvSeqReader obj_reader;
- float* obj_ptr = m_object.ptr<float>(0);
+ float* obj_ptr = m_object.ptr<float>(0);
cvStartReadSeq( objectDescriptors, &obj_reader );
for(int i = 0; i < objectDescriptors->total; i++ )
{
obj_ptr += length;
}
CvSeqReader img_reader;
- float* img_ptr = m_image.ptr<float>(0);
+ float* img_ptr = m_image.ptr<float>(0);
cvStartReadSeq( imageDescriptors, &img_reader );
for(int i = 0; i < imageDescriptors->total; i++ )
{
int* indices_ptr = m_indices.ptr<int>(0);
float* dists_ptr = m_dists.ptr<float>(0);
for (int i=0;i<m_indices.rows;++i) {
- if (dists_ptr[2*i]<0.6*dists_ptr[2*i+1]) {
- ptpairs.push_back(i);
- ptpairs.push_back(indices_ptr[2*i]);
- }
+ if (dists_ptr[2*i]<0.6*dists_ptr[2*i+1]) {
+ ptpairs.push_back(i);
+ ptpairs.push_back(indices_ptr[2*i]);
+ }
}
}
#else
cvNamedWindow("Object", 1);
cvNamedWindow("Object Correspond", 1);
- static CvScalar colors[] =
+ static CvScalar colors[] =
{
{{0,0,255}},
{{0,128,255}},
};
-static void print_variable_importance( CvDTree* dtree, const char** var_desc )
+static void print_variable_importance( CvDTree* dtree )
{
const CvMat* var_importance = dtree->get_var_importance();
int i;
for( i = 0; i < var_importance->cols*var_importance->rows; i++ )
{
double val = var_importance->data.db[i];
- if( var_desc )
- {
- char buf[100];
- int len = (int)(strchr( var_desc[i], '(' ) - var_desc[i] - 1);
- strncpy( buf, var_desc[i], len );
- buf[len] = '\0';
- printf( "%s", buf );
- }
- else
- printf( "var #%d", i );
+ char buf[100];
+ int len = (int)(strchr( var_desc[i], '(' ) - var_desc[i] - 1);
+ strncpy( buf, var_desc[i], len );
+ buf[len] = '\0';
+ printf( "%s", buf );
printf( ": %g%%\n", val*100. );
}
}
-static void interactive_classification( CvDTree* dtree, const char** var_desc )
+static void interactive_classification( CvDTree* dtree )
{
char input[1000];
const CvDTreeNode* root;
cvReleaseMat( &missing );
cvReleaseMat( &responses );
- print_variable_importance( dtree, var_desc );
- interactive_classification( dtree, var_desc );
+ print_variable_importance( dtree );
+ interactive_classification( dtree );
delete dtree;
return 0;
// TODO : take care of this step !!! maybe disable of do this in a nicer way ... each successive image should get the same transformation... but it depends on the initial image format
double maxInput, minInput;
minMaxLoc(inputImage, &minInput, &maxInput);
- std::cout<<"ORIGINAL IMAGE pixels values range (max,min) : "<<maxInput<<", "<<minInput<<std::endl
-;if (firstTimeread)
+ std::cout<<"ORIGINAL IMAGE pixels values range (max,min) : "<<maxInput<<", "<<minInput<<std::endl;
+
+ if (firstTimeread)
{
/* the first time, get the pixel values range and rougthly update scaling value
in order to center values around 128 and getting a range close to [0-255],
=> actually using a little less in order to let some more flexibility in range evolves...
*/
- double maxInput, minInput;
- minMaxLoc(inputImage, &minInput, &maxInput);
- std::cout<<"FIRST IMAGE pixels values range (max,min) : "<<maxInput<<", "<<minInput<<std::endl;
- globalRescalefactor=(float)(50.0/(maxInput-minInput)); // less than 255 for flexibility... experimental value to be carefull about
+ double maxInput1, minInput1;
+ minMaxLoc(inputImage, &minInput1, &maxInput1);
+ std::cout<<"FIRST IMAGE pixels values range (max,min) : "<<maxInput1<<", "<<minInput1<<std::endl;
+ globalRescalefactor=(float)(50.0/(maxInput1-minInput1)); // less than 255 for flexibility... experimental value to be carefull about
double channelOffset = -1.5*minInput;
globalOffset= cv::Scalar(channelOffset, channelOffset, channelOffset, channelOffset);
}
std::sort(order.begin(),order.end(),orderingSorter());
/* 2. save ranking results to text file */
- string input_file_std = checkFilenamePathsep(input_file);
- size_t fnamestart = input_file_std.rfind("/");
- string scoregt_file_str = input_file_std.substr(0,fnamestart+1) + "scoregt_" + class_name + ".txt";
+ string input_file_std1 = checkFilenamePathsep(input_file);
+ size_t fnamestart = input_file_std1.rfind("/");
+ string scoregt_file_str = input_file_std1.substr(0,fnamestart+1) + "scoregt_" + class_name + ".txt";
std::ofstream scoregt_file(scoregt_file_str.c_str());
if (scoregt_file.is_open())
{
{
if( i1 == i )
continue;
- Point2f p1 = keypoints1[i1].pt;
+ Point2f pt1 = keypoints1[i1].pt;
const float* d11 = descriptors1.ptr<float>(i1);
double dist = 0;
- e = p2.x*(F[0]*p1.x + F[1]*p1.y + F[2]) +
- p2.y*(F[3]*p1.x + F[4]*p1.y + F[5]) +
- F[6]*p1.x + F[7]*p1.y + F[8];
+ e = p2.x*(F[0]*pt1.x + F[1]*pt1.y + F[2]) +
+ p2.y*(F[3]*pt1.x + F[4]*pt1.y + F[5]) +
+ F[6]*pt1.x + F[7]*pt1.y + F[8];
if( fabs(e) > eps )
continue;
{
FileStorage fs( filename, FileStorage::WRITE );
- time_t t;
- time( &t );
- struct tm *t2 = localtime( &t );
+ time_t tt;
+ time( &tt );
+ struct tm *t2 = localtime( &tt );
char buf[1024];
strftime( buf, sizeof(buf)-1, "%c", t2 );
static void help()
{
cout << "\nThis is a demo that shows mean-shift based tracking\n"
- "You select a color objects such as your face and it tracks it.\n"
- "This reads from video camera (0 by default, or the camera number the user enters\n"
- "Usage: \n"
- " ./camshiftdemo [camera number]\n";
+ "You select a color objects such as your face and it tracks it.\n"
+ "This reads from video camera (0 by default, or the camera number the user enters\n"
+ "Usage: \n"
+ " ./camshiftdemo [camera number]\n";
cout << "\n\nHot keys: \n"
- "\tESC - quit the program\n"
- "\tc - stop the tracking\n"
- "\tb - switch to/from backprojection view\n"
- "\th - show/hide object histogram\n"
- "\tp - pause video\n"
+ "\tESC - quit the program\n"
+ "\tc - stop the tracking\n"
+ "\tb - switch to/from backprojection view\n"
+ "\th - show/hide object histogram\n"
+ "\tp - pause video\n"
"To initialize tracking, select the object with mouse\n";
}
-const char* keys =
+const char* keys =
{
- "{1| | 0 | camera number}"
+ "{1| | 0 | camera number}"
};
int main( int argc, const char** argv )
{
- help();
+ help();
VideoCapture cap;
Rect trackWindow;
- RotatedRect trackBox;
int hsize = 16;
float hranges[] = {0,180};
const float* phranges = hranges;
- CommandLineParser parser(argc, argv, keys);
- int camNum = parser.get<int>("1");
-
- cap.open(camNum);
+ CommandLineParser parser(argc, argv, keys);
+ int camNum = parser.get<int>("1");
+
+ cap.open(camNum);
if( !cap.isOpened() )
{
- help();
+ help();
cout << "***Could not initialize capturing...***\n";
cout << "Current parameter's value: \n";
- parser.printParams();
+ parser.printParams();
return -1;
}
Mat frame, hsv, hue, mask, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj;
bool paused = false;
-
+
for(;;)
{
if( !paused )
}
frame.copyTo(image);
-
+
if( !paused )
{
cvtColor(image, hsv, CV_BGR2HSV);
Mat roi(hue, selection), maskroi(mask, selection);
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
normalize(hist, hist, 0, 255, CV_MINMAX);
-
+
trackWindow = selection;
trackObject = 1;
for( int i = 0; i < hsize; i++ )
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255);
cvtColor(buf, buf, CV_HSV2BGR);
-
+
for( int i = 0; i < hsize; i++ )
{
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255);
int main(int,char**)
{
help();
- Mat i = Mat::eye(4, 4, CV_64F);
- i.at<double>(1,1) = CV_PI;
- cout << "i = " << i << ";" << endl;
+ Mat I = Mat::eye(4, 4, CV_64F);
+ I.at<double>(1,1) = CV_PI;
+ cout << "I = " << I << ";" << endl;
Mat r = Mat(10, 3, CV_8UC3);
randu(r, Scalar::all(0), Scalar::all(255));
isWriteParams = false;
FileNode topfn = fs.getFirstTopLevelNode();
- FileNode fn = topfn[DEFAULT_PARAMS];
- readDefaultRunParams(fn);
+ FileNode pfn = topfn[DEFAULT_PARAMS];
+ readDefaultRunParams(pfn);
for( int i = 0; i < DATASETS_COUNT; i++ )
{
if( !fs.isOpened() )
{
cout << "filename " << dirname + filename.str() << endl;
- FileStorage fs( dirname + filename.str(), FileStorage::READ );
+ FileStorage fs2( dirname + filename.str(), FileStorage::READ );
return false;
}
fs.getFirstTopLevelNode() >> Hs[i];
int trackObject = 0;
int live = 1;
-static void drawRectangle(Mat* image, Rect win) {
- rectangle(*image, Point(win.x, win.y), Point(win.x + win.width, win.y
+static void drawRectangle(Mat* img, Rect win) {
+ rectangle(*img, Point(win.x, win.y), Point(win.x + win.width, win.y
+ win.height), Scalar(0, 255, 0), 2, CV_AA);
}
"To add/remove a feature point click it\n" << endl;
}
-Point2f pt;
+Point2f point;
bool addRemovePt = false;
static void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
{
if( event == CV_EVENT_LBUTTONDOWN )
{
- pt = Point2f((float)x,(float)y);
+ point = Point2f((float)x,(float)y);
addRemovePt = true;
}
}
{
if( addRemovePt )
{
- if( norm(pt - points[1][i]) <= 5 )
+ if( norm(point - points[1][i]) <= 5 )
{
addRemovePt = false;
continue;
if( addRemovePt && points[1].size() < (size_t)MAX_COUNT )
{
vector<Point2f> tmp;
- tmp.push_back(pt);
+ tmp.push_back(point);
cornerSubPix( gray, tmp, winSize, cvSize(-1,-1), termcrit);
points[1].push_back(tmp[0]);
addRemovePt = false;
int val = atoi(mask.c_str());
int l = 100000, r = 10000, sum = 0;
- for( int i = 0; i < 5; i++ )
+ for( int j = 0; j < 5; j++ )
{
- retrievedImageFlags[i] = ((val % l) / r ) == 0 ? false : true;
+ retrievedImageFlags[j] = ((val % l) / r ) == 0 ? false : true;
l /= 10; r /= 10;
- if( retrievedImageFlags[i] ) sum++;
+ if( retrievedImageFlags[j] ) sum++;
}
if( sum == 0 )
double seam_megapix = 0.1;
double compose_megapix = -1;
float conf_thresh = 1.f;
-string features = "surf";
+string features_type = "surf";
string ba_cost_func = "ray";
string ba_refine_mask = "xxxxx";
bool do_wave_correct = true;
}
else if (string(argv[i]) == "--features")
{
- features = argv[i + 1];
- if (features == "orb")
+ features_type = argv[i + 1];
+ if (features_type == "orb")
match_conf = 0.3f;
i++;
}
int64 t = getTickCount();
Ptr<FeaturesFinder> finder;
- if (features == "surf")
+ if (features_type == "surf")
{
#ifdef HAVE_OPENCV_GPU
if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
#endif
finder = new SurfFeaturesFinder();
}
- else if (features == "orb")
+ else if (features_type == "orb")
{
finder = new OrbFeaturesFinder();
}
else
{
- cout << "Unknown 2D features type: '" << features << "'.\n";
+ cout << "Unknown 2D features type: '" << features_type << "'.\n";
return -1;
}
virtual ~IMotionEstimatorBuilder() {}
virtual Ptr<ImageMotionEstimatorBase> build() = 0;
protected:
- IMotionEstimatorBuilder(CommandLineParser &cmd) : cmd(cmd) {}
+ IMotionEstimatorBuilder(CommandLineParser &command) : cmd(command) {}
CommandLineParser cmd;
};
class MotionEstimatorRansacL2Builder : public IMotionEstimatorBuilder
{
public:
- MotionEstimatorRansacL2Builder(CommandLineParser &cmd, bool gpu, const string &prefix = "")
- : IMotionEstimatorBuilder(cmd), gpu(gpu), prefix(prefix) {}
+ MotionEstimatorRansacL2Builder(CommandLineParser &command, bool use_gpu, const string &_prefix = "")
+ : IMotionEstimatorBuilder(command), gpu(use_gpu), prefix(_prefix) {}
virtual Ptr<ImageMotionEstimatorBase> build()
{
if (arg(prefix + "subset") != "auto")
ransac.size = argi(prefix + "subset");
if (arg(prefix + "thresh") != "auto")
- ransac.thresh = argi(prefix + "thresh");
+ ransac.thresh = argf(prefix + "thresh");
ransac.eps = argf(prefix + "outlier-ratio");
est->setRansacParams(ransac);
class MotionEstimatorL1Builder : public IMotionEstimatorBuilder
{
public:
- MotionEstimatorL1Builder(CommandLineParser &cmd, bool gpu, const string &prefix = "")
- : IMotionEstimatorBuilder(cmd), gpu(gpu), prefix(prefix) {}
+ MotionEstimatorL1Builder(CommandLineParser &command, bool use_gpu, const string &_prefix = "")
+ : IMotionEstimatorBuilder(command), gpu(use_gpu), prefix(_prefix) {}
virtual Ptr<ImageMotionEstimatorBase> build()
{
for( i = 0; i < markers.rows; i++ )
for( j = 0; j < markers.cols; j++ )
{
- int idx = markers.at<int>(i,j);
- if( idx == -1 )
+ int index = markers.at<int>(i,j);
+ if( index == -1 )
wshed.at<Vec3b>(i,j) = Vec3b(255,255,255);
- else if( idx <= 0 || idx > compCount )
+ else if( index <= 0 || index > compCount )
wshed.at<Vec3b>(i,j) = Vec3b(0,0,0);
else
- wshed.at<Vec3b>(i,j) = colorTab[idx - 1];
+ wshed.at<Vec3b>(i,j) = colorTab[index - 1];
}
wshed = wshed*0.5 + imgGray*0.5;
GpuMat d_fu, d_fv;\r
\r
d_flow(d_frame0, d_frame1, d_fu, d_fv);\r
- \r
+\r
Mat flowFieldForward;\r
getFlowField(Mat(d_fu), Mat(d_fv), flowFieldForward);\r
- \r
+\r
cout << "\tBackward..." << endl;\r
\r
GpuMat d_bu, d_bv;\r
\r
d_flow(d_frame1, d_frame0, d_bu, d_bv);\r
- \r
+\r
Mat flowFieldBackward;\r
getFlowField(Mat(d_bu), Mat(d_bv), flowFieldBackward);\r
\r
#ifdef HAVE_OPENGL\r
cout << "Create Optical Flow Needle Map..." << endl;\r
- \r
+\r
GpuMat d_vertex, d_colors;\r
\r
createOpticalFlowNeedleMap(d_fu, d_fv, d_vertex, d_colors);\r
d_bt.upload(channels[0]);\r
d_gt.upload(channels[1]);\r
d_rt.upload(channels[2]);\r
- \r
+\r
// temporary buffer\r
GpuMat d_buf;\r
\r
// interpolate red channel\r
interpolateFrames(d_r, d_rt, d_fu, d_fv, d_bu, d_bv, timePos, d_rNew, d_buf);\r
\r
- GpuMat channels[] = {d_bNew, d_gNew, d_rNew};\r
- merge(channels, 3, d_newFrame);\r
+ GpuMat channels3[] = {d_bNew, d_gNew, d_rNew};\r
+ merge(channels3, 3, d_newFrame);\r
\r
frames.push_back(Mat(d_newFrame));\r
\r
return 0;\r
\r
case 'A':\r
- if (currentFrame > 0) \r
+ if (currentFrame > 0)\r
--currentFrame;\r
\r
imshow("Interpolated frame", frames[currentFrame]);\r
{\r
float d = max(fabsf(ptr_u[j]), fabsf(ptr_v[j]));\r
\r
- if (d > maxDisplacement) \r
+ if (d > maxDisplacement)\r
maxDisplacement = d;\r
}\r
}\r
class Runnable\r
{\r
public:\r
- explicit Runnable(const std::string& name): name_(name) {} \r
+ explicit Runnable(const std::string& nameStr): name_(nameStr) {}\r
virtual ~Runnable() {}\r
- \r
- const std::string& name() const { return name_; } \r
- \r
+\r
+ const std::string& name() const { return name_; }\r
+\r
virtual void run() = 0;\r
\r
private:\r
bool stop() const { return cur_iter_idx_ >= num_iters_; }\r
\r
void cpuOn() { cpu_started_ = cv::getTickCount(); }\r
- void cpuOff() \r
+ void cpuOff()\r
{\r
int64 delta = cv::getTickCount() - cpu_started_;\r
cpu_times_.push_back(delta);\r
}\r
\r
void gpuOn() { gpu_started_ = cv::getTickCount(); }\r
- void gpuOff() \r
+ void gpuOff()\r
{\r
int64 delta = cv::getTickCount() - gpu_started_;\r
gpu_times_.push_back(delta);\r
{\r
cpu_times_.reserve(num_iters_);\r
gpu_times_.reserve(num_iters_);\r
- } \r
+ }\r
\r
void finishCurrentSubtest();\r
- void resetCurrentSubtest() \r
+ void resetCurrentSubtest()\r
{\r
cpu_elapsed_ = 0;\r
gpu_elapsed_ = 0;\r
} TestSystem::instance().gpuComplete()\r
\r
// Generates a matrix\r
-void gen(cv::Mat& mat, int rows, int cols, int type, cv::Scalar low, \r
+void gen(cv::Mat& mat, int rows, int cols, int type, cv::Scalar low,\r
cv::Scalar high);\r
\r
// Returns abs path taking into account test system working dir\r
GlArrays arr;\r
};\r
\r
-void drawCallback(void* userdata)\r
+static void drawCallback(void* userdata)\r
{\r
DrawData* data = static_cast<DrawData*>(userdata);\r
\r
}\r
\r
\r
-App::App(const Params& p)\r
- : p(p), running(false)\r
+App::App(const Params& params)\r
+ : p(params), running(false)\r
{\r
cv::gpu::printShortCudaDeviceInfo(cv::gpu::getDevice());\r
\r