1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-30 15:53:03 +04:00

merged all the latest changes from 2.4 to trunk

This commit is contained in:
Vadim Pisarevsky
2012-04-13 21:50:59 +00:00
parent 020f9a6047
commit 2fd1e2ea57
416 changed files with 12852 additions and 6070 deletions
@@ -86,6 +86,11 @@ protected:
int emptyCameraCallbackReported;
static const char* flashModesNames[ANDROID_CAMERA_FLASH_MODES_NUM];
static const char* focusModesNames[ANDROID_CAMERA_FOCUS_MODES_NUM];
static const char* whiteBalanceModesNames[ANDROID_CAMERA_WHITE_BALANCE_MODES_NUM];
static const char* antibandingModesNames[ANDROID_CAMERA_ANTIBANDING_MODES_NUM];
void doCall(void* buffer, size_t bufferSize)
{
if (cameraCallback == 0)
@@ -156,6 +161,68 @@ protected:
camera->releaseRecordingFrame(dataPtr);
}
// Split list of floats, returns number of floats found
static int split_float(const char *str, float* out, char delim, int max_elem_num,
char **endptr = NULL)
{
// Find the first float.
char *end = const_cast<char*>(str);
int elem_num = 0;
for(; elem_num < max_elem_num; elem_num++ ){
char* curr_end;
out[elem_num] = (float)strtof(end, &curr_end);
// No other numbers found, finish the loop
if(end == curr_end){
break;
}
if (*curr_end != delim) {
// When end of string, finish the loop
if (*curr_end == 0){
elem_num++;
break;
}
else {
LOGE("Cannot find delimeter (%c) in str=%s", delim, str);
return -1;
}
}
// Skip the delimiter character
end = curr_end + 1;
}
if (endptr)
*endptr = end;
return elem_num;
}
int is_supported(const char* supp_modes_key, const char* mode)
{
const char* supported_modes = params.get(supp_modes_key);
return strstr(supported_modes, mode) > 0;
}
float getFocusDistance(int focus_distance_type){
if (focus_distance_type >= 0 && focus_distance_type < 3) {
float focus_distances[3];
const char* output = params.get(CameraParameters::KEY_FOCUS_DISTANCES);
int val_num = CameraHandler::split_float(output, focus_distances, ',', 3);
if(val_num == 3){
return focus_distances[focus_distance_type];
} else {
LOGE("Invalid focus distances.");
}
}
return -1;
}
static int getModeNum(const char** modes, const int modes_num, const char* mode_name)
{
for (int i = 0; i < modes_num; i++){
if(!strcmp(modes[i],mode_name))
return i;
}
return -1;
}
public:
CameraHandler(CameraCallback callback = 0, void* _userData = 0):
cameraId(0),
@@ -220,6 +287,42 @@ public:
std::string cameraPropertyPreviewFormatString;
};
const char* CameraHandler::flashModesNames[ANDROID_CAMERA_FLASH_MODES_NUM] =
{
CameraParameters::FLASH_MODE_AUTO,
CameraParameters::FLASH_MODE_OFF,
CameraParameters::FLASH_MODE_ON,
CameraParameters::FLASH_MODE_RED_EYE,
CameraParameters::FLASH_MODE_TORCH
};
const char* CameraHandler::focusModesNames[ANDROID_CAMERA_FOCUS_MODES_NUM] =
{
CameraParameters::FOCUS_MODE_AUTO,
CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO,
CameraParameters::FOCUS_MODE_EDOF,
CameraParameters::FOCUS_MODE_FIXED,
CameraParameters::FOCUS_MODE_INFINITY
};
const char* CameraHandler::whiteBalanceModesNames[ANDROID_CAMERA_WHITE_BALANCE_MODES_NUM] =
{
CameraParameters::WHITE_BALANCE_AUTO,
CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT,
CameraParameters::WHITE_BALANCE_DAYLIGHT,
CameraParameters::WHITE_BALANCE_FLUORESCENT,
CameraParameters::WHITE_BALANCE_INCANDESCENT,
CameraParameters::WHITE_BALANCE_SHADE,
CameraParameters::WHITE_BALANCE_TWILIGHT
};
const char* CameraHandler::antibandingModesNames[ANDROID_CAMERA_ANTIBANDING_MODES_NUM] =
{
CameraParameters::ANTIBANDING_50HZ,
CameraParameters::ANTIBANDING_60HZ,
CameraParameters::ANTIBANDING_AUTO
};
CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, int cameraId, void* userData, CameraParameters* prevCameraParameters)
{
@@ -229,7 +332,7 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback,
#ifdef ANDROID_r2_2_0
camera = Camera::connect();
#else
#else
/* This is 2.3 or higher. The connect method has cameraID parameter */
camera = Camera::connect(cameraId);
#endif
@@ -273,6 +376,28 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback,
LOGD("Supported Antibanding Options: %s", handler->params.get(CameraParameters::KEY_SUPPORTED_ANTIBANDING));
LOGD("Supported Flash Modes: %s", handler->params.get(CameraParameters::KEY_SUPPORTED_FLASH_MODES));
#if !defined(ANDROID_r2_2_0)
// Set focus mode to continuous-video if supported
const char* available_focus_modes = handler->params.get(CameraParameters::KEY_SUPPORTED_FOCUS_MODES);
if (available_focus_modes != 0)
{
if (strstr(available_focus_modes, "continuous-video") != NULL)
{
handler->params.set(CameraParameters::KEY_FOCUS_MODE, CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO);
status_t resParams = handler->camera->setParameters(handler->params.flatten());
if (resParams != 0)
{
LOGE("initCameraConnect: failed to set autofocus mode to \"continuous-video\"");
}
else
{
LOGD("initCameraConnect: autofocus is set to mode \"continuous-video\"");
}
}
}
#endif
//check if yuv420sp format available. Set this format as preview format.
const char* available_formats = handler->params.get(CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS);
@@ -312,17 +437,6 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback,
}
}
}
#if !defined(ANDROID_r2_2_0)
const char* available_focus_modes = handler->params.get(CameraParameters::KEY_SUPPORTED_FOCUS_MODES);
if (available_focus_modes != 0)
{
// find continuous focus mode
if (strstr(available_focus_modes, "continuous-picture") != NULL)
{
handler->params.set(CameraParameters::KEY_FOCUS_MODE, CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO);
}
}
#endif
status_t pdstatus;
#if defined(ANDROID_r2_2_0)
@@ -424,7 +538,6 @@ double CameraHandler::getProperty(int propIdx)
u.str = cameraPropertySupportedPreviewSizesString.c_str();
return u.res;
}
case ANDROID_CAMERA_PROPERTY_PREVIEW_FORMAT_STRING:
{
const char* fmt = params.get(CameraParameters::KEY_PREVIEW_FORMAT);
@@ -445,7 +558,62 @@ double CameraHandler::getProperty(int propIdx)
u.str = cameraPropertyPreviewFormatString.c_str();
return u.res;
}
case ANDROID_CAMERA_PROPERTY_EXPOSURE:
{
int exposure = params.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION);
return exposure;
}
case ANDROID_CAMERA_PROPERTY_FPS:
{
return params.getPreviewFrameRate();
}
case ANDROID_CAMERA_PROPERTY_FLASH_MODE:
{
int flash_mode = getModeNum(CameraHandler::flashModesNames,
ANDROID_CAMERA_FLASH_MODES_NUM,
params.get(CameraParameters::KEY_FLASH_MODE));
return flash_mode;
}
case ANDROID_CAMERA_PROPERTY_FOCUS_MODE:
{
int focus_mode = getModeNum(CameraHandler::focusModesNames,
ANDROID_CAMERA_FOCUS_MODES_NUM,
params.get(CameraParameters::KEY_FOCUS_MODE));
return focus_mode;
}
case ANDROID_CAMERA_PROPERTY_WHITE_BALANCE:
{
int white_balance = getModeNum(CameraHandler::whiteBalanceModesNames,
ANDROID_CAMERA_WHITE_BALANCE_MODES_NUM,
params.get(CameraParameters::KEY_WHITE_BALANCE));
return white_balance;
}
case ANDROID_CAMERA_PROPERTY_ANTIBANDING:
{
int antibanding = getModeNum(CameraHandler::antibandingModesNames,
ANDROID_CAMERA_ANTIBANDING_MODES_NUM,
params.get(CameraParameters::KEY_ANTIBANDING));
return antibanding;
}
case ANDROID_CAMERA_PROPERTY_FOCAL_LENGTH:
{
float focal_length = params.getFloat(CameraParameters::KEY_FOCAL_LENGTH);
return focal_length;
}
case ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_NEAR:
{
return getFocusDistance(ANDROID_CAMERA_FOCUS_DISTANCE_NEAR_INDEX);
}
case ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_OPTIMAL:
{
return getFocusDistance(ANDROID_CAMERA_FOCUS_DISTANCE_OPTIMAL_INDEX);
}
case ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_FAR:
{
return getFocusDistance(ANDROID_CAMERA_FOCUS_DISTANCE_FAR_INDEX);
}
default:
LOGW("CameraHandler::getProperty - Unsupported property.");
};
return -1;
}
@@ -472,6 +640,80 @@ void CameraHandler::setProperty(int propIdx, double value)
params.setPreviewSize(w, h);
}
break;
case ANDROID_CAMERA_PROPERTY_EXPOSURE:
{
int max_exposure = params.getInt("max-exposure-compensation");
int min_exposure = params.getInt("min-exposure-compensation");
if(max_exposure && min_exposure){
int exposure = (int)value;
if(exposure >= min_exposure && exposure <= max_exposure){
params.set("exposure-compensation", exposure);
} else {
LOGE("Exposure compensation not in valid range (%i,%i).", min_exposure, max_exposure);
}
} else {
LOGE("Exposure compensation adjust is not supported.");
}
}
break;
case ANDROID_CAMERA_PROPERTY_FLASH_MODE:
{
int new_val = (int)value;
if(new_val >= 0 && new_val < ANDROID_CAMERA_FLASH_MODES_NUM){
const char* mode_name = flashModesNames[new_val];
if(is_supported(CameraParameters::KEY_SUPPORTED_FLASH_MODES, mode_name))
params.set(CameraParameters::KEY_FLASH_MODE, mode_name);
else
LOGE("Flash mode %s is not supported.", mode_name);
} else {
LOGE("Flash mode value not in valid range.");
}
}
break;
case ANDROID_CAMERA_PROPERTY_FOCUS_MODE:
{
int new_val = (int)value;
if(new_val >= 0 && new_val < ANDROID_CAMERA_FOCUS_MODES_NUM){
const char* mode_name = focusModesNames[new_val];
if(is_supported(CameraParameters::KEY_SUPPORTED_FOCUS_MODES, mode_name))
params.set(CameraParameters::KEY_FOCUS_MODE, mode_name);
else
LOGE("Focus mode %s is not supported.", mode_name);
} else {
LOGE("Focus mode value not in valid range.");
}
}
break;
case ANDROID_CAMERA_PROPERTY_WHITE_BALANCE:
{
int new_val = (int)value;
if(new_val >= 0 && new_val < ANDROID_CAMERA_WHITE_BALANCE_MODES_NUM){
const char* mode_name = whiteBalanceModesNames[new_val];
if(is_supported(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE, mode_name))
params.set(CameraParameters::KEY_WHITE_BALANCE, mode_name);
else
LOGE("White balance mode %s is not supported.", mode_name);
} else {
LOGE("White balance mode value not in valid range.");
}
}
break;
case ANDROID_CAMERA_PROPERTY_ANTIBANDING:
{
int new_val = (int)value;
if(new_val >= 0 && new_val < ANDROID_CAMERA_ANTIBANDING_MODES_NUM){
const char* mode_name = antibandingModesNames[new_val];
if(is_supported(CameraParameters::KEY_SUPPORTED_ANTIBANDING, mode_name))
params.set(CameraParameters::KEY_ANTIBANDING, mode_name);
else
LOGE("Antibanding mode %s is not supported.", mode_name);
} else {
LOGE("Antibanding mode value not in valid range.");
}
}
break;
default:
LOGW("CameraHandler::setProperty - Unsupported property.");
};
}
@@ -5,7 +5,64 @@ enum {
ANDROID_CAMERA_PROPERTY_FRAMEWIDTH = 0,
ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT = 1,
ANDROID_CAMERA_PROPERTY_SUPPORTED_PREVIEW_SIZES_STRING = 2,
ANDROID_CAMERA_PROPERTY_PREVIEW_FORMAT_STRING = 3
ANDROID_CAMERA_PROPERTY_PREVIEW_FORMAT_STRING = 3,
ANDROID_CAMERA_PROPERTY_FPS = 4,
ANDROID_CAMERA_PROPERTY_EXPOSURE = 5,
ANDROID_CAMERA_PROPERTY_FLASH_MODE = 101,
ANDROID_CAMERA_PROPERTY_FOCUS_MODE = 102,
ANDROID_CAMERA_PROPERTY_WHITE_BALANCE = 103,
ANDROID_CAMERA_PROPERTY_ANTIBANDING = 104,
ANDROID_CAMERA_PROPERTY_FOCAL_LENGTH = 105,
ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_NEAR = 106,
ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_OPTIMAL = 107,
ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_FAR = 108
};
enum {
ANDROID_CAMERA_FLASH_MODE_AUTO = 0,
ANDROID_CAMERA_FLASH_MODE_OFF,
ANDROID_CAMERA_FLASH_MODE_ON,
ANDROID_CAMERA_FLASH_MODE_RED_EYE,
ANDROID_CAMERA_FLASH_MODE_TORCH,
ANDROID_CAMERA_FLASH_MODES_NUM
};
enum {
ANDROID_CAMERA_FOCUS_MODE_AUTO = 0,
ANDROID_CAMERA_FOCUS_MODE_CONTINUOUS_PICTURE,
ANDROID_CAMERA_FOCUS_MODE_CONTINUOUS_VIDEO,
ANDROID_CAMERA_FOCUS_MODE_EDOF,
ANDROID_CAMERA_FOCUS_MODE_FIXED,
ANDROID_CAMERA_FOCUS_MODE_INFINITY,
ANDROID_CAMERA_FOCUS_MODE_MACRO,
ANDROID_CAMERA_FOCUS_MODES_NUM
};
enum {
ANDROID_CAMERA_WHITE_BALANCE_AUTO = 0,
ANDROID_CAMERA_WHITE_BALANCE_CLOUDY_DAYLIGHT,
ANDROID_CAMERA_WHITE_BALANCE_DAYLIGHT,
ANDROID_CAMERA_WHITE_BALANCE_FLUORESCENT,
ANDROID_CAMERA_WHITE_BALANCE_INCANDESCENT,
ANDROID_CAMERA_WHITE_BALANCE_SHADE,
ANDROID_CAMERA_WHITE_BALANCE_TWILIGHT,
ANDROID_CAMERA_WHITE_BALANCE_WARM_FLUORESCENT,
ANDROID_CAMERA_WHITE_BALANCE_MODES_NUM
};
enum {
ANDROID_CAMERA_ANTIBANDING_50HZ = 0,
ANDROID_CAMERA_ANTIBANDING_60HZ,
ANDROID_CAMERA_ANTIBANDING_AUTO,
ANDROID_CAMERA_ANTIBANDING_OFF,
ANDROID_CAMERA_ANTIBANDING_MODES_NUM
};
enum {
ANDROID_CAMERA_FOCUS_DISTANCE_NEAR_INDEX = 0,
ANDROID_CAMERA_FOCUS_DISTANCE_OPTIMAL_INDEX,
ANDROID_CAMERA_FOCUS_DISTANCE_FAR_INDEX
};
#endif // CAMERA_PROPERTIES_H
@@ -33,7 +33,7 @@ where:
* :math:`(u, v)` are the coordinates of the projection point in pixels
* :math:`A` is a camera matrix, or a matrix of intrinsic parameters
* :math:`(cx, cy)` is a principal point that is usually at the image center
* :math:`fx, fy` are the focal lengths expressed in pixel-related units
* :math:`fx, fy` are the focal lengths expressed in pixel units.
Thus, if an image from the camera is
@@ -158,7 +158,7 @@ Finds the camera intrinsic and extrinsic parameters from several views of a cali
:param term_crit: same as ``criteria``.
The function estimates the intrinsic camera
parameters and extrinsic parameters for each of the views. The algorithm is based on [Zhang2000] and [BoughuetMCT]. The coordinates of 3D object points and their corresponding 2D projections
parameters and extrinsic parameters for each of the views. The algorithm is based on [Zhang2000]_ and [BouguetMCT]_. The coordinates of 3D object points and their corresponding 2D projections
in each view must be specified. That may be achieved by using an
object with a known geometry and easily detectable feature points.
Such an object is called a calibration rig or calibration pattern,
@@ -616,7 +616,7 @@ Finds an object pose from 3D-2D point correspondences using the RANSAC scheme.
:param flags: Method for solving a PnP problem (see :ocv:func:`solvePnP` ).
The function estimates an object pose given a set of object points, their corresponding image projections, as well as the camera matrix and the distortion coefficients. This function finds such a pose that minimizes reprojection error, that is, the sum of squared distances between the observed projections ``imagePoints`` and the projected (using
:ocv:func:`projectPoints` ) ``objectPoints``. The use of RANSAC makes the function resistant to outliers.
:ocv:func:`projectPoints` ) ``objectPoints``. The use of RANSAC makes the function resistant to outliers. The function is parallelized with the TBB library.
@@ -1127,8 +1127,7 @@ Computes disparity using the BM algorithm for a rectified stereo pair.
:param state: The pre-initialized ``CvStereoBMState`` structure in the case of the old API.
The method executes the BM algorithm on a rectified stereo pair. See the ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method. Note that the method is not constant, thus you should not use the same ``StereoBM`` instance from within different threads simultaneously.
The method executes the BM algorithm on a rectified stereo pair. See the ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method. Note that the method is not constant, thus you should not use the same ``StereoBM`` instance from within different threads simultaneously. The function is parallelized with the TBB library.
@@ -1165,13 +1164,13 @@ Class for computing stereo correspondence using the semi-global block matching a
...
};
The class implements the modified H. Hirschmuller algorithm HH08 that differs from the original one as follows:
The class implements the modified H. Hirschmuller algorithm [HH08]_ that differs from the original one as follows:
* By default, the algorithm is single-pass, which means that you consider only 5 directions instead of 8. Set ``fullDP=true`` to run the full variant of the algorithm but beware that it may consume a lot of memory.
* The algorithm matches blocks, not individual pixels. Though, setting ``SADWindowSize=1`` reduces the blocks to single pixels.
* Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi sub-pixel metric from BT96 is used. Though, the color images are supported as well.
* Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi sub-pixel metric from [BT98]_ is used. Though, the color images are supported as well.
* Some pre- and post- processing steps from K. Konolige algorithm :ocv:funcx:`StereoBM::operator()` are included, for example: pre-filtering (``CV_STEREO_BM_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering).
@@ -1556,13 +1555,6 @@ The function computes the rectification transformations without knowing intrinsi
While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, it would be better to correct it before computing the fundamental matrix and calling this function. For example, distortion coefficients can be estimated for each head of stereo camera separately by using :ocv:func:`calibrateCamera` . Then, the images can be corrected using :ocv:func:`undistort` , or just the point coordinates can be corrected with :ocv:func:`undistortPoints` .
.. [BouguetMCT] J.Y.Bouguet. MATLAB calibration tool. http://www.vision.caltech.edu/bouguetj/calib_doc/
.. [Hartley99] Hartley, R.I., Theory and Practice of Projective Rectification. IJCV 35 2, pp 115-127 (1999)
.. [Zhang2000] Z. Zhang. A Flexible New Technique for Camera Calibration. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(11):1330-1334, 2000.
triangulatePoints
-----------------
@@ -1589,3 +1581,14 @@ The function reconstructs 3-dimensional points (in homogeneous coordinates) by u
.. seealso::
:ocv:func:`reprojectImageTo3D`
.. [BT98] Birchfield, S. and Tomasi, C. A pixel dissimilarity measure that is insensitive to image sampling. IEEE Transactions on Pattern Analysis and Machine Intelligence. 1998.
.. [BouguetMCT] J.Y.Bouguet. MATLAB calibration tool. http://www.vision.caltech.edu/bouguetj/calib_doc/
.. [Hartley99] Hartley, R.I., Theory and Practice of Projective Rectification. IJCV 35 2, pp 115-127 (1999)
.. [HH08] Hirschmuller, H. Stereo Processing by Semiglobal Matching and Mutual Information, PAMI(30), No. 2, February 2008, pp. 328-341.
.. [Zhang2000] Z. Zhang. A Flexible New Technique for Camera Calibration. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(11):1330-1334, 2000.
+8 -3
View File
@@ -29,10 +29,18 @@ epnp::epnp(const cv::Mat& cameraMatrix, const cv::Mat& opoints, const cv::Mat& i
alphas.resize(4 * number_of_correspondences);
pcs.resize(3 * number_of_correspondences);
max_nr = 0;
A1 = NULL;
A2 = NULL;
}
epnp::~epnp()
{
if (A1)
delete[] A1;
if (A2)
delete[] A2;
}
void epnp::choose_control_points(void)
@@ -513,9 +521,6 @@ void epnp::gauss_newton(const CvMat * L_6x10, const CvMat * Rho,
void epnp::qr_solve(CvMat * A, CvMat * b, CvMat * X)
{
static int max_nr = 0;
static double * A1, * A2;
const int nr = A->rows;
const int nc = A->cols;
+11 -9
View File
@@ -14,24 +14,24 @@ class epnp {
void compute_pose(cv::Mat& R, cv::Mat& t);
private:
template <typename T>
void init_camera_parameters(const cv::Mat& cameraMatrix)
{
uc = cameraMatrix.at<T> (0, 2);
vc = cameraMatrix.at<T> (1, 2);
fu = cameraMatrix.at<T> (0, 0);
fv = cameraMatrix.at<T> (1, 1);
void init_camera_parameters(const cv::Mat& cameraMatrix)
{
uc = cameraMatrix.at<T> (0, 2);
vc = cameraMatrix.at<T> (1, 2);
fu = cameraMatrix.at<T> (0, 0);
fv = cameraMatrix.at<T> (1, 1);
}
template <typename OpointType, typename IpointType>
void init_points(const cv::Mat& opoints, const cv::Mat& ipoints)
{
for(int i = 0; i < number_of_correspondences; i++)
{
for(int i = 0; i < number_of_correspondences; i++)
{
pws[3 * i ] = opoints.at<OpointType>(0,i).x;
pws[3 * i + 1] = opoints.at<OpointType>(0,i).y;
pws[3 * i + 2] = opoints.at<OpointType>(0,i).z;
us[2 * i ] = ipoints.at<IpointType>(0,i).x*fu + uc;
us[2 * i + 1] = ipoints.at<IpointType>(0,i).y*fv + vc;
us[2 * i + 1] = ipoints.at<IpointType>(0,i).y*fv + vc;
}
}
double reprojection_error(const double R[3][3], const double t[3]);
@@ -74,6 +74,8 @@ class epnp {
double cws[4][3], ccs[4][3];
double cws_determinant;
int max_nr;
double * A1, * A2;
};
#endif
+34 -18
View File
@@ -333,6 +333,7 @@ void CV_CameraCalibrationTest::run( int start_from )
goodTransVects = 0;
goodRotMatrs = 0;
int progress = 0;
int values_read = -1;
sprintf( filepath, "%scameracalibration/", ts->get_data_path().c_str() );
sprintf( filename, "%sdatafiles.txt", filepath );
@@ -344,11 +345,13 @@ void CV_CameraCalibrationTest::run( int start_from )
goto _exit_;
}
fscanf(datafile,"%d",&numTests);
values_read = fscanf(datafile,"%d",&numTests);
CV_Assert(values_read == 1);
for( currTest = start_from; currTest < numTests; currTest++ )
{
fscanf(datafile,"%s",i_dat_file);
values_read = fscanf(datafile,"%s",i_dat_file);
CV_Assert(values_read == 1);
sprintf(filename, "%s%s", filepath, i_dat_file);
file = fopen(filename,"r");
@@ -366,7 +369,8 @@ void CV_CameraCalibrationTest::run( int start_from )
continue; // if there is more than one test, just skip the test
}
fscanf(file,"%d %d\n",&(imageSize.width),&(imageSize.height));
values_read = fscanf(file,"%d %d\n",&(imageSize.width),&(imageSize.height));
CV_Assert(values_read == 2);
if( imageSize.width <= 0 || imageSize.height <= 0 )
{
ts->printf( cvtest::TS::LOG, "Image size in test file is incorrect\n" );
@@ -375,7 +379,8 @@ void CV_CameraCalibrationTest::run( int start_from )
}
/* Read etalon size */
fscanf(file,"%d %d\n",&(etalonSize.width),&(etalonSize.height));
values_read = fscanf(file,"%d %d\n",&(etalonSize.width),&(etalonSize.height));
CV_Assert(values_read == 2);
if( etalonSize.width <= 0 || etalonSize.height <= 0 )
{
ts->printf( cvtest::TS::LOG, "Pattern size in test file is incorrect\n" );
@@ -386,7 +391,8 @@ void CV_CameraCalibrationTest::run( int start_from )
numPoints = etalonSize.width * etalonSize.height;
/* Read number of images */
fscanf(file,"%d\n",&numImages);
values_read = fscanf(file,"%d\n",&numImages);
CV_Assert(values_read == 1);
if( numImages <=0 )
{
ts->printf( cvtest::TS::LOG, "Number of images in test file is incorrect\n");
@@ -427,7 +433,8 @@ void CV_CameraCalibrationTest::run( int start_from )
for( currPoint = 0; currPoint < numPoints; currPoint++ )
{
double x,y,z;
fscanf(file,"%lf %lf %lf\n",&x,&y,&z);
values_read = fscanf(file,"%lf %lf %lf\n",&x,&y,&z);
CV_Assert(values_read == 3);
(objectPoints+i)->x = x;
(objectPoints+i)->y = y;
@@ -443,7 +450,8 @@ void CV_CameraCalibrationTest::run( int start_from )
for( currPoint = 0; currPoint < numPoints; currPoint++ )
{
double x,y;
fscanf(file,"%lf %lf\n",&x,&y);
values_read = fscanf(file,"%lf %lf\n",&x,&y);
CV_Assert(values_read == 2);
(imagePoints+i)->x = x;
(imagePoints+i)->y = y;
@@ -455,32 +463,40 @@ void CV_CameraCalibrationTest::run( int start_from )
/* Focal lengths */
double goodFcx,goodFcy;
fscanf(file,"%lf %lf",&goodFcx,&goodFcy);
values_read = fscanf(file,"%lf %lf",&goodFcx,&goodFcy);
CV_Assert(values_read == 2);
/* Principal points */
double goodCx,goodCy;
fscanf(file,"%lf %lf",&goodCx,&goodCy);
values_read = fscanf(file,"%lf %lf",&goodCx,&goodCy);
CV_Assert(values_read == 2);
/* Read distortion */
fscanf(file,"%lf",goodDistortion+0);
fscanf(file,"%lf",goodDistortion+1);
fscanf(file,"%lf",goodDistortion+2);
fscanf(file,"%lf",goodDistortion+3);
values_read = fscanf(file,"%lf",goodDistortion+0); CV_Assert(values_read == 1);
values_read = fscanf(file,"%lf",goodDistortion+1); CV_Assert(values_read == 1);
values_read = fscanf(file,"%lf",goodDistortion+2); CV_Assert(values_read == 1);
values_read = fscanf(file,"%lf",goodDistortion+3); CV_Assert(values_read == 1);
/* Read good Rot matrixes */
for( currImage = 0; currImage < numImages; currImage++ )
{
for( i = 0; i < 3; i++ )
for( j = 0; j < 3; j++ )
fscanf(file, "%lf", goodRotMatrs + currImage * 9 + j * 3 + i);
{
values_read = fscanf(file, "%lf", goodRotMatrs + currImage * 9 + j * 3 + i);
CV_Assert(values_read == 1);
}
}
/* Read good Trans vectors */
for( currImage = 0; currImage < numImages; currImage++ )
{
for( i = 0; i < 3; i++ )
fscanf(file, "%lf", goodTransVects + currImage * 3 + i);
{
values_read = fscanf(file, "%lf", goodTransVects + currImage * 3 + i);
CV_Assert(values_read == 1);
}
}
calibFlags = 0
@@ -1508,7 +1524,7 @@ void CV_StereoCalibrationTest::run( int )
const float minDisparity = 0.1f;
const float maxDisparity = 600.0f;
const int pointsCount = 500;
const float requiredAccuracy = 1e-3;
const float requiredAccuracy = 1e-3f;
RNG& rng = ts->get_rng();
Mat projectedPoints_1(2, pointsCount, CV_32FC1);
@@ -1544,7 +1560,7 @@ void CV_StereoCalibrationTest::run( int )
}
//check correctMatches
const float constraintAccuracy = 1e-5;
const float constraintAccuracy = 1e-5f;
Mat newPoints1, newPoints2;
Mat points1 = projectedPoints_1.t();
points1 = points1.reshape(2, 1);
@@ -1767,7 +1783,7 @@ void CV_StereoCalibrationTest_C::correct( const Mat& F,
CvMat _F = F, _points1 = points1, _points2 = points2;
newPoints1.create(1, points1.cols, points1.type());
newPoints2.create(1, points2.cols, points2.type());
CvMat _newPoints1 = newPoints1, _newPoints2 = _newPoints2;
CvMat _newPoints1 = newPoints1, _newPoints2 = newPoints2;
cvCorrectMatches(&_F, &_points1, &_points2, &_newPoints1, &_newPoints2);
}
@@ -66,7 +66,6 @@ struct CV_EXPORTS CvMotionModel
}
float low_pass_gain; // low pass gain
CvEMParams em_params; // EM parameters
};
// Mean Shift Tracker parameters for specifying use of HSV channel and CamShift parameters.
@@ -109,7 +108,6 @@ struct CV_EXPORTS CvHybridTrackerParams
float ms_tracker_weight;
CvFeatureTrackerParams ft_params;
CvMeanShiftTrackerParams ms_params;
CvEMParams em_params;
int motion_model;
float low_pass_gain;
};
@@ -182,7 +180,6 @@ private:
CvMat* samples;
CvMat* labels;
CvEM em_model;
Rect prev_window;
Point2f prev_center;
+4 -3
View File
@@ -47,7 +47,7 @@ static void sortMatrixRowsByIndices(InputArray _src, InputArray _indices, Output
Mat dst = _dst.getMat();
for(size_t idx = 0; idx < indices.size(); idx++) {
Mat originalRow = src.row(indices[idx]);
Mat sortedRow = dst.row(idx);
Mat sortedRow = dst.row((int)idx);
originalRow.copyTo(sortedRow);
}
}
@@ -127,8 +127,9 @@ static Mat interp1(InputArray _x, InputArray _Y, InputArray _xi)
case CV_32SC1: return interp1_<int>(x,Y,xi); break;
case CV_32FC1: return interp1_<float>(x,Y,xi); break;
case CV_64FC1: return interp1_<double>(x,Y,xi); break;
default: CV_Error(CV_StsUnsupportedFormat, ""); return Mat();
default: CV_Error(CV_StsUnsupportedFormat, ""); break;
}
return Mat();
}
namespace colormap
@@ -166,7 +167,7 @@ namespace colormap
static Mat linear_colormap(InputArray X,
InputArray r, InputArray g, InputArray b,
float begin, float end, float n) {
return linear_colormap(X,r,g,b,linspace(begin,end,n));
return linear_colormap(X,r,g,b,linspace(begin,end, cvRound(n)));
}
// Interpolates from a base colormap.
+7 -7
View File
@@ -117,7 +117,7 @@ public:
void train(InputArray src, InputArray labels);
// Predicts the label of a query image in src.
int predict(const InputArray src) const;
int predict(InputArray src) const;
// See FaceRecognizer::load.
void load(const FileStorage& fs);
@@ -384,7 +384,7 @@ void Fisherfaces::train(InputArray src, InputArray _lbls) {
if(labels.size() != (size_t)N)
CV_Error(CV_StsUnsupportedFormat, "Labels must be given as integer (CV_32SC1).");
// compute the Fisherfaces
int C = remove_dups(labels).size(); // number of unique classes
int C = (int)remove_dups(labels).size(); // number of unique classes
// clip number of components to be a valid number
if((_num_components <= 0) || (_num_components > (C-1)))
_num_components = (C-1);
@@ -495,8 +495,8 @@ inline void elbp_(InputArray _src, OutputArray _dst, int radius, int neighbors)
dst.setTo(0);
for(int n=0; n<neighbors; n++) {
// sample points
float x = static_cast<float>(-radius) * sin(2.0*CV_PI*n/static_cast<float>(neighbors));
float y = static_cast<float>(radius) * cos(2.0*CV_PI*n/static_cast<float>(neighbors));
float x = static_cast<float>(-radius * sin(2.0*CV_PI*n/static_cast<float>(neighbors)));
float y = static_cast<float>(radius * cos(2.0*CV_PI*n/static_cast<float>(neighbors)));
// relative indices
int fx = static_cast<int>(floor(x));
int fy = static_cast<int>(floor(y));
@@ -514,7 +514,7 @@ inline void elbp_(InputArray _src, OutputArray _dst, int radius, int neighbors)
for(int i=radius; i < src.rows-radius;i++) {
for(int j=radius;j < src.cols-radius;j++) {
// calculate interpolated value
float t = w1*src.at<_Tp>(i+fy,j+fx) + w2*src.at<_Tp>(i+fy,j+cx) + w3*src.at<_Tp>(i+cy,j+fx) + w4*src.at<_Tp>(i+cy,j+cx);
float t = static_cast<float>(w1*src.at<_Tp>(i+fy,j+fx) + w2*src.at<_Tp>(i+fy,j+cx) + w3*src.at<_Tp>(i+cy,j+fx) + w4*src.at<_Tp>(i+cy,j+cx));
// floating point precision, so check some machine-dependent epsilon
dst.at<int>(i-radius,j-radius) += ((t > src.at<_Tp>(i,j)) || (std::abs(t-src.at<_Tp>(i,j)) < std::numeric_limits<float>::epsilon())) << n;
}
@@ -543,13 +543,13 @@ histc_(const Mat& src, int minVal=0, int maxVal=255, bool normed=false)
// Establish the number of bins.
int histSize = maxVal-minVal+1;
// Set the ranges.
float range[] = { minVal, maxVal } ;
float range[] = { static_cast<float>(minVal), static_cast<float>(maxVal) };
const float* histRange = { range };
// calc histogram
calcHist(&src, 1, 0, Mat(), result, 1, &histSize, &histRange, true, false);
// normalize
if(normed) {
result /= src.total();
result /= (int)src.total();
}
return result.reshape(1,1);
}
+9 -14
View File
@@ -132,17 +132,6 @@ void CvHybridTracker::newTracker(Mat image, Rect selection) {
mstracker->newTrackingWindow(image, selection);
fttracker->newTrackingWindow(image, selection);
params.em_params.covs = NULL;
params.em_params.means = NULL;
params.em_params.probs = NULL;
params.em_params.nclusters = 1;
params.em_params.weights = NULL;
params.em_params.cov_mat_type = CvEM::COV_MAT_SPHERICAL;
params.em_params.start_step = CvEM::START_AUTO_STEP;
params.em_params.term_crit.max_iter = 10000;
params.em_params.term_crit.epsilon = 0.001;
params.em_params.term_crit.type = CV_TERMCRIT_ITER | CV_TERMCRIT_EPS;
samples = cvCreateMat(2, 1, CV_32FC1);
labels = cvCreateMat(2, 1, CV_32SC1);
@@ -221,10 +210,16 @@ void CvHybridTracker::updateTrackerWithEM(Mat image) {
count++;
}
em_model.train(samples, 0, params.em_params, labels);
cv::Mat lbls;
EM em_model(1, EM::COV_MAT_SPHERICAL, TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 10000, 0.001));
em_model.train(cvarrToMat(samples), lbls);
if(labels)
lbls.copyTo(cvarrToMat(labels));
curr_center.x = (float)em_model.getMeans().at<double> (0, 0);
curr_center.y = (float)em_model.getMeans().at<double> (0, 1);
Mat em_means = em_model.get<Mat>("means");
curr_center.x = (float)em_means.at<float>(0, 0);
curr_center.y = (float)em_means.at<float>(0, 1);
}
void CvHybridTracker::updateTrackerWithLowPassFilter(Mat image) {
+4 -4
View File
@@ -62,7 +62,7 @@ static Mat asRowMatrix(InputArrayOfArrays src, int rtype, double alpha=1, double
if(n == 0)
return Mat();
// dimensionality of samples
int d = src.getMat(0).total();
int d = (int)src.getMat(0).total();
// create data matrix
Mat data(n, d, rtype);
// copy data
@@ -82,7 +82,7 @@ void sortMatrixColumnsByIndices(InputArray _src, InputArray _indices, OutputArra
Mat dst = _dst.getMat();
for(size_t idx = 0; idx < indices.size(); idx++) {
Mat originalCol = src.col(indices[idx]);
Mat sortedCol = dst.col(idx);
Mat sortedCol = dst.col((int)idx);
originalCol.copyTo(sortedCol);
}
}
@@ -947,14 +947,14 @@ void LDA::lda(InputArray _src, InputArray _lbls) {
vector<int> num2label = remove_dups(labels);
map<int, int> label2num;
for (size_t i = 0; i < num2label.size(); i++)
label2num[num2label[i]] = i;
label2num[num2label[i]] = (int)i;
for (size_t i = 0; i < labels.size(); i++)
mapped_labels[i] = label2num[labels[i]];
// get sample size, dimension
int N = data.rows;
int D = data.cols;
// number of unique labels
int C = num2label.size();
int C = (int)num2label.size();
// throw error if less labels, than samples
if (labels.size() != (size_t)N)
CV_Error(CV_StsBadArg, "Error: The number of samples must equal the number of labels.");
+9 -9
View File
@@ -440,9 +440,9 @@ cv::Mesh3D::~Mesh3D() {}
void cv::Mesh3D::buildOctree() { if (octree.getNodes().empty()) octree.buildTree(vtx); }
void cv::Mesh3D::clearOctree(){ octree = Octree(); }
float cv::Mesh3D::estimateResolution(float tryRatio)
float cv::Mesh3D::estimateResolution(float /*tryRatio*/)
{
#if 0
#if 0
const int neighbors = 3;
const int minReasonable = 10;
@@ -476,10 +476,10 @@ float cv::Mesh3D::estimateResolution(float tryRatio)
sort(dist, less<double>());
return resolution = (float)dist[ dist.size() / 2 ];
#else
#else
CV_Error(CV_StsNotImplemented, "");
return 1.f;
#endif
#endif
}
@@ -1171,7 +1171,7 @@ private:
break;
std::transform(left.begin(), left.end(), buf_beg, WgcHelper(group, groupingMat));
int minInd = min_element(buf_beg, buf_beg + left_size) - buf_beg;
size_t minInd = min_element(buf_beg, buf_beg + left_size) - buf_beg;
if (buf[minInd] < model.T_GroupingCorespondances) /* can add corespondance to group */
{
@@ -1182,14 +1182,14 @@ private:
left.erase(pos);
}
else
break;
break;
}
if (group.size() >= 4)
groups.push_back(group);
groups.push_back(group);
}
/* converting the data to final result */
/* converting the data to final result */
for(size_t i = 0; i < groups.size(); ++i)
{
const group_t& group = groups[i];
@@ -1197,7 +1197,7 @@ private:
vector< Vec2i > outgrp;
for(citer pos = group.begin(); pos != group.end(); ++pos)
{
const Match& m = allMatches[*pos];
const Match& m = allMatches[*pos];
outgrp.push_back(Vec2i(subset[m.modelInd], scene.subset[m.sceneInd]));
}
result.push_back(outgrp);
+7 -4
View File
@@ -16,7 +16,13 @@ else()
set(cuda_link_libs "")
endif()
ocv_glob_module_sources(SOURCES ${lib_cuda} ${cuda_objs})
set(OPENCV_VERSION_FILE "${opencv_core_BINARY_DIR}/version_string.inc")
add_custom_command(OUTPUT "${OPENCV_VERSION_FILE}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${OPENCV_BUILD_INFO_FILE}" "${OPENCV_VERSION_FILE}"
MAIN_DEPENDENCY "${OPENCV_BUILD_INFO_FILE}"
COMMENT "")
ocv_glob_module_sources(SOURCES ${lib_cuda} ${cuda_objs} "${OPENCV_VERSION_FILE}")
ocv_create_module(${cuda_link_libs})
ocv_add_precompiled_headers(${the_module})
@@ -24,6 +30,3 @@ ocv_add_precompiled_headers(${the_module})
ocv_add_accuracy_tests()
ocv_add_perf_tests()
+12 -10
View File
@@ -42,7 +42,7 @@ The main purpose of this class is to convert compilation-time type information t
cout << B.depth() << ", " << B.channels() << endl;
So, such traits are used to tell OpenCV which data type you are working with, even if such a type is not native to OpenCV. For example, the matrix ``B`` intialization above is compiled because OpenCV defines the proper specialized template class ``DataType<complex<_Tp> >`` . This mechanism is also useful (and used in OpenCV this way) for generic algorithms implementations.
So, such traits are used to tell OpenCV which data type you are working with, even if such a type is not native to OpenCV. For example, the matrix ``B`` initialization above is compiled because OpenCV defines the proper specialized template class ``DataType<complex<_Tp> >`` . This mechanism is also useful (and used in OpenCV this way) for generic algorithms implementations.
Point\_
@@ -100,7 +100,7 @@ Size\_
------
.. ocv:class:: Size_
Template class for specfying the size of an image or rectangle. The class includes two members called ``width`` and ``height``. The structure can be converted to and from the old OpenCV structures
Template class for specifying the size of an image or rectangle. The class includes two members called ``width`` and ``height``. The structure can be converted to and from the old OpenCV structures
``CvSize`` and ``CvSize2D32f`` . The same set of arithmetic and comparison operations as for ``Point_`` is available.
OpenCV defines the following ``Size_<>`` aliases: ::
@@ -372,7 +372,7 @@ This class provides the following options:
*
Heterogeneous collections of objects. The standard STL and most other C++ and OpenCV containers can store only objects of the same type and the same size. The classical solution to store objects of different types in the same container is to store pointers to the base class ``base_class_t*`` instead but then you loose the automatic memory management. Again, by using ``Ptr<base_class_t>()`` instead of the raw pointers, you can solve the problem.
The ``Ptr`` class treats the wrapped object as a black box. The reference counter is allocated and managed separately. The only thing the pointer class needs to know about the object is how to deallocate it. This knowledge is incapsulated in the ``Ptr::delete_obj()`` method that is called when the reference counter becomes 0. If the object is a C++ class instance, no additional coding is needed, because the default implementation of this method calls ``delete obj;`` .
The ``Ptr`` class treats the wrapped object as a black box. The reference counter is allocated and managed separately. The only thing the pointer class needs to know about the object is how to deallocate it. This knowledge is encapsulated in the ``Ptr::delete_obj()`` method that is called when the reference counter becomes 0. If the object is a C++ class instance, no additional coding is needed, because the default implementation of this method calls ``delete obj;`` .
However, if the object is deallocated in a different way, the specialized method should be created. For example, if you want to wrap ``FILE`` , the ``delete_obj`` may be implemented as follows: ::
template<> inline void Ptr<FILE>::delete_obj()
@@ -711,7 +711,7 @@ This is a list of implemented matrix operations that can be combined in arbitrar
*
``Mat_<destination_type>()`` constructors to cast the result to the proper type.
.. note:: Comma-separated initializers and probably some other operations may require additional explicit ``Mat()`` or ``Mat_<T>()`` constuctor calls to resolve a possible ambiguity.
.. note:: Comma-separated initializers and probably some other operations may require additional explicit ``Mat()`` or ``Mat_<T>()`` constructor calls to resolve a possible ambiguity.
Here are examples of matrix expressions:
@@ -786,6 +786,8 @@ Various Mat constructors
:param cols: Number of columns in a 2D array.
:param roi: Region of interest.
:param size: 2D array size: ``Size(cols, rows)`` . In the ``Size()`` constructor, the number of rows and the number of columns go in the reverse order.
:param sizes: Array of integers specifying an n-dimensional array shape.
@@ -890,7 +892,7 @@ The method makes a new header for the specified matrix row and returns it. This
// works, but looks a bit obscure.
A.row(i) = A.row(j) + 0;
// this is a bit longe, but the recommended method.
// this is a bit longer, but the recommended method.
A.row(j).copyTo(A.row(i));
Mat::col
@@ -996,7 +998,7 @@ When the operation mask is specified, and the ``Mat::create`` call shown above r
Mat::convertTo
------------------
Converts an array to another datatype with optional scaling.
Converts an array to another data type with optional scaling.
.. ocv:function:: void Mat::convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const
@@ -1008,7 +1010,7 @@ Converts an array to another datatype with optional scaling.
:param beta: Optional delta added to the scaled values.
The method converts source pixel values to the target datatype. ``saturate_cast<>`` is applied at the end to avoid possible overflows:
The method converts source pixel values to the target data type. ``saturate_cast<>`` is applied at the end to avoid possible overflows:
.. math::
@@ -1347,7 +1349,7 @@ Locates the matrix header within a parent matrix.
.. ocv:function:: void Mat::locateROI( Size& wholeSize, Point& ofs ) const
:param wholeSize: Output parameter that contains the size of the whole matrix containing ``*this`` is a part.
:param wholeSize: Output parameter that contains the size of the whole matrix containing ``*this`` as a part.
:param ofs: Output parameter that contains an offset of ``*this`` inside the whole matrix.
@@ -1380,7 +1382,7 @@ The method is complimentary to
In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the filtering with the 5x5 kernel.
It is your responsibility to make sure ``adjustROI`` does not cross the parent matrix boundary. If it does, the function signals an error.
``adjustROI`` forces the adjusted ROI to be inside of the parent matrix that is boundaries of the adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix ``A`` is located in the first row of a parent matrix and you called ``A.adjustROI(2, 2, 2, 2)`` then ``A`` will not be increased in the upward direction.
The function is used internally by the OpenCV filtering functions, like
:ocv:func:`filter2D` , morphological operations, and so on.
@@ -1600,7 +1602,7 @@ The method returns a matrix size: ``Size(cols, rows)`` . When the matrix is more
Mat::empty
--------------
Returns ``true`` if the array has no elemens.
Returns ``true`` if the array has no elements.
.. ocv:function:: bool Mat::empty() const
+7 -3
View File
@@ -11,9 +11,9 @@ Finds centers of clusters and groups input samples around the clusters.
.. ocv:pyfunction:: cv2.kmeans(data, K, criteria, attempts, flags[, bestLabels[, centers]]) -> retval, bestLabels, centers
.. ocv:cfunction:: int cvKMeans2(const CvArr* samples, int nclusters, CvArr* labels, CvTermCriteria criteria, int attempts=1, CvRNG* rng=0, int flags=0, CvArr* centers=0, double* compactness=0)
.. ocv:cfunction:: int cvKMeans2(const CvArr* samples, int clusterCount, CvArr* labels, CvTermCriteria criteria, int attempts=1, CvRNG* rng=0, int flags=0, CvArr* centers=0, double* compactness=0)
.. ocv:pyoldfunction:: cv.KMeans2(samples, nclusters, labels, criteria)-> None
.. ocv:pyoldfunction:: cv.KMeans2(samples, clusterCount, labels, criteria)-> None
:param samples: Floating-point matrix of input samples, one row per sample.
@@ -23,7 +23,9 @@ Finds centers of clusters and groups input samples around the clusters.
:param criteria: The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy. The accuracy is specified as ``criteria.epsilon``. As soon as each of the cluster centers moves by less than ``criteria.epsilon`` on some iteration, the algorithm stops.
:param attempts: Flag to specify the number of times the algorithm is executed using different initial labelings. The algorithm returns the labels that yield the best compactness (see the last function parameter).
:param attempts: Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness (see the last function parameter).
:param rng: CvRNG state initialized by RNG().
:param flags: Flag that can take the following values:
@@ -35,6 +37,8 @@ Finds centers of clusters and groups input samples around the clusters.
:param centers: Output matrix of the cluster centers, one row per each cluster center.
:param compactness: The returned value that is described below.
The function ``kmeans`` implements a k-means algorithm that finds the
centers of ``clusterCount`` clusters and groups the input samples
around the clusters. As an output,
+5 -3
View File
@@ -190,7 +190,7 @@ Fills the area bounded by one or more polygons.
.. ocv:pyfunction:: cv2.fillPoly(img, pts, color[, lineType[, shift[, offset]]]) -> None
.. ocv:cfunction:: void cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int contours, CvScalar color, int lineType=8, int shift=0 )
.. ocv:cfunction:: void cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int ncontours, CvScalar color, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.FillPoly(img, polys, color, lineType=8, shift=0)-> None
:param img: Image.
@@ -207,8 +207,10 @@ Fills the area bounded by one or more polygons.
:param shift: Number of fractional bits in the vertex coordinates.
:param offset: Optional offset of all points of the contours.
The function ``fillPoly`` fills an area bounded by several polygonal contours. The function can fill complex areas, for example,
areas with holes, contours with self-intersections (some of thier parts), and so forth.
areas with holes, contours with self-intersections (some of their parts), and so forth.
@@ -413,7 +415,7 @@ Draws a simple, thick, or filled up-right rectangle.
:param pt1: Vertex of the rectangle.
:param pt2: Vertex of the recangle opposite to ``pt1`` .
:param pt2: Vertex of the rectangle opposite to ``pt1`` .
:param r: Alternative specification of the drawn rectangle.
+15 -9
View File
@@ -34,7 +34,7 @@ A storage for various OpenCV dynamic data structures, such as ``CvSeq``, ``CvSet
Memory storage is a low-level structure used to store dynamically growing data structures such as sequences, contours, graphs, subdivisions, etc. It is organized as a list of memory blocks of equal size -
``bottom`` field is the beginning of the list of blocks and ``top`` is the currently used block, but not necessarily the last block of the list. All blocks between ``bottom`` and ``top``, not including the
latter, are considered fully occupied; all blocks between ``top`` and the last block, not including ``top``, are considered free and ``top`` itself is partly ocupied - ``free_space`` contains the number of free bytes left in the end of ``top``.
latter, are considered fully occupied; all blocks between ``top`` and the last block, not including ``top``, are considered free and ``top`` itself is partly occupied - ``free_space`` contains the number of free bytes left in the end of ``top``.
A new memory buffer that may be allocated explicitly by :ocv:cfunc:`MemStorageAlloc` function or implicitly by higher-level functions, such as :ocv:cfunc:`SeqPush`, :ocv:cfunc:`GraphAddEdge` etc.
@@ -126,16 +126,22 @@ There are helper functions to construct the slice and to compute its length:
.. ocv:cfunction:: CvSlice cvSlice( int start, int end )
:param start: Inclusive left boundary.
:param end: Exclusive right boundary.
::
#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
..
.. ocv:cfunction:: int cvSliceLength( CvSlice slice, const CvSeq* seq )
Calculates the sequence slice length
:param slice: The slice of sequence.
:param seq: Source sequence.
Calculates the sequence slice length.
Some of functions that operate on sequences take a ``CvSlice slice`` parameter that is often set to the whole sequence (CV_WHOLE_SEQ) by default. Either of the ``start_index`` and ``end_index`` may be negative or exceed the sequence length. If they are equal, the slice is considered empty (i.e., contains no elements). Because sequences are treated as circular structures, the slice may select a
few elements in the end of a sequence followed by a few elements at the beginning of the sequence. For example, ``cvSlice(-2, 3)`` in the case of a 10-element sequence will select a 5-element slice, containing the pre-last (8th), last (9th), the very first (0th), second (1th) and third (2nd)
@@ -338,7 +344,7 @@ Creates structure for depth-first graph traversal.
* **CV_GRAPH_BACK_EDGE** stop at back edges ( ``back edge`` is an edge connecting the last visited vertex with some of its ancestors in the search tree)
* **CV_GRAPH_FORWARD_EDGE** stop at forward edges ( ``forward edge`` is an edge conecting the last visited vertex with some of its descendants in the search tree. The forward edges are only possible during oriented graph traversal)
* **CV_GRAPH_FORWARD_EDGE** stop at forward edges ( ``forward edge`` is an edge connecting the last visited vertex with some of its descendants in the search tree. The forward edges are only possible during oriented graph traversal)
* **CV_GRAPH_CROSS_EDGE** stop at cross edges ( ``cross edge`` is an edge connecting different search trees or branches of the same tree. The ``cross edges`` are only possible during oriented graph traversal)
@@ -715,7 +721,7 @@ The function removes a vertex from the graph by using its pointer together with
GraphVtxDegree
--------------
Counts the number of edges indicent to the vertex.
Counts the number of edges incident to the vertex.
.. ocv:cfunction:: int cvGraphVtxDegree( const CvGraph* graph, int vtxIdx )
@@ -1222,7 +1228,7 @@ Searches for an element in a sequence.
:param elem_idx: Output parameter; index of the found element
:param userdata: The user parameter passed to the compasion function; helps to avoid global variables in some cases
:param userdata: The user parameter passed to the comparison function; helps to avoid global variables in some cases
::
@@ -1265,7 +1271,7 @@ Sorts sequence element using the specified comparison function.
:param func: The comparison function that returns a negative, zero, or positive value depending on the relationships among the elements (see the above declaration and the example below) - a similar function is used by ``qsort`` from C runline except that in the latter, ``userdata`` is not used
:param userdata: The user parameter passed to the compasion function; helps to avoid global variables in some cases
:param userdata: The user parameter passed to the comparison function; helps to avoid global variables in some cases
::
@@ -1552,5 +1558,5 @@ Gathers all node pointers to a single sequence.
:param storage: Container for the sequence
The function puts pointers of all nodes reacheable from ``first`` into a single sequence. The pointers are written sequentially in the depth-first order.
The function puts pointers of all nodes reachable from ``first`` into a single sequence. The pointers are written sequentially in the depth-first order.
+1 -1
View File
@@ -91,7 +91,7 @@ you can use::
Ptr<T> ptr = new T(...);
That is, ``Ptr<T> ptr`` incapsulates a pointer to a ``T`` instance and a reference counter associated with the pointer. See the
That is, ``Ptr<T> ptr`` encapsulates a pointer to a ``T`` instance and a reference counter associated with the pointer. See the
:ocv:class:`Ptr`
description for details.
+2 -2
View File
@@ -750,7 +750,7 @@ or:
DotProduct
----------
Calculates the dot product of two arrays in Euclidian metrics.
Calculates the dot product of two arrays in Euclidean metrics.
.. ocv:cfunction:: double cvDotProduct(const CvArr* src1, const CvArr* src2)
.. ocv:pyoldfunction:: cv.DotProduct(src1, src2)-> double
@@ -937,7 +937,7 @@ The function provides an easy way to handle both types of arrays - ``IplImage``
.. seealso:: :ocv:cfunc:`GetImage`, :ocv:func:`cvarrToMat`.
.. note:: If the input array is ``IplImage`` with planar data layout and COI set, the function returns the pointer to the selected plane and ``COI == 0``. This feature allows user to process ``IplImage`` strctures with planar data layout, even though OpenCV does not support such images.
.. note:: If the input array is ``IplImage`` with planar data layout and COI set, the function returns the pointer to the selected plane and ``COI == 0``. This feature allows user to process ``IplImage`` structures with planar data layout, even though OpenCV does not support such images.
GetNextSparseNode
-----------------
@@ -144,7 +144,7 @@ Type information. ::
..
The structure contains information about one of the standard or user-defined types. Instances of the type may or may not contain a pointer to the corresponding :ocv:struct:`CvTypeInfo` structure. In any case, there is a way to find the type info structure for a given object using the :ocv:cfunc:`TypeOf` function. Aternatively, type info can be found by type name using :ocv:cfunc:`FindType`, which is used when an object is read from file storage. The user can register a new type with :ocv:cfunc:`RegisterType`
The structure contains information about one of the standard or user-defined types. Instances of the type may or may not contain a pointer to the corresponding :ocv:struct:`CvTypeInfo` structure. In any case, there is a way to find the type info structure for a given object using the :ocv:cfunc:`TypeOf` function. Alternatively, type info can be found by type name using :ocv:cfunc:`FindType`, which is used when an object is read from file storage. The user can register a new type with :ocv:cfunc:`RegisterType`
that adds the type information structure into the beginning of the type list. Thus, it is possible to create specialized types from generic standard types and override the basic methods.
Clone
@@ -215,7 +215,7 @@ Finds a node in a map or file storage.
:param name: The file node name
The function finds a file node by ``name``. The node is searched either in ``map`` or, if the pointer is NULL, among the top-level file storage nodes. Using this function for maps and :ocv:cfunc:`GetSeqElem`
(or sequence reader) for sequences, it is possible to nagivate through the file storage. To speed up multiple queries for a certain key (e.g., in the case of an array of structures) one may use a combination of :ocv:cfunc:`GetHashedKey` and :ocv:cfunc:`GetFileNode`.
(or sequence reader) for sequences, it is possible to navigate through the file storage. To speed up multiple queries for a certain key (e.g., in the case of an array of structures) one may use a combination of :ocv:cfunc:`GetHashedKey` and :ocv:cfunc:`GetFileNode`.
GetFileNodeName
---------------
@@ -356,7 +356,7 @@ Opens file storage for reading or writing data.
* **CV_STORAGE_WRITE** the storage is open for writing
The function opens file storage for reading or writing data. In the latter case, a new file is created or an existing file is rewritten. The type of the read or written file is determined by the filename extension: ``.xml`` for ``XML`` and ``.yml`` or ``.yaml`` for ``YAML``. The function returns a pointer to the :ocv:struct:`CvFileStorage` structure.
The function opens file storage for reading or writing data. In the latter case, a new file is created or an existing file is rewritten. The type of the read or written file is determined by the filename extension: ``.xml`` for ``XML`` and ``.yml`` or ``.yaml`` for ``YAML``. The function returns a pointer to the :ocv:struct:`CvFileStorage` structure. If the file cannot be opened then the function returns ``NULL``.
Read
----
@@ -629,7 +629,7 @@ The function finishes the currently written stream and starts the next stream. I
</opencv_storage>
...
The a YAML file will look like this: ::
The YAML file will look like this: ::
%YAML:1.0
# stream #1 data
@@ -722,7 +722,7 @@ Writes an object to file storage.
:param ptr: Pointer to the object
:param attributes: The attributes of the object. They are specific for each particular type (see the dicsussion below).
:param attributes: The attributes of the object. They are specific for each particular type (see the discussion below).
The function writes an object to file storage. First, the appropriate type info is found using :ocv:cfunc:`TypeOf`. Then, the ``write`` method associated with the type info is called.
@@ -796,7 +796,7 @@ Writes a file node to another file storage.
:param node: The written node
:param embed: If the written node is a collection and this parameter is not zero, no extra level of hiararchy is created. Instead, all the elements of ``node`` are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence.
:param embed: If the written node is a collection and this parameter is not zero, no extra level of hierarchy is created. Instead, all the elements of ``node`` are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence.
The function writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML and YAML formats.
+40 -7
View File
@@ -208,7 +208,7 @@ Calculates the per-element bit-wise conjunction of two arrays or an array and a
:param src2: Second source array or a scalar.
:param dst: Destination arrayb that has the same size and type as the input array(s).
:param dst: Destination array that has the same size and type as the input array(s).
:param mask: Optional operation mask, 8-bit single channel array, that specifies elements of the destination array to be changed.
@@ -1124,6 +1124,37 @@ To extract a channel from a new-style matrix, use
.. seealso:: :ocv:func:`mixChannels` , :ocv:func:`split` , :ocv:func:`merge` , :ocv:func:`cvarrToMat` , :ocv:cfunc:`cvSetImageCOI` , :ocv:cfunc:`cvGetImageCOI`
insertImageCOI
---------------
Copies the selected image channel from a new-style C++ matrix to the old-style C array.
.. ocv:function:: void insertImageCOI(InputArray src, CvArr* dst, int coi=-1)
:param src: Source array with a single channel and the same size and depth as ``dst``.
:param dst: Destination array, it should be a pointer to ``CvMat`` or ``IplImage``.
:param coi: If the parameter is ``>=0`` , it specifies the channel to insert. If it is ``<0`` and ``dst`` is a pointer to ``IplImage`` with a valid COI set, the selected COI is extracted.
The function ``insertImageCOI`` is used to extract an image COI from a new-style C++ matrix and put the result to the old-style array.
The sample below illustrates how to use the function:
::
Mat temp(240, 320, CV_8UC1, Scalar(255));
IplImage* img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
insertImageCOI(temp, img, 1); //insert to the first channel
cvNamedWindow("window",1);
cvShowImage("window", img); //you should see green image, because channel number 1 is green (BGR)
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&img);
To insert a channel to a new-style matrix, use
:ocv:func:`merge` .
.. seealso:: :ocv:func:`mixChannels` , :ocv:func:`split` , :ocv:func:`merge` , :ocv:func:`cvarrToMat` , :ocv:cfunc:`cvSetImageCOI` , :ocv:cfunc:`cvGetImageCOI`
flip
--------
@@ -1182,7 +1213,7 @@ Performs generalized matrix multiplication.
.. ocv:pyfunction:: cv2.gemm(src1, src2, alpha, src3, gamma[, dst[, flags]]) -> dst
.. ocv:cfunction:: void cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, const CvArr* src3, double beta, CvArr* dst, int tABC=0)
.. ocv:pyoldfunction:: cv.GEMM(src1, src2, alphs, src3, beta, dst, tABC=0)-> None
.. ocv:pyoldfunction:: cv.GEMM(src1, src2, alpha, src3, beta, dst, tABC=0)-> None
:param src1: First multiplied input matrix that should have ``CV_32FC1`` , ``CV_64FC1`` , ``CV_32FC2`` , or ``CV_64FC2`` type.
@@ -1373,7 +1404,7 @@ The function checks the range as follows:
That is, ``dst`` (I) is set to 255 (all ``1`` -bits) if ``src`` (I) is within the specified 1D, 2D, 3D, ... box and 0 otherwise.
When the lower and/or upper bounary parameters are scalars, the indexes ``(I)`` at ``lowerb`` and ``upperb`` in the above formulas should be omitted.
When the lower and/or upper boundary parameters are scalars, the indexes ``(I)`` at ``lowerb`` and ``upperb`` in the above formulas should be omitted.
invert
@@ -1398,7 +1429,7 @@ Finds the inverse or pseudo-inverse of a matrix.
* **DECOMP_SVD** Singular value decomposition (SVD) method.
* **DECOMP_CHOLESKY** Cholesky decomposion. The matrix must be symmetrical and positively defined.
* **DECOMP_CHOLESKY** Cholesky decomposition. The matrix must be symmetrical and positively defined.
The function ``invert`` inverts the matrix ``src`` and stores the result in ``dst`` .
When the matrix ``src`` is singular or non-square, the function computes the pseudo-inverse matrix (the ``dst`` matrix) so that ``norm(src*dst - I)`` is minimal, where I is an identity matrix.
@@ -2097,7 +2128,7 @@ Normalizes the norm or value range of an array.
:param alpha: Norm value to normalize to or the lower range boundary in case of the range normalization.
:param beta: Upper range boundary in case ofthe range normalization. It is not used for the norm normalization.
:param beta: Upper range boundary in case of the range normalization. It is not used for the norm normalization.
:param normType: Normalization type. See the details below.
@@ -2423,6 +2454,8 @@ So, for a non-integer power exponent, the absolute values of input array element
For some values of ``p`` , such as integer values, 0.5 and -0.5, specialized faster algorithms are used.
Special values (NaN, Inf) are not handled.
.. seealso::
:ocv:func:`sqrt`,
@@ -3021,7 +3054,7 @@ If you need to extract a single channel or do some other sophisticated channel p
sqrt
----
Calculates a quare root of array elements.
Calculates a square root of array elements.
.. ocv:function:: void sqrt(InputArray src, OutputArray dst)
@@ -3203,7 +3236,7 @@ Performs SVD of a matrix
:param vt: Transposed matrix of right singular values
:param flags: Opertion flags - see :ocv:func:`SVD::SVD`.
:param flags: Operation flags - see :ocv:func:`SVD::SVD`.
The methods/functions perform SVD of matrix. Unlike ``SVD::SVD`` constructor and ``SVD::operator()``, they store the results to the user-provided matrices. ::
@@ -31,7 +31,7 @@ Aligns a buffer size to the specified number of bytes.
:param n: Alignment size that must be a power of two.
The function returns the minimum number that is greater or equal to ``sz`` and is divisble by ``n`` :
The function returns the minimum number that is greater or equal to ``sz`` and is divisible by ``n`` :
.. math::
+530 -2
View File
@@ -148,17 +148,545 @@ FileStorage
-----------
.. ocv:class:: FileStorage
XML/YAML file storage class that incapsulates all the information necessary for writing or reading data to/from file.
XML/YAML file storage class that encapsulates all the information necessary for writing or reading data to/from a file.
FileStorage::FileStorage
------------------------
The constructors.
.. ocv:function:: FileStorage::FileStorage()
.. ocv:function:: FileStorage::FileStorage(const string& filename, int flags, const string& encoding=string())
:param filename: Name of the file to open. Extension of the file (``.xml`` or ``.yml``/``.yaml``) determines its format (XML or YAML respectively). Also you can append ``.gz`` to work with compressed files, for example ``myHugeMatrix.xml.gz``.
:param flags: Mode of operation. Possible values are:
* **FileStorage::READ** Open the file for reading.
* **FileStorage::WRITE** Open the file for writing.
* **FileStorage::APPEND** Open the file for appending.
:param encoding: Encoding of the file. Note that UTF-16 XML encoding is not supported currently and you should use 8-bit encoding instead of it.
The full constructor opens the file. Alternatively you can use the default constructor and then call :ocv:func:`FileStorage::open`.
FileStorage::open
-----------------
Opens a file.
.. ocv:function:: bool FileStorage::open(const string& filename, int flags, const string& encoding=string())
See description of parameters in :ocv:func:`FileStorage::FileStorage`. The method calls :ocv:func:`FileStorage::release` before opening the file.
FileStorage::isOpened
---------------------
Checks whether the file is opened.
.. ocv:function:: bool FileStorage::isOpened() const
:returns: ``true`` if the object is associated with the current file and ``false`` otherwise.
It is a good practice to call this method after you tried to open a file.
FileStorage::release
--------------------
Closes the file and releases all the memory buffers.
.. ocv:function:: void FileStorage::release()
Call this method after all I/O operations with the storage are finished.
FileStorage::getFirstTopLevelNode
---------------------------------
Returns the first element of the top-level mapping.
.. ocv:function:: FileNode FileStorage::getFirstTopLevelNode() const
:returns: The first element of the top-level mapping.
FileStorage::root
-----------------
Returns the top-level mapping
.. ocv:function:: FileNode FileStorage::root(int streamidx=0) const
:param streamidx: Zero-based index of the stream. In most cases there is only one stream in the file. However, YAML supports multiple streams and so there can be several.
:returns: The top-level mapping.
FileStorage::operator[]
-----------------------
Returns the specified element of the top-level mapping.
.. ocv:function:: FileNode FileStorage::operator[](const string& nodename) const
.. ocv:function:: FileNode FileStorage::operator[](const char* nodename) const
:param nodename: Name of the file node.
:returns: Node with the given name.
FileStorage::operator*
----------------------
Returns the obsolete C FileStorage structure.
.. ocv:function:: CvFileStorage* FileStorage::operator *()
.. ocv:function:: const CvFileStorage* FileStorage::operator *() const
:returns: Pointer to the underlying C FileStorage structure
FileStorage::writeRaw
---------------------
Writes multiple numbers.
.. ocv:function:: void FileStorage::writeRaw( const string& fmt, const uchar* vec, size_t len )
:param fmt: Specification of each array element that has the following format ``([count]{'u'|'c'|'w'|'s'|'i'|'f'|'d'})...`` where the characters correspond to fundamental C++ types:
* **u** 8-bit unsigned number
* **c** 8-bit signed number
* **w** 16-bit unsigned number
* **s** 16-bit signed number
* **i** 32-bit signed number
* **f** single precision floating-point number
* **d** double precision floating-point number
* **r** pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements.
``count`` is the optional counter of values of a given type. For example, ``2if`` means that each array element is a structure of 2 integers, followed by a single-precision floating-point number. The equivalent notations of the above specification are ' ``iif`` ', ' ``2i1f`` ' and so forth. Other examples: ``u`` means that the array consists of bytes, and ``2d`` means the array consists of pairs of doubles.
:param vec: Pointer to the written array.
:param len: Number of the ``uchar`` elements to write.
Writes one or more numbers of the specified format to the currently written structure. Usually it is more convenient to use :ocv:func:`operator <<` instead of this method.
FileStorage::writeObj
---------------------
Writes the registered C structure (CvMat, CvMatND, CvSeq).
.. ocv:function:: void FileStorage::writeObj( const string& name, const void* obj )
:param name: Name of the written object.
:param obj: Pointer to the object.
See :ocv:cfunc:`Write` for details.
FileStorage::getDefaultObjectName
---------------------------------
Returns the normalized object name for the specified name of a file.
.. ocv:function:: static string FileStorage::getDefaultObjectName(const string& filename)
:param filename: Name of a file
:returns: The normalized object name.
operator <<
-----------
Writes data to a file storage.
.. ocv:function:: template<typename _Tp> FileStorage& operator << (FileStorage& fs, const _Tp& value)
.. ocv:function:: template<typename _Tp> FileStorage& operator << ( FileStorage& fs, const vector<_Tp>& vec )
:param fs: Opened file storage to write data.
:param value: Value to be written to the file storage.
:param vec: Vector of values to be written to the file storage.
It is the main function to write data to a file storage. See an example of its usage at the beginning of the section.
operator >>
-----------
Reads data from a file storage.
.. ocv:function:: template<typename _Tp> void operator >> (const FileNode& n, _Tp& value)
.. ocv:function:: template<typename _Tp> void operator >> (const FileNode& n, vector<_Tp>& vec)
.. ocv:function:: template<typename _Tp> FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value)
.. ocv:function:: template<typename _Tp> FileNodeIterator& operator >> (FileNodeIterator& it, vector<_Tp>& vec)
:param n: Node from which data will be read.
:param it: Iterator from which data will be read.
:param value: Value to be read from the file storage.
:param vec: Vector of values to be read from the file storage.
It is the main function to read data from a file storage. See an example of its usage at the beginning of the section.
FileNode
--------
.. ocv:class:: FileNode
The class ``FileNode`` represents each element of the file storage, be it a matrix, a matrix element or a top-level node, containing all the file content. That is, a file node may contain either a singe value (integer, floating-point value or a text string), or it can be a sequence of other file nodes, or it can be a mapping. Type of the file node can be determined using :ocv:func:`FileNode::type` method.
File Storage Node class. The node is used to store each and every element of the file storage opened for reading. When XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of nodes. Each node can be a “leaf” that is contain a single number or a string, or be a collection of other nodes. There can be named collections (mappings) where each element has a name and it is accessed by a name, and ordered collections (sequences) where elements do not have names but rather accessed by index. Type of the file node can be determined using :ocv:func:`FileNode::type` method.
Note that file nodes are only used for navigating file storages opened for reading. When a file storage is opened for writing, no data is stored in memory after it is written.
FileNode::FileNode
------------------
The constructors.
.. ocv:function:: FileNode::FileNode()
.. ocv:function:: FileNode::FileNode(const CvFileStorage* fs, const CvFileNode* node)
.. ocv:function:: FileNode::FileNode(const FileNode& node)
:param fs: Pointer to the obsolete file storage structure.
:param node: File node to be used as initialization for the created file node.
These constructors are used to create a default file node, construct it from obsolete structures or from the another file node.
FileNode::operator[]
--------------------
Returns element of a mapping node or a sequence node.
.. ocv:function:: FileNode FileNode::operator[](const string& nodename) const
.. ocv:function:: FileNode FileNode::operator[](const char* nodename) const
.. ocv:function:: FileNode FileNode::operator[](int i) const
:param nodename: Name of an element in the mapping node.
:param i: Index of an element in the sequence node.
:returns: Returns the element with the given identifier.
FileNode::type
--------------
Returns type of the node.
.. ocv:function:: int FileNode::type() const
:returns: Type of the node. Possible values are:
* **FileNode::NONE** Empty node.
* **FileNode::INT** Integer.
* **FileNode::REAL** Floating-point number.
* **FileNode::FLOAT** Synonym or ``REAL``.
* **FileNode::STR** Text string in UTF-8 encoding.
* **FileNode::STRING** Synonym for ``STR``.
* **FileNode::REF** Integer of type ``size_t``. Typically used for storing complex dynamic structures where some elements reference the others.
* **FileNode::SEQ** Sequence.
* **FileNode::MAP** Mapping.
* **FileNode::FLOW** Compact representation of a sequence or mapping. Used only by the YAML writer.
* **FileNode::USER** Registered object (e.g. a matrix).
* **FileNode::EMPTY** Empty structure (sequence or mapping).
* **FileNode::NAMED** The node has a name (i.e. it is an element of a mapping).
FileNode::empty
---------------
Checks whether the node is empty.
.. ocv:function:: bool FileNode::empty() const
:returns: ``true`` if the node is empty.
FileNode::isNone
----------------
Checks whether the node is a "none" object
.. ocv:function:: bool FileNode::isNone() const
:returns: ``true`` if the node is a "none" object.
FileNode::isSeq
---------------
Checks whether the node is a sequence.
.. ocv:function:: bool FileNode::isSeq() const
:returns: ``true`` if the node is a sequence.
FileNode::isMap
---------------
Checks whether the node is a mapping.
.. ocv:function:: bool FileNode::isMap() const
:returns: ``true`` if the node is a mapping.
FileNode::isInt
---------------
Checks whether the node is an integer.
.. ocv:function:: bool FileNode::isInt() const
:returns: ``true`` if the node is an integer.
FileNode::isReal
----------------
Checks whether the node is a floating-point number.
.. ocv:function:: bool FileNode::isReal() const
:returns: ``true`` if the node is a floating-point number.
FileNode::isString
------------------
Checks whether the node is a text string.
.. ocv:function:: bool FileNode::isString() const
:returns: ``true`` if the node is a text string.
FileNode::isNamed
-----------------
Checks whether the node has a name.
.. ocv:function:: bool FileNode::isNamed() const
:returns: ``true`` if the node has a name.
FileNode::name
--------------
Returns the node name.
.. ocv:function:: string FileNode::name() const
:returns: The node name or an empty string if the node is nameless.
FileNode::size
--------------
Returns the number of elements in the node.
.. ocv:function:: size_t FileNode::size() const
:returns: The number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
FileNode::operator int
----------------------
Returns the node content as an integer.
.. ocv:function:: FileNode::operator int() const
:returns: The node content as an integer. If the node stores a floating-point number, it is rounded.
FileNode::operator float
------------------------
Returns the node content as float.
.. ocv:function:: FileNode::operator float() const
:returns: The node content as float.
FileNode::operator double
-------------------------
Returns the node content as double.
.. ocv:function:: FileNode::operator double() const
:returns: The node content as double.
FileNode::operator string
-------------------------
Returns the node content as text string.
.. ocv:function:: FileNode::operator string() const
:returns: The node content as a text string.
FileNode::operator*
-------------------
Returns pointer to the underlying obsolete file node structure.
.. ocv:function:: CvFileNode* FileNode::operator *()
:returns: Pointer to the underlying obsolete file node structure.
FileNode::begin
---------------
Returns the iterator pointing to the first node element.
.. ocv:function:: FileNodeIterator FileNode::begin() const
:returns: Iterator pointing to the first node element.
FileNode::end
-------------
Returns the iterator pointing to the element following the last node element.
.. ocv:function:: FileNodeIterator FileNode::end() const
:returns: Iterator pointing to the element following the last node element.
FileNode::readRaw
-----------------
Reads node elements to the buffer with the specified format.
.. ocv:function:: void FileNode::readRaw( const string& fmt, uchar* vec, size_t len ) const
:param fmt: Specification of each array element. It has the same format as in :ocv:func:`FileStorage::writeRaw`.
:param vec: Pointer to the destination array.
:param len: Number of elements to read. If it is greater than number of remaining elements then all of them will be read.
Usually it is more convenient to use :ocv:func:`operator >>` instead of this method.
FileNode::readObj
-----------------
Reads the registered object.
.. ocv:function:: void* FileNode::readObj() const
:returns: Pointer to the read object.
See :ocv:cfunc:`Read` for details.
FileNodeIterator
----------------
.. ocv:class:: FileNodeIterator
The class ``FileNodeIterator`` is used to iterate through sequences and mappings. A standard STL notation, with ``node.begin()``, ``node.end()`` denoting the beginning and the end of a sequence, stored in ``node``. See the data reading sample in the beginning of the section.
FileNodeIterator::FileNodeIterator
----------------------------------
The constructors.
.. ocv:function:: FileNodeIterator::FileNodeIterator()
.. ocv:function:: FileNodeIterator::FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0)
.. ocv:function:: FileNodeIterator::FileNodeIterator(const FileNodeIterator& it)
:param fs: File storage for the iterator.
:param node: File node for the iterator.
:param ofs: Index of the element in the node. The created iterator will point to this element.
:param it: Iterator to be used as initialization for the created iterator.
These constructors are used to create a default iterator, set it to specific element in a file node or construct it from another iterator.
FileNodeIterator::operator*
---------------------------
Returns the currently observed element.
.. ocv:function:: FileNode FileNodeIterator::operator *() const
:returns: Currently observed element.
FileNodeIterator::operator->
----------------------------
Accesses methods of the currently observed element.
.. ocv:function:: FileNode FileNodeIterator::operator ->() const
FileNodeIterator::operator ++
-----------------------------
Moves iterator to the next node.
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator ++ ()
.. ocv:function:: FileNodeIterator FileNodeIterator::operator ++ (int)
FileNodeIterator::operator --
-----------------------------
Moves iterator to the previous node.
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator -- ()
.. ocv:function:: FileNodeIterator FileNodeIterator::operator -- (int)
FileNodeIterator::operator +=
-----------------------------
Moves iterator forward by the specified offset.
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator += (int ofs)
:param ofs: Offset (possibly negative) to move the iterator.
FileNodeIterator::operator -=
-----------------------------
Moves iterator backward by the specified offset (possibly negative).
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator -= (int ofs)
:param ofs: Offset (possibly negative) to move the iterator.
FileNodeIterator::readRaw
-------------------------
Reads node elements to the buffer with the specified format.
.. ocv:function:: FileNodeIterator& FileNodeIterator::readRaw( const string& fmt, uchar* vec, size_t maxCount=(size_t)INT_MAX )
:param fmt: Specification of each array element. It has the same format as in :ocv:func:`FileStorage::writeRaw`.
:param vec: Pointer to the destination array.
:param maxCount: Number of elements to read. If it is greater than number of remaining elements then all of them will be read.
Usually it is more convenient to use :ocv:func:`operator >>` instead of this method.
+21 -2
View File
@@ -218,6 +218,8 @@ CV_EXPORTS void setNumThreads(int nthreads);
CV_EXPORTS int getNumThreads();
CV_EXPORTS int getThreadNum();
CV_EXPORTS_W const std::string& getBuildInformation();
//! Returns the number of ticks.
/*!
@@ -1944,6 +1946,9 @@ public:
MSize size;
MStep step;
protected:
void initEmpty();
};
@@ -2727,7 +2732,6 @@ public:
static MatExpr eye(Size size);
//! some more overriden methods
Mat_ reshape(int _rows) const;
Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
Mat_ operator()( const Rect& roi ) const;
@@ -4273,6 +4277,7 @@ public:
void set(const string& name, bool value);
void set(const string& name, const string& value);
void set(const string& name, const Mat& value);
void set(const string& name, const vector<Mat>& value);
void set(const string& name, const Ptr<Algorithm>& value);
void set(const char* name, int value);
@@ -4280,6 +4285,7 @@ public:
void set(const char* name, bool value);
void set(const char* name, const string& value);
void set(const char* name, const Mat& value);
void set(const char* name, const vector<Mat>& value);
void set(const char* name, const Ptr<Algorithm>& value);
string paramHelp(const string& name) const;
@@ -4347,6 +4353,11 @@ public:
Mat (Algorithm::*getter)()=0,
void (Algorithm::*setter)(const Mat&)=0,
const string& help=string());
void addParam(Algorithm& algo, const char* name,
vector<Mat>& value, bool readOnly=false,
vector<Mat> (Algorithm::*getter)()=0,
void (Algorithm::*setter)(const vector<Mat>&)=0,
const string& help=string());
void addParam(Algorithm& algo, const char* name,
Ptr<Algorithm>& value, bool readOnly=false,
Ptr<Algorithm> (Algorithm::*getter)()=0,
@@ -4359,7 +4370,7 @@ protected:
struct CV_EXPORTS Param
{
enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, ALGORITHM=5 };
enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6 };
Param();
Param(int _type, bool _readonly, int _offset,
@@ -4414,6 +4425,14 @@ template<> struct ParamType<Mat>
enum { type = Param::MAT };
};
template<> struct ParamType<vector<Mat> >
{
typedef const vector<Mat>& const_param_type;
typedef vector<Mat> member_type;
enum { type = Param::MAT_VECTOR };
};
template<> struct ParamType<Algorithm>
{
typedef const Ptr<Algorithm>& const_param_type;
@@ -59,7 +59,7 @@ namespace cv
// It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile
template <bool expr> struct StaticAssert;
template <> struct StaticAssert<true> {static __CV_GPU_HOST_DEVICE__ void check(){}};
template <> struct StaticAssert<true> {static __CV_GPU_HOST_DEVICE__ void check(){}};
template<typename T> struct DevPtr
{
+26 -47
View File
@@ -55,53 +55,55 @@ namespace cv
//////////////////////////////// Mat ////////////////////////////////
inline Mat::Mat()
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
inline void Mat::initEmpty()
{
flags = MAGIC_VAL;
dims = rows = cols = 0;
data = datastart = dataend = datalimit = 0;
refcount = 0;
allocator = 0;
}
inline Mat::Mat() : size(&rows)
{
initEmpty();
}
inline Mat::Mat(int _rows, int _cols, int _type)
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
inline Mat::Mat(int _rows, int _cols, int _type) : size(&rows)
{
initEmpty();
create(_rows, _cols, _type);
}
inline Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s)
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
inline Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s) : size(&rows)
{
initEmpty();
create(_rows, _cols, _type);
*this = _s;
}
inline Mat::Mat(Size _sz, int _type)
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
inline Mat::Mat(Size _sz, int _type) : size(&rows)
{
initEmpty();
create( _sz.height, _sz.width, _type );
}
inline Mat::Mat(Size _sz, int _type, const Scalar& _s)
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
inline Mat::Mat(Size _sz, int _type, const Scalar& _s) : size(&rows)
{
initEmpty();
create(_sz.height, _sz.width, _type);
*this = _s;
}
inline Mat::Mat(int _dims, const int* _sz, int _type)
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
inline Mat::Mat(int _dims, const int* _sz, int _type) : size(&rows)
{
initEmpty();
create(_dims, _sz, _type);
}
inline Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s)
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
inline Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s) : size(&rows)
{
initEmpty();
create(_dims, _sz, _type);
*this = _s;
}
@@ -169,27 +171,6 @@ inline Mat::Mat(Size _sz, int _type, void* _data, size_t _step)
}
inline Mat::Mat(const CvMat* m, bool copyData)
: flags(MAGIC_VAL + (m->type & (CV_MAT_TYPE_MASK|CV_MAT_CONT_FLAG))),
dims(2), rows(m->rows), cols(m->cols), data(m->data.ptr), refcount(0),
datastart(m->data.ptr), allocator(0), size(&rows)
{
if( !copyData )
{
size_t esz = CV_ELEM_SIZE(m->type), minstep = cols*esz, _step = m->step;
if( _step == 0 )
_step = minstep;
datalimit = datastart + _step*rows;
dataend = datalimit - _step + minstep;
step[0] = _step; step[1] = esz;
}
else
{
data = datastart = dataend = 0;
Mat(m->rows, m->cols, m->type, m->data.ptr, m->step).copyTo(*this);
}
}
template<typename _Tp> inline Mat::Mat(const vector<_Tp>& vec, bool copyData)
: flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG),
dims(2), rows((int)vec.size()), cols(1), data(0), refcount(0),
@@ -338,8 +319,9 @@ inline Mat Mat::colRange(const Range& r) const
inline Mat Mat::diag(const Mat& d)
{
CV_Assert( d.cols == 1 );
Mat m(d.rows, d.rows, d.type(), Scalar(0)), md = m.diag();
CV_Assert( d.cols == 1 || d.rows == 1 );
int len = d.rows + d.cols - 1;
Mat m(len, len, d.type(), Scalar(0)), md = m.diag();
d.copyTo(md);
return m;
}
@@ -969,9 +951,6 @@ template<typename _Tp> inline int Mat_<_Tp>::channels() const
template<typename _Tp> inline size_t Mat_<_Tp>::stepT(int i) const { return step.p[i]/elemSize(); }
template<typename _Tp> inline size_t Mat_<_Tp>::step1(int i) const { return step.p[i]/elemSize1(); }
template<typename _Tp> inline Mat_<_Tp> Mat_<_Tp>::reshape(int _rows) const
{ return Mat_<_Tp>(Mat::reshape(0,_rows)); }
template<typename _Tp> inline Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright )
{ return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); }
@@ -2277,7 +2277,7 @@ public:
{ set((_Tp*)&vec.val[0], n, true); }
Vector(const std::vector<_Tp>& vec, bool _copyData=false)
{ set((_Tp*)&vec[0], vec.size(), _copyData); }
{ set(!vec.empty() ? (_Tp*)&vec[0] : 0, vec.size(), _copyData); }
Vector(const Vector& d) { *this = d; }
@@ -2445,14 +2445,17 @@ dot(const Vector<_Tp>& v1, const Vector<_Tp>& v2)
assert(v1.size() == v2.size());
_Tw s = 0;
const _Tp *ptr1 = &v1[0], *ptr2 = &v2[0];
#if CV_ENABLE_UNROLLED
for(; i <= n - 4; i += 4 )
s += (_Tw)ptr1[i]*ptr2[i] + (_Tw)ptr1[i+1]*ptr2[i+1] +
(_Tw)ptr1[i+2]*ptr2[i+2] + (_Tw)ptr1[i+3]*ptr2[i+3];
#endif
for( ; i < n; i++ )
s += (_Tw)ptr1[i]*ptr2[i];
if( n > 0 )
{
const _Tp *ptr1 = &v1[0], *ptr2 = &v2[0];
#if CV_ENABLE_UNROLLED
for(; i <= n - 4; i += 4 )
s += (_Tw)ptr1[i]*ptr2[i] + (_Tw)ptr1[i+1]*ptr2[i+1] +
(_Tw)ptr1[i+2]*ptr2[i+2] + (_Tw)ptr1[i+3]*ptr2[i+3];
#endif
for( ; i < n; i++ )
s += (_Tw)ptr1[i]*ptr2[i];
}
return s;
}
@@ -2834,29 +2837,27 @@ public:
{
int _fmt = DataType<_Tp>::fmt;
char fmt[] = { (char)((_fmt>>8)+'1'), (char)_fmt, '\0' };
fs->writeRaw( string(fmt), (uchar*)&vec[0], vec.size()*sizeof(_Tp) );
fs->writeRaw( string(fmt), !vec.empty() ? (uchar*)&vec[0] : 0, vec.size()*sizeof(_Tp) );
}
FileStorage* fs;
};
template<typename _Tp> static inline void write( FileStorage& fs, const vector<_Tp>& vec )
{
VecWriterProxy<_Tp, DataType<_Tp>::fmt != 0> w(&fs);
w(vec);
}
template<typename _Tp> static inline FileStorage&
operator << ( FileStorage& fs, const vector<_Tp>& vec )
template<typename _Tp> static inline void write( FileStorage& fs, const string& name,
const vector<_Tp>& vec )
{
VecWriterProxy<_Tp, DataType<_Tp>::generic_type == 0> w(&fs);
w(vec);
return fs;
}
WriteStructContext ws(fs, name, CV_NODE_SEQ+(DataType<_Tp>::fmt != 0 ? CV_NODE_FLOW : 0));
write(fs, vec);
}
CV_EXPORTS_W void write( FileStorage& fs, const string& name, const Mat& value );
CV_EXPORTS void write( FileStorage& fs, const string& name, const SparseMat& value );
template<typename _Tp> static inline FileStorage& operator << (FileStorage& fs, const _Tp& value)
{
if( !fs.isOpened() )
@@ -2893,7 +2894,7 @@ inline size_t FileNode::size() const
{
int t = type();
return t == MAP ? ((CvSet*)node->data.map)->active_count :
t == SEQ ? node->data.seq->total : node != 0;
t == SEQ ? node->data.seq->total : (size_t)!isNone();
}
inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; }
@@ -2956,7 +2957,7 @@ static inline void read(const FileNode& node, string& value, const string& defau
}
CV_EXPORTS_W void read(const FileNode& node, Mat& mat, const Mat& default_mat=Mat() );
CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat=SparseMat() );
CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat=SparseMat() );
inline FileNode::operator int() const
{
@@ -3011,10 +3012,10 @@ public:
size_t remaining = it->remaining, cn = DataType<_Tp>::channels;
int _fmt = DataType<_Tp>::fmt;
char fmt[] = { (char)((_fmt>>8)+'1'), (char)_fmt, '\0' };
size_t remaining1 = remaining/cn;
count = count < remaining1 ? count : remaining1;
size_t remaining1 = remaining/cn;
count = count < remaining1 ? count : remaining1;
vec.resize(count);
it->readRaw( string(fmt), (uchar*)&vec[0], count*sizeof(_Tp) );
it->readRaw( string(fmt), !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp) );
}
FileNodeIterator* it;
};
@@ -3027,9 +3028,15 @@ read( FileNodeIterator& it, vector<_Tp>& vec, size_t maxCount=(size_t)INT_MAX )
}
template<typename _Tp> static inline void
read( FileNode& node, vector<_Tp>& vec, const vector<_Tp>& default_value=vector<_Tp>() )
read( const FileNode& node, vector<_Tp>& vec, const vector<_Tp>& default_value=vector<_Tp>() )
{
read( node.begin(), vec );
if(!node.node)
vec = default_value;
else
{
FileNodeIterator it = node.begin();
read( it, vec );
}
}
inline FileNodeIterator FileNode::begin() const
+1 -1
View File
@@ -32,5 +32,5 @@ PERF_TEST_P( Size_DepthSrc_DepthDst_Channels_alpha, convertTo,
TEST_CYCLE() src.convertTo(dst, depthDst, alpha);
SANITY_CHECK(dst);
SANITY_CHECK(dst, 1e-12);
}
+1 -1
View File
@@ -32,5 +32,5 @@ PERF_TEST_P( Size_SrcDepth_DstChannels, merge,
Mat dst;
TEST_CYCLE() merge( (vector<Mat> &)mv, dst );
SANITY_CHECK(dst);
SANITY_CHECK(dst, 1e-12);
}
+1 -1
View File
@@ -29,5 +29,5 @@ PERF_TEST_P( Size_Depth_Channels, split,
TEST_CYCLE() split(m, (vector<Mat>&)mv);
SANITY_CHECK(mv);
SANITY_CHECK(mv, 1e-12);
}
+59 -7
View File
@@ -149,17 +149,21 @@ struct CV_EXPORTS AlgorithmInfoData
};
static sorted_vector<string, Algorithm::Constructor> alglist;
static sorted_vector<string, Algorithm::Constructor>& alglist()
{
static sorted_vector<string, Algorithm::Constructor> alglist_var;
return alglist_var;
}
void Algorithm::getList(vector<string>& algorithms)
{
alglist.get_keys(algorithms);
alglist().get_keys(algorithms);
}
Ptr<Algorithm> Algorithm::_create(const string& name)
{
Algorithm::Constructor c = 0;
if( !alglist.find(name, c) )
if( !alglist().find(name, c) )
return Ptr<Algorithm>();
return c();
}
@@ -202,6 +206,11 @@ void Algorithm::set(const string& name, const Mat& value)
info()->set(this, name.c_str(), ParamType<Mat>::type, &value);
}
void Algorithm::set(const string& name, const vector<Mat>& value)
{
info()->set(this, name.c_str(), ParamType<vector<Mat> >::type, &value);
}
void Algorithm::set(const string& name, const Ptr<Algorithm>& value)
{
info()->set(this, name.c_str(), ParamType<Algorithm>::type, &value);
@@ -232,6 +241,11 @@ void Algorithm::set(const char* name, const Mat& value)
info()->set(this, name, ParamType<Mat>::type, &value);
}
void Algorithm::set(const char* name, const vector<Mat>& value)
{
info()->set(this, name, ParamType<vector<Mat> >::type, &value);
}
void Algorithm::set(const char* name, const Ptr<Algorithm>& value)
{
info()->set(this, name, ParamType<Algorithm>::type, &value);
@@ -272,7 +286,7 @@ AlgorithmInfo::AlgorithmInfo(const string& _name, Algorithm::Constructor create)
{
data = new AlgorithmInfoData;
data->_name = _name;
alglist.add(_name, create);
alglist().add(_name, create);
}
AlgorithmInfo::~AlgorithmInfo()
@@ -298,6 +312,8 @@ void AlgorithmInfo::write(const Algorithm* algo, FileStorage& fs) const
cv::write(fs, pname, algo->get<string>(pname));
else if( p.type == Param::MAT )
cv::write(fs, pname, algo->get<Mat>(pname));
else if( p.type == Param::MAT_VECTOR )
cv::write(fs, pname, algo->get<vector<Mat> >(pname));
else if( p.type == Param::ALGORITHM )
{
WriteStructContext ws(fs, pname, CV_NODE_MAP);
@@ -317,7 +333,7 @@ void AlgorithmInfo::read(Algorithm* algo, const FileNode& fn) const
{
const Param& p = data->params.vec[i].second;
const string& pname = data->params.vec[i].first;
FileNode n = fn[pname];
const FileNode n = fn[pname];
if( n.empty() )
continue;
if( p.type == Param::INT )
@@ -331,9 +347,15 @@ void AlgorithmInfo::read(Algorithm* algo, const FileNode& fn) const
else if( p.type == Param::MAT )
{
Mat m;
cv::read(fn, m);
cv::read(n, m);
algo->set(pname, m);
}
else if( p.type == Param::MAT_VECTOR )
{
vector<Mat> mv;
cv::read(n, mv);
algo->set(pname, mv);
}
else if( p.type == Param::ALGORITHM )
{
Ptr<Algorithm> nestedAlgo = Algorithm::_create((string)n["name"]);
@@ -358,6 +380,7 @@ union GetSetParam
double (Algorithm::*get_double)() const;
string (Algorithm::*get_string)() const;
Mat (Algorithm::*get_mat)() const;
vector<Mat> (Algorithm::*get_mat_vector)() const;
Ptr<Algorithm> (Algorithm::*get_algo)() const;
void (Algorithm::*set_int)(int);
@@ -365,6 +388,7 @@ union GetSetParam
void (Algorithm::*set_double)(double);
void (Algorithm::*set_string)(const string&);
void (Algorithm::*set_mat)(const Mat&);
void (Algorithm::*set_mat_vector)(const vector<Mat>&);
void (Algorithm::*set_algo)(const Ptr<Algorithm>&);
};
@@ -436,6 +460,16 @@ void AlgorithmInfo::set(Algorithm* algo, const char* name, int argType, const vo
else
*(Mat*)((uchar*)algo + p->offset) = val;
}
else if( argType == Param::MAT_VECTOR )
{
CV_Assert( p->type == Param::MAT_VECTOR );
const vector<Mat>& val = *(const vector<Mat>*)value;
if( p->setter )
(algo->*f.set_mat_vector)(val);
else
*(vector<Mat>*)((uchar*)algo + p->offset) = val;
}
else if( argType == Param::ALGORITHM )
{
CV_Assert( p->type == Param::ALGORITHM );
@@ -505,6 +539,13 @@ void AlgorithmInfo::get(const Algorithm* algo, const char* name, int argType, vo
*(Mat*)value = p->getter ? (algo->*f.get_mat)() :
*(Mat*)((uchar*)algo + p->offset);
}
else if( argType == Param::MAT_VECTOR )
{
CV_Assert( p->type == Param::MAT_VECTOR );
*(vector<Mat>*)value = p->getter ? (algo->*f.get_mat_vector)() :
*(vector<Mat>*)((uchar*)algo + p->offset);
}
else if( argType == Param::ALGORITHM )
{
CV_Assert( p->type == Param::ALGORITHM );
@@ -548,7 +589,8 @@ void AlgorithmInfo::addParam_(Algorithm& algo, const char* name, int argType,
{
CV_Assert( argType == Param::INT || argType == Param::BOOLEAN ||
argType == Param::REAL || argType == Param::STRING ||
argType == Param::MAT || argType == Param::ALGORITHM );
argType == Param::MAT || argType == Param::MAT_VECTOR ||
argType == Param::ALGORITHM );
data->params.add(string(name), Param(argType, readOnly,
(int)((size_t)value - (size_t)(void*)&algo),
getter, setter, help));
@@ -604,6 +646,16 @@ void AlgorithmInfo::addParam(Algorithm& algo, const char* name,
addParam_(algo, name, ParamType<Mat>::type, &value, readOnly,
(Algorithm::Getter)getter, (Algorithm::Setter)setter, help);
}
void AlgorithmInfo::addParam(Algorithm& algo, const char* name,
vector<Mat>& value, bool readOnly,
vector<Mat> (Algorithm::*getter)(),
void (Algorithm::*setter)(const vector<Mat>&),
const string& help)
{
addParam_(algo, name, ParamType<vector<Mat> >::type, &value, readOnly,
(Algorithm::Getter)getter, (Algorithm::Setter)setter, help);
}
void AlgorithmInfo::addParam(Algorithm& algo, const char* name,
Ptr<Algorithm>& value, bool readOnly,
+1
View File
@@ -47,6 +47,7 @@ namespace cv
// 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 )
#endif
/****************************************************************************************\
+15 -13
View File
@@ -2032,8 +2032,9 @@ template<> struct mat_type_assotiations<CV_32S>
static const type max_allowable = INT_MAX;
};
// inclusive maxVal !!!
template<int depth>
bool chackIntegerRang(cv::Mat src, Point& bad_pt, int minVal, int maxVal, double& bad_value)
bool checkIntegerRange(cv::Mat src, Point& bad_pt, int minVal, int maxVal, double& bad_value)
{
typedef mat_type_assotiations<depth> type_ass;
@@ -2041,7 +2042,7 @@ bool chackIntegerRang(cv::Mat src, Point& bad_pt, int minVal, int maxVal, double
{
return true;
}
else if (minVal >= type_ass::max_allowable || maxVal <= type_ass::min_allowable || maxVal <= minVal)
else if (minVal > type_ass::max_allowable || maxVal < type_ass::min_allowable || maxVal < minVal)
{
bad_pt = cv::Point(0,0);
return false;
@@ -2051,7 +2052,7 @@ bool chackIntegerRang(cv::Mat src, Point& bad_pt, int minVal, int maxVal, double
for (int j = 0; j < as_one_channel.rows; ++j)
for (int i = 0; i < as_one_channel.cols; ++i)
{
if (as_one_channel.at<typename type_ass::type>(j ,i) <= minVal || as_one_channel.at<typename type_ass::type>(j ,i) >= maxVal)
if (as_one_channel.at<typename type_ass::type>(j ,i) < minVal || as_one_channel.at<typename type_ass::type>(j ,i) > maxVal)
{
bad_pt.y = j ;
bad_pt.x = i % src.channels();
@@ -2064,15 +2065,15 @@ bool chackIntegerRang(cv::Mat src, Point& bad_pt, int minVal, int maxVal, double
return true;
}
typedef bool (*check_pange_function)(cv::Mat src, Point& bad_pt, int minVal, int maxVal, double& bad_value);
typedef bool (*check_range_function)(cv::Mat src, Point& bad_pt, int minVal, int maxVal, double& bad_value);
check_pange_function check_range_functions[] =
check_range_function check_range_functions[] =
{
&chackIntegerRang<CV_8U>,
&chackIntegerRang<CV_8S>,
&chackIntegerRang<CV_16U>,
&chackIntegerRang<CV_16S>,
&chackIntegerRang<CV_32S>
&checkIntegerRange<CV_8U>,
&checkIntegerRange<CV_8S>,
&checkIntegerRange<CV_16U>,
&checkIntegerRange<CV_16S>,
&checkIntegerRange<CV_32S>
};
bool checkRange(InputArray _src, bool quiet, Point* pt, double minVal, double maxVal)
@@ -2102,8 +2103,9 @@ bool checkRange(InputArray _src, bool quiet, Point* pt, double minVal, double ma
if (depth < CV_32F)
{
int minVali = cvFloor(minVal);
int maxVali = cvCeil(maxVal);
// see "Bug #1784"
int minVali = minVal<(-INT_MAX - 1) ? (-INT_MAX - 1) : cvFloor(minVal);
int maxVali = maxVal>INT_MAX ? INT_MAX : cvCeil(maxVal) - 1; // checkIntegerRang() use inclusive maxVal
(check_range_functions[depth])(src, badPt, minVali, maxVali, badValue);
}
@@ -2487,7 +2489,7 @@ double cv::solvePoly( InputArray _coeffs0, OutputArray _roots0, int maxIters )
for( i = 0; i < n; i++ )
{
p = roots[i];
C num = coeffs[n], denom = 1;
C num = coeffs[n], denom = coeffs[n];
for( j = 0; j < n; j++ )
{
num = num*p + coeffs[n-j-1];
+51 -1
View File
@@ -2098,7 +2098,7 @@ void cv::calcCovarMatrix( const Mat* data, int nsamples, Mat& covar, Mat& _mean,
{
CV_Assert( data && nsamples > 0 );
Size size = data[0].size();
int sz = size.width*size.height, esz = (int)data[0].elemSize();
int sz = size.width * size.height, esz = (int)data[0].elemSize();
int type = data[0].type();
Mat mean;
ctype = std::max(std::max(CV_MAT_DEPTH(ctype >= 0 ? ctype : type), _mean.depth()), CV_32F);
@@ -2116,6 +2116,7 @@ void cv::calcCovarMatrix( const Mat* data, int nsamples, Mat& covar, Mat& _mean,
}
Mat _data(nsamples, sz, type);
for( int i = 0; i < nsamples; i++ )
{
CV_Assert( data[i].size() == size && data[i].type() == type );
@@ -2135,6 +2136,55 @@ void cv::calcCovarMatrix( const Mat* data, int nsamples, Mat& covar, Mat& _mean,
void cv::calcCovarMatrix( InputArray _data, OutputArray _covar, InputOutputArray _mean, int flags, int ctype )
{
if(_data.kind() == _InputArray::STD_VECTOR_MAT)
{
std::vector<cv::Mat> src;
_data.getMatVector(src);
CV_Assert( src.size() > 0 );
Size size = src[0].size();
int type = src[0].type();
ctype = std::max(std::max(CV_MAT_DEPTH(ctype >= 0 ? ctype : type), _mean.depth()), CV_32F);
Mat _data(static_cast<int>(src.size()), size.area(), type);
int i = 0;
for(vector<cv::Mat>::iterator each = src.begin(); each != src.end(); each++, i++ )
{
CV_Assert( (*each).size() == size && (*each).type() == type );
Mat dataRow(size.height, size.width, type, _data.ptr(i));
(*each).copyTo(dataRow);
}
Mat mean;
if( (flags & CV_COVAR_USE_AVG) != 0 )
{
CV_Assert( _mean.size() == size );
if( mean.type() != ctype )
{
mean = _mean.getMat();
_mean.create(mean.size(), ctype);
Mat tmp = _mean.getMat();
mean.convertTo(tmp, ctype);
mean = tmp;
}
mean = _mean.getMat().reshape(1, 1);
}
calcCovarMatrix( _data, _covar, mean, (flags & ~(CV_COVAR_ROWS|CV_COVAR_COLS)) | CV_COVAR_ROWS, ctype );
if( (flags & CV_COVAR_USE_AVG) == 0 )
{
mean = mean.reshape(1, size.height);
mean.copyTo(_mean);
}
return;
}
Mat data = _data.getMat(), mean;
CV_Assert( ((flags & CV_COVAR_ROWS) != 0) ^ ((flags & CV_COVAR_COLS) != 0) );
bool takeRows = (flags & CV_COVAR_ROWS) != 0;
+65 -25
View File
@@ -262,10 +262,9 @@ void Mat::deallocate()
}
Mat::Mat(const Mat& m, const Range& rowRange, const Range& colRange)
: flags(0), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
Mat::Mat(const Mat& m, const Range& rowRange, const Range& colRange) : size(&rows)
{
initEmpty();
CV_Assert( m.dims >= 2 );
if( m.dims > 2 )
{
@@ -336,21 +335,19 @@ Mat::Mat(const Mat& m, const Rect& roi)
}
Mat::Mat(int _dims, const int* _sizes, int _type, void* _data, const size_t* _steps)
: flags(MAGIC_VAL|CV_MAT_TYPE(_type)), dims(0),
rows(0), cols(0), data((uchar*)_data), refcount(0),
datastart((uchar*)_data), dataend((uchar*)_data), datalimit((uchar*)_data),
allocator(0), size(&rows)
Mat::Mat(int _dims, const int* _sizes, int _type, void* _data, const size_t* _steps) : size(&rows)
{
initEmpty();
flags |= CV_MAT_TYPE(_type);
data = datastart = (uchar*)_data;
setSize(*this, _dims, _sizes, _steps, true);
finalizeHdr(*this);
}
Mat::Mat(const Mat& m, const Range* ranges)
: flags(m.flags), dims(0), rows(0), cols(0), data(0), refcount(0),
datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
Mat::Mat(const Mat& m, const Range* ranges) : size(&rows)
{
initEmpty();
int i, d = m.dims;
CV_Assert(ranges);
@@ -374,12 +371,13 @@ Mat::Mat(const Mat& m, const Range* ranges)
}
Mat::Mat(const CvMatND* m, bool copyData)
: flags(MAGIC_VAL|CV_MAT_TYPE(m->type)), dims(0), rows(0), cols(0),
data((uchar*)m->data.ptr), refcount(0),
datastart((uchar*)m->data.ptr), allocator(0),
size(&rows)
Mat::Mat(const CvMatND* m, bool copyData) : size(&rows)
{
initEmpty();
if( !m )
return;
data = datastart = m->data.ptr;
flags |= CV_MAT_TYPE(m->type);
int _sizes[CV_MAX_DIM];
size_t _steps[CV_MAX_DIM];
@@ -434,12 +432,45 @@ Mat Mat::diag(int d) const
return m;
}
Mat::Mat(const IplImage* img, bool copyData)
: flags(MAGIC_VAL), dims(2), rows(0), cols(0),
data(0), refcount(0), datastart(0), dataend(0), allocator(0), size(&rows)
Mat::Mat(const CvMat* m, bool copyData) : size(&rows)
{
initEmpty();
if( !m )
return;
if( !copyData )
{
flags = MAGIC_VAL + (m->type & (CV_MAT_TYPE_MASK|CV_MAT_CONT_FLAG));
dims = 2;
rows = m->rows;
cols = m->cols;
data = datastart = m->data.ptr;
size_t esz = CV_ELEM_SIZE(m->type), minstep = cols*esz, _step = m->step;
if( _step == 0 )
_step = minstep;
datalimit = datastart + _step*rows;
dataend = datalimit - _step + minstep;
step[0] = _step; step[1] = esz;
}
else
{
data = datastart = dataend = 0;
Mat(m->rows, m->cols, m->type, m->data.ptr, m->step).copyTo(*this);
}
}
Mat::Mat(const IplImage* img, bool copyData) : size(&rows)
{
initEmpty();
if( !img )
return;
dims = 2;
CV_DbgAssert(CV_IS_IMAGE(img) && img->imageData != 0);
int depth = IPL2CV_DEPTH(img->depth);
@@ -2428,8 +2459,9 @@ double cv::kmeans( InputArray _data, int K,
{
const int SPP_TRIALS = 3;
Mat data = _data.getMat();
int N = data.rows > 1 ? data.rows : data.cols;
int dims = (data.rows > 1 ? data.cols : 1)*data.channels();
bool isrow = data.rows == 1 && data.channels() > 1;
int N = !isrow ? data.rows : data.cols;
int dims = (!isrow ? data.cols : 1)*data.channels();
int type = data.depth();
attempts = std::max(attempts, 1);
@@ -2458,7 +2490,7 @@ double cv::kmeans( InputArray _data, int K,
}
int* labels = _labels.ptr<int>();
Mat centers(K, dims, type), old_centers(K, dims, type);
Mat centers(K, dims, type), old_centers(K, dims, type), temp(1, dims, type);
vector<int> counters(K);
vector<Vec2f> _box(dims);
Vec2f* box = &_box[0];
@@ -2502,7 +2534,7 @@ double cv::kmeans( InputArray _data, int K,
for( a = 0; a < attempts; a++ )
{
double max_center_shift = DBL_MAX;
for( iter = 0; iter < criteria.maxCount && max_center_shift > criteria.epsilon; iter++ )
for( iter = 0;; )
{
swap(centers, old_centers);
@@ -2579,13 +2611,17 @@ double cv::kmeans( InputArray _data, int K,
int farthest_i = -1;
float* new_center = centers.ptr<float>(k);
float* old_center = centers.ptr<float>(max_k);
float* _old_center = temp.ptr<float>(); // normalized
float scale = 1.f/counters[max_k];
for( j = 0; j < dims; j++ )
_old_center[j] = old_center[j]*scale;
for( i = 0; i < N; i++ )
{
if( labels[i] != max_k )
continue;
sample = data.ptr<float>(i);
double dist = normL2Sqr_(sample, old_center, dims);
double dist = normL2Sqr_(sample, _old_center, dims);
if( max_dist <= dist )
{
@@ -2596,6 +2632,7 @@ double cv::kmeans( InputArray _data, int K,
counters[max_k]--;
counters[k]++;
labels[farthest_i] = k;
sample = data.ptr<float>(farthest_i);
for( j = 0; j < dims; j++ )
@@ -2627,6 +2664,9 @@ double cv::kmeans( InputArray _data, int K,
}
}
}
if( ++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon )
break;
// assign labels
compactness = 0;
+7 -5
View File
@@ -2987,9 +2987,6 @@ cvWriteRawData( CvFileStorage* fs, const void* _data, int len, const char* dt )
CV_CHECK_OUTPUT_FILE_STORAGE( fs );
if( !data0 )
CV_Error( CV_StsNullPtr, "Null data pointer" );
if( len < 0 )
CV_Error( CV_StsOutOfRange, "Negative number of elements" );
@@ -2997,6 +2994,9 @@ cvWriteRawData( CvFileStorage* fs, const void* _data, int len, const char* dt )
if( !len )
return;
if( !data0 )
CV_Error( CV_StsNullPtr, "Null data pointer" );
if( fmt_pair_count == 1 )
{
@@ -3457,6 +3457,8 @@ icvReadMat( CvFileStorage* fs, CvFileNode* node )
mat = cvCreateMat( rows, cols, elem_type );
cvReadRawData( fs, data, mat->data.ptr, dt );
}
else if( rows == 0 && cols == 0 )
mat = cvCreateMatHeader( 0, 1, elem_type );
else
mat = cvCreateMatHeader( rows, cols, elem_type );
@@ -5195,7 +5197,7 @@ FileNodeIterator::FileNodeIterator()
FileNodeIterator::FileNodeIterator(const CvFileStorage* _fs,
const CvFileNode* _node, size_t _ofs)
{
if( _fs && _node )
if( _fs && _node && CV_NODE_TYPE(_node->tag) != CV_NODE_NONE )
{
int node_type = _node->tag & FileNode::TYPE_MASK;
fs = _fs;
@@ -5358,7 +5360,7 @@ void write( FileStorage& fs, const string& name, const SparseMat& value )
Ptr<CvSparseMat> mat = (CvSparseMat*)value;
cvWrite( *fs, name.size() ? name.c_str() : 0, mat );
}
WriteStructContext::WriteStructContext(FileStorage& _fs, const string& name,
int flags, const string& typeName) : fs(&_fs)
+3 -8
View File
@@ -1605,25 +1605,20 @@ struct BatchDistInvoker
// we handle both CV_32S and CV_32F cases with a single branch
int* distptr = (int*)dist->ptr(i);
int k, k0, k0_, j;
for( k0 = 0; k0 < K; k0++ )
if( nidxptr[k0] < 0 )
break;
k0_ = std::max(k0, 1);
int j, k;
for( j = 0; j < src2->rows; j++ )
{
int d = bufptr[j];
if( d < distptr[k0_-1] )
if( d < distptr[K-1] )
{
for( k = std::min(k0-1, K-2); k >= 0 && distptr[k] > d; k-- )
for( k = K-2; k >= 0 && distptr[k] > d; k-- )
{
nidxptr[k+1] = nidxptr[k];
distptr[k+1] = distptr[k];
}
nidxptr[k+1] = j + update;
distptr[k+1] = d;
k0_ = k0 = std::min(k0 + 1, K);
}
}
}
+52
View File
@@ -374,6 +374,46 @@ int getThreadNum(void)
#endif
}
#if ANDROID
static inline int getNumberOfCPUsImpl()
{
FILE* cpuPossible = fopen("/sys/devices/system/cpu/possible", "r");
if(!cpuPossible)
return 1;
char buf[2000]; //big enough for 1000 CPUs in worst possible configuration
char* pbuf = fgets(buf, sizeof(buf), cpuPossible);
fclose(cpuPossible);
if(!pbuf)
return 1;
//parse string of form "0-1,3,5-7,10,13-15"
int cpusAvailable = 0;
while(*pbuf)
{
const char* pos = pbuf;
bool range = false;
while(*pbuf && *pbuf != ',')
{
if(*pbuf == '-') range = true;
++pbuf;
}
if(*pbuf) *pbuf++ = 0;
if(!range)
++cpusAvailable;
else
{
int rstart = 0, rend = 0;
sscanf(pos, "%d-%d", &rstart, &rend);
cpusAvailable += rend - rstart + 1;
}
}
return cpusAvailable ? cpusAvailable : 1;
}
#endif
int getNumberOfCPUs(void)
{
#if defined WIN32 || defined _WIN32
@@ -381,6 +421,10 @@ int getNumberOfCPUs(void)
GetSystemInfo( &sysinfo );
return (int)sysinfo.dwNumberOfProcessors;
#elif ANDROID
static int ncpus = getNumberOfCPUsImpl();
printf("CPUS= %d\n", ncpus);
return ncpus;
#elif defined __linux__
return (int)sysconf( _SC_NPROCESSORS_ONLN );
#elif defined __APPLE__
@@ -410,6 +454,14 @@ int getNumberOfCPUs(void)
#endif
}
const std::string& getBuildInformation()
{
static std::string build_info =
#include "version_string.inc"
;
return build_info;
}
string format( const char* fmt, ... )
{
char buf[1 << 16];
+3
View File
@@ -1437,6 +1437,9 @@ protected:
Mat mask1;
Mat c, d;
rng.fill(a, RNG::UNIFORM, 0, 100);
rng.fill(b, RNG::UNIFORM, 0, 100);
// [-2,2) range means that the each generated random number
// will be one of -2, -1, 0, 1. Saturated to [0,255], it will become
// 0, 0, 0, 1 => the mask will be filled by ~25%.
+3 -3
View File
@@ -42,7 +42,7 @@
#include "test_precomp.hpp"
#include <time.h>
#include <limits>
using namespace cv;
using namespace std;
@@ -82,7 +82,7 @@ private:
void print_information(int right, int result);
};
CV_CountNonZeroTest::CV_CountNonZeroTest(): eps_32(1e-8f), eps_64(1e-16f), src(Mat()), current_type(-1) {}
CV_CountNonZeroTest::CV_CountNonZeroTest(): eps_32(std::numeric_limits<float>::min()), eps_64(std::numeric_limits<double>::min()), src(Mat()), current_type(-1) {}
CV_CountNonZeroTest::~CV_CountNonZeroTest() {}
void CV_CountNonZeroTest::generate_src_data(cv::Size size, int type)
@@ -252,4 +252,4 @@ void CV_CountNonZeroTest::run(int)
}
}
// TEST (Core_CountNonZero, accuracy) { CV_CountNonZeroTest test; test.safe_run(); }
TEST (Core_CountNonZero, accuracy) { CV_CountNonZeroTest test; test.safe_run(); }
-4
View File
@@ -146,7 +146,6 @@ void Core_EigenTest_Scalar_32::run(int)
float value = cv::randu<float>();
cv::Mat src(1, 1, CV_32FC1, Scalar::all((float)value));
test_values(src);
src.~Mat();
}
}
@@ -158,7 +157,6 @@ void Core_EigenTest_Scalar_64::run(int)
float value = cv::randu<float>();
cv::Mat src(1, 1, CV_64FC1, Scalar::all((double)value));
test_values(src);
src.~Mat();
}
}
@@ -401,8 +399,6 @@ bool Core_EigenTest::check_full(int type)
else src.at<double>(k, j) = src.at<double>(j, k) = cv::randu<double>();
if (!test_values(src)) return false;
src.~Mat();
}
return true;
+47
View File
@@ -377,6 +377,53 @@ protected:
TEST(Core_InputOutput, write_read_consistency) { Core_IOTest test; test.safe_run(); }
class CV_MiscIOTest : public cvtest::BaseTest
{
public:
CV_MiscIOTest() {}
~CV_MiscIOTest() {}
protected:
void run(int)
{
try
{
FileStorage fs("test.xml", FileStorage::WRITE);
vector<int> mi, mi2, mi3, mi4;
vector<Mat> mv, mv2, mv3, mv4;
Mat m(10, 9, CV_32F);
Mat empty;
randu(m, 0, 1);
mi3.push_back(5);
mv3.push_back(m);
fs << "mi" << mi;
fs << "mv" << mv;
fs << "mi3" << mi3;
fs << "mv3" << mv3;
fs << "empty" << empty;
fs.release();
fs.open("test.xml", FileStorage::READ);
fs["mi"] >> mi2;
fs["mv"] >> mv2;
fs["mi3"] >> mi4;
fs["mv3"] >> mv4;
fs["empty"] >> empty;
CV_Assert( mi2.empty() );
CV_Assert( mv2.empty() );
CV_Assert( norm(mi3, mi4, CV_C) == 0 );
CV_Assert( mv4.size() == 1 );
double n = norm(mv3[0], mv4[0], CV_C);
CV_Assert( n == 0 );
}
catch(...)
{
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
}
}
};
TEST(Core_InputOutput, misc) { CV_MiscIOTest test; test.safe_run(); }
/*class CV_BigMatrixIOTest : public cvtest::BaseTest
{
public:
+26 -10
View File
@@ -10,7 +10,7 @@ public:
Core_ReduceTest() {};
protected:
void run( int);
int checkOp( const Mat& src, int dstType, int opType, const Mat& opRes, int dim, double eps );
int checkOp( const Mat& src, int dstType, int opType, const Mat& opRes, int dim );
int checkCase( int srcType, int dstType, int dim, Size sz );
int checkDim( int dim, Size sz );
int checkSize( Size sz );
@@ -80,7 +80,7 @@ void getMatTypeStr( int type, string& str)
type == CV_64FC1 ? "CV_64FC1" : "unsupported matrix type";
}
int Core_ReduceTest::checkOp( const Mat& src, int dstType, int opType, const Mat& opRes, int dim, double eps )
int Core_ReduceTest::checkOp( const Mat& src, int dstType, int opType, const Mat& opRes, int dim )
{
int srcType = src.type();
bool support = false;
@@ -117,12 +117,30 @@ int Core_ReduceTest::checkOp( const Mat& src, int dstType, int opType, const Mat
}
if( !support )
return cvtest::TS::OK;
double eps = 0.0;
if ( opType == CV_REDUCE_SUM || opType == CV_REDUCE_AVG )
{
if ( dstType == CV_32F )
eps = 1.e-5;
else if( dstType == CV_64F )
eps = 1.e-8;
else if ( dstType == CV_32S )
eps = 0.6;
}
assert( opRes.type() == CV_64FC1 );
Mat _dst, dst;
Mat _dst, dst, diff;
reduce( src, _dst, dim, opType, dstType );
_dst.convertTo( dst, CV_64FC1 );
if( norm( opRes, dst, NORM_INF ) > eps )
absdiff( opRes,dst,diff );
bool check = false;
if (dstType == CV_32F || dstType == CV_64F)
check = countNonZero(diff>eps*dst) > 0;
else
check = countNonZero(diff>eps) > 0;
if( check )
{
char msg[100];
const char* opTypeStr = opType == CV_REDUCE_SUM ? "CV_REDUCE_SUM" :
@@ -168,21 +186,19 @@ int Core_ReduceTest::checkCase( int srcType, int dstType, int dim, Size sz )
assert( 0 );
// 1. sum
tempCode = checkOp( src, dstType, CV_REDUCE_SUM, sum, dim,
srcType == CV_32FC1 && dstType == CV_32FC1 ? 0.05 : FLT_EPSILON );
tempCode = checkOp( src, dstType, CV_REDUCE_SUM, sum, dim );
code = tempCode != cvtest::TS::OK ? tempCode : code;
// 2. avg
tempCode = checkOp( src, dstType, CV_REDUCE_AVG, avg, dim,
dstType == CV_32SC1 ? 0.6 : 0.00007 );
tempCode = checkOp( src, dstType, CV_REDUCE_AVG, avg, dim );
code = tempCode != cvtest::TS::OK ? tempCode : code;
// 3. max
tempCode = checkOp( src, dstType, CV_REDUCE_MAX, max, dim, FLT_EPSILON );
tempCode = checkOp( src, dstType, CV_REDUCE_MAX, max, dim );
code = tempCode != cvtest::TS::OK ? tempCode : code;
// 4. min
tempCode = checkOp( src, dstType, CV_REDUCE_MIN, min, dim, FLT_EPSILON );
tempCode = checkOp( src, dstType, CV_REDUCE_MIN, min, dim );
code = tempCode != cvtest::TS::OK ? tempCode : code;
return code;
+170 -1
View File
@@ -2347,6 +2347,41 @@ void Core_SolvePolyTest::run( int )
}
}
class Core_CheckRange_Empty : public cvtest::BaseTest
{
public:
Core_CheckRange_Empty(){}
~Core_CheckRange_Empty(){}
protected:
virtual void run( int start_from );
};
void Core_CheckRange_Empty::run( int )
{
cv::Mat m;
ASSERT_TRUE( cv::checkRange(m) );
}
TEST(Core_CheckRange_Empty, accuracy) { Core_CheckRange_Empty test; test.safe_run(); }
class Core_CheckRange_INT_MAX : public cvtest::BaseTest
{
public:
Core_CheckRange_INT_MAX(){}
~Core_CheckRange_INT_MAX(){}
protected:
virtual void run( int start_from );
};
void Core_CheckRange_INT_MAX::run( int )
{
cv::Mat m(3, 3, CV_32SC1, cv::Scalar(INT_MAX));
ASSERT_FALSE( cv::checkRange(m, true, 0, 0, INT_MAX) );
ASSERT_TRUE( cv::checkRange(m) );
}
TEST(Core_CheckRange_INT_MAX, accuracy) { Core_CheckRange_INT_MAX test; test.safe_run(); }
template <typename T> class Core_CheckRange : public testing::Test {};
TYPED_TEST_CASE_P(Core_CheckRange);
@@ -2402,7 +2437,17 @@ TYPED_TEST_P(Core_CheckRange, Bounds)
delete bad_pt;
}
REGISTER_TYPED_TEST_CASE_P(Core_CheckRange, Negative, Positive, Bounds);
TYPED_TEST_P(Core_CheckRange, Zero)
{
double min_bound = 0.0;
double max_bound = 0.1;
cv::Mat src = cv::Mat::zeros(3,3, cv::DataDepth<TypeParam>::value);
ASSERT_TRUE( checkRange(src, true, NULL, min_bound, max_bound) );
}
REGISTER_TYPED_TEST_CASE_P(Core_CheckRange, Negative, Positive, Bounds, Zero);
typedef ::testing::Types<signed char,unsigned char, signed short, unsigned short, signed int> mat_data_types;
INSTANTIATE_TYPED_TEST_CASE_P(Negative_Test, Core_CheckRange, mat_data_types);
@@ -2428,5 +2473,129 @@ TEST(Core_SolvePoly, accuracy) { Core_SolvePolyTest test; test.safe_run(); }
// TODO: eigenvv, invsqrt, cbrt, fastarctan, (round, floor, ceil(?)),
class CV_KMeansSingularTest : public cvtest::BaseTest
{
public:
CV_KMeansSingularTest() {}
~CV_KMeansSingularTest() {}
protected:
void run(int)
{
int i, iter = 0, N = 0, N0 = 0, K = 0, dims = 0;
Mat labels;
try
{
RNG& rng = theRNG();
const int MAX_DIM=5;
int MAX_POINTS = 100, maxIter = 100;
for( iter = 0; iter < maxIter; iter++ )
{
ts->update_context(this, iter, true);
dims = rng.uniform(1, MAX_DIM+1);
N = rng.uniform(1, MAX_POINTS+1);
N0 = rng.uniform(1, MAX(N/10, 2));
K = rng.uniform(1, N+1);
Mat data0(N0, dims, CV_32F);
rng.fill(data0, RNG::UNIFORM, -1, 1);
Mat data(N, dims, CV_32F);
for( i = 0; i < N; i++ )
data0.row(rng.uniform(0, N0)).copyTo(data.row(i));
kmeans(data, K, labels, TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS, 30, 0),
5, KMEANS_PP_CENTERS);
Mat hist(K, 1, CV_32S, Scalar(0));
for( i = 0; i < N; i++ )
{
int l = labels.at<int>(i);
CV_Assert(0 <= l && l < K);
hist.at<int>(l)++;
}
for( i = 0; i < K; i++ )
CV_Assert( hist.at<int>(i) != 0 );
}
}
catch(...)
{
ts->printf(cvtest::TS::LOG,
"context: iteration=%d, N=%d, N0=%d, K=%d\n",
iter, N, N0, K);
std::cout << labels << std::endl;
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
}
}
};
TEST(Core_KMeans, singular) { CV_KMeansSingularTest test; test.safe_run(); }
TEST(CovariationMatrixVectorOfMat, accuracy)
{
unsigned int col_problem_size = 8, row_problem_size = 8, vector_size = 16;
cv::Mat src(vector_size, col_problem_size * row_problem_size, CV_32F);
int singleMatFlags = CV_COVAR_ROWS;
cv::Mat gold;
cv::Mat goldMean;
cv::randu(src,cv::Scalar(-128), cv::Scalar(128));
cv::calcCovarMatrix(src,gold,goldMean,singleMatFlags,CV_32F);
std::vector<cv::Mat> srcVec;
for(size_t i = 0; i < vector_size; i++)
{
srcVec.push_back(src.row(static_cast<int>(i)).reshape(0,col_problem_size));
}
cv::Mat actual;
cv::Mat actualMean;
cv::calcCovarMatrix(srcVec, actual, actualMean,singleMatFlags,CV_32F);
cv::Mat diff;
cv::absdiff(gold, actual, diff);
cv::Scalar s = cv::sum(diff);
ASSERT_EQ(s.dot(s), 0.0);
cv::Mat meanDiff;
cv::absdiff(goldMean, actualMean.reshape(0,1), meanDiff);
cv::Scalar sDiff = cv::sum(meanDiff);
ASSERT_EQ(sDiff.dot(sDiff), 0.0);
}
TEST(CovariationMatrixVectorOfMatWithMean, accuracy)
{
unsigned int col_problem_size = 8, row_problem_size = 8, vector_size = 16;
cv::Mat src(vector_size, col_problem_size * row_problem_size, CV_32F);
int singleMatFlags = CV_COVAR_ROWS | CV_COVAR_USE_AVG;
cv::Mat gold;
cv::randu(src,cv::Scalar(-128), cv::Scalar(128));
cv::Mat goldMean;
cv::reduce(src,goldMean,0 ,CV_REDUCE_AVG, CV_32F);
cv::calcCovarMatrix(src,gold,goldMean,singleMatFlags,CV_32F);
std::vector<cv::Mat> srcVec;
for(size_t i = 0; i < vector_size; i++)
{
srcVec.push_back(src.row(static_cast<int>(i)).reshape(0,col_problem_size));
}
cv::Mat actual;
cv::Mat actualMean = goldMean.reshape(0, row_problem_size);
cv::calcCovarMatrix(srcVec, actual, actualMean,singleMatFlags,CV_32F);
cv::Mat diff;
cv::absdiff(gold, actual, diff);
cv::Scalar s = cv::sum(diff);
ASSERT_EQ(s.dot(s), 0.0);
cv::Mat meanDiff;
cv::absdiff(goldMean, actualMean.reshape(0,1), meanDiff);
cv::Scalar sDiff = cv::sum(meanDiff);
ASSERT_EQ(sDiff.dot(sDiff), 0.0);
}
/* End of file. */
+1 -1
View File
@@ -630,7 +630,7 @@ bool CV_OperationsTest::TestTemplateMat()
Mat_<uchar> matFromData(1, 4, uchar_data);
const Mat_<uchar> mat2 = matFromData.clone();
CHECK_DIFF(matFromData, eye.reshape(1));
CHECK_DIFF(matFromData, eye.reshape(1, 1));
if (matFromData(Point(0,0)) != uchar_data[0])throw test_excep();
if (mat2(Point(0,0)) != uchar_data[0]) throw test_excep();
+5 -1
View File
@@ -109,6 +109,10 @@ void Core_RandTest::run( int )
int dist_type = cvtest::randInt(rng) % (CV_RAND_NORMAL+1);
int i, k, SZ = N/cn;
Scalar A, B;
double eps = 1.e-4;
if (depth == CV_64F)
eps = 1.e-7;
bool do_sphere_test = dist_type == CV_RAND_UNI;
Mat arr[2], hist[4];
@@ -170,7 +174,7 @@ void Core_RandTest::run( int )
}
}
if( maxk >= 1 && norm(arr[0], arr[1], NORM_INF) != 0 )
if( maxk >= 1 && norm(arr[0], arr[1], NORM_INF) > eps)
{
ts->printf( cvtest::TS::LOG, "RNG output depends on the array lengths (some generated numbers get lost?)" );
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
@@ -500,7 +500,7 @@ The constructor
:param max_features: Maximum desired number of features.
:param max_iters: Maximum number of times to try adjusting the feature detector parameters. For :ocv:class:`FastAdjuster` , this number can be high, but with ``Star`` or ``Surf`` many iterations can be time-comsuming. At each iteration the detector is rerun.
:param max_iters: Maximum number of times to try adjusting the feature detector parameters. For :ocv:class:`FastAdjuster` , this number can be high, but with ``Star`` or ``Surf`` many iterations can be time-consuming. At each iteration the detector is rerun.
AdjusterAdapter
---------------
@@ -196,7 +196,7 @@ Finds the ``k`` best matches for each query keypoint.
.. ocv:function:: void GenericDescriptorMatcher::knnMatch( const Mat& queryImage, vector<KeyPoint>& queryKeypoints, vector<vector<DMatch> >& matches, int k, const vector<Mat>& masks=vector<Mat>(), bool compactResult=false )
The methods are extended variants of ``GenericDescriptorMatch::match``. The parameters are similar, and the the semantics is similar to ``DescriptorMatcher::knnMatch``. But this class does not require explicitly computed keypoint descriptors.
The methods are extended variants of ``GenericDescriptorMatch::match``. The parameters are similar, and the semantics is similar to ``DescriptorMatcher::knnMatch``. But this class does not require explicitly computed keypoint descriptors.
@@ -15,7 +15,7 @@ Detects corners using the FAST algorithm
:param threshold: Threshold on difference between intensity of the central pixel and pixels on a circle around this pixel. See the algorithm description below.
:param nonmaxSupression: If it is true, non-maximum supression is applied to detected corners (keypoints).
:param nonmaxSupression: If it is true, non-maximum suppression is applied to detected corners (keypoints).
Detects corners using the FAST algorithm by E. Rosten (*Machine Learning for High-speed Corner Detection*, 2006).
@@ -43,7 +43,7 @@ Maximally stable extremal region extractor. ::
};
The class encapsulates all the parameters of the MSER extraction algorithm (see
http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions). Also see http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/MSER for usefull comments and parameters description.
http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions). Also see http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/MSER for useful comments and parameters description.
StarDetector
@@ -186,7 +186,7 @@ Computes an image descriptor using the set visual vocabulary.
BOWImgDescriptorExtractor::descriptorSize
---------------------------------------------
Returns an image discriptor size if the vocabulary is set. Otherwise, it returns 0.
Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0.
.. ocv:function:: int BOWImgDescriptorExtractor::descriptorSize() const
@@ -51,6 +51,8 @@
namespace cv
{
CV_EXPORTS bool initModule_features2d();
/*!
The Keypoint Class
-16
View File
@@ -172,20 +172,4 @@ void BriefDescriptorExtractor::computeImpl(const Mat& image, std::vector<KeyPoin
test_fn_(sum, keypoints, descriptors);
}
static Algorithm* createBRIEF() { return new BriefDescriptorExtractor; }
static AlgorithmInfo brief_info("Feature2D.BRIEF", createBRIEF);
AlgorithmInfo* BriefDescriptorExtractor::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
BriefDescriptorExtractor brief;
brief_info.addParam(brief, "bytes", brief.bytes_);
initialized = true;
}
return &brief_info;
}
} // namespace cv
+158 -2
View File
@@ -195,7 +195,7 @@ DenseFeatureDetector::DenseFeatureDetector( float _initFeatureScale, int _featur
void DenseFeatureDetector::detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask ) const
{
float curScale = initFeatureScale;
float curScale = static_cast<float>(initFeatureScale);
int curStep = initXyStep;
int curBound = initImgBound;
for( int curLevel = 0; curLevel < featureScaleLevels; curLevel++ )
@@ -208,7 +208,7 @@ void DenseFeatureDetector::detectImpl( const Mat& image, vector<KeyPoint>& keypo
}
}
curScale = curScale * featureScaleMul;
curScale = static_cast<float>(curScale * featureScaleMul);
if( varyXyStepWithScale ) curStep = static_cast<int>( curStep * featureScaleMul + 0.5f );
if( varyImgBoundWithScale ) curBound = static_cast<int>( curBound * featureScaleMul + 0.5f );
}
@@ -359,5 +359,161 @@ void PyramidAdaptedFeatureDetector::detectImpl( const Mat& image, vector<KeyPoin
if( !mask.empty() )
KeyPointsFilter::runByPixelsMask( keypoints, mask );
}
/////////////////////// AlgorithmInfo for various detector & descriptors ////////////////////////////
/* NOTE!!!
All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d().
Otherwise, linker may throw away some seemingly unused stuff.
*/
static Algorithm* createBRIEF() { return new BriefDescriptorExtractor; }
static AlgorithmInfo& brief_info()
{
static AlgorithmInfo brief_info_var("Feature2D.BRIEF", createBRIEF);
return brief_info_var;
}
static AlgorithmInfo& brief_info_auto = brief_info();
AlgorithmInfo* BriefDescriptorExtractor::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
BriefDescriptorExtractor brief;
brief_info().addParam(brief, "bytes", brief.bytes_);
initialized = true;
}
return &brief_info();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createFAST() { return new FastFeatureDetector; }
static AlgorithmInfo& fast_info()
{
static AlgorithmInfo fast_info_var("Feature2D.FAST", createFAST);
return fast_info_var;
}
static AlgorithmInfo& fast_info_auto = fast_info();
AlgorithmInfo* FastFeatureDetector::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
FastFeatureDetector obj;
fast_info().addParam(obj, "threshold", obj.threshold);
fast_info().addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
initialized = true;
}
return &fast_info();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createStarDetector() { return new StarDetector; }
static AlgorithmInfo& star_info()
{
static AlgorithmInfo star_info_var("Feature2D.STAR", createStarDetector);
return star_info_var;
}
static AlgorithmInfo& star_info_auto = star_info();
AlgorithmInfo* StarDetector::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
StarDetector obj;
star_info().addParam(obj, "maxSize", obj.maxSize);
star_info().addParam(obj, "responseThreshold", obj.responseThreshold);
star_info().addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
star_info().addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
star_info().addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize);
initialized = true;
}
return &star_info();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createMSER() { return new MSER; }
static AlgorithmInfo& mser_info()
{
static AlgorithmInfo mser_info_var("Feature2D.MSER", createMSER);
return mser_info_var;
}
static AlgorithmInfo& mser_info_auto = mser_info();
AlgorithmInfo* MSER::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
MSER obj;
mser_info().addParam(obj, "delta", obj.delta);
mser_info().addParam(obj, "minArea", obj.minArea);
mser_info().addParam(obj, "maxArea", obj.maxArea);
mser_info().addParam(obj, "maxVariation", obj.maxVariation);
mser_info().addParam(obj, "minDiversity", obj.minDiversity);
mser_info().addParam(obj, "maxEvolution", obj.maxEvolution);
mser_info().addParam(obj, "areaThreshold", obj.areaThreshold);
mser_info().addParam(obj, "minMargin", obj.minMargin);
mser_info().addParam(obj, "edgeBlurSize", obj.edgeBlurSize);
initialized = true;
}
return &mser_info();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createORB() { return new ORB; }
static AlgorithmInfo& orb_info()
{
static AlgorithmInfo orb_info_var("Feature2D.ORB", createORB);
return orb_info_var;
}
static AlgorithmInfo& orb_info_auto = orb_info();
AlgorithmInfo* ORB::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
ORB obj;
orb_info().addParam(obj, "nFeatures", obj.nfeatures);
orb_info().addParam(obj, "scaleFactor", obj.scaleFactor);
orb_info().addParam(obj, "nLevels", obj.nlevels);
orb_info().addParam(obj, "firstLevel", obj.firstLevel);
orb_info().addParam(obj, "edgeThreshold", obj.edgeThreshold);
orb_info().addParam(obj, "patchSize", obj.patchSize);
orb_info().addParam(obj, "WTA_K", obj.WTA_K);
orb_info().addParam(obj, "scoreType", obj.scoreType);
initialized = true;
}
return &orb_info();
}
bool initModule_features2d(void)
{
Ptr<Algorithm> brief = createBRIEF(), orb = createORB(),
star = createStarDetector(), fastd = createFAST(), mser = createMSER();
return brief->info() != 0 && orb->info() != 0 && star->info() != 0 &&
fastd->info() != 0 && mser->info() != 0;
}
}
-18
View File
@@ -391,22 +391,4 @@ void FastFeatureDetector::detectImpl( const Mat& image, vector<KeyPoint>& keypoi
KeyPointsFilter::runByPixelsMask( keypoints, mask );
}
static Algorithm* createFAST() { return new FastFeatureDetector; }
static AlgorithmInfo fast_info("Feature2D.FAST", createFAST);
AlgorithmInfo* FastFeatureDetector::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
FastFeatureDetector obj;
fast_info.addParam(obj, "threshold", obj.threshold);
fast_info.addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
initialized = true;
}
return &fast_info;
}
}
+1 -1
View File
@@ -383,7 +383,7 @@ void BFMatcher::knnMatchImpl( const Mat& queryDescriptors, vector<vector<DMatch>
vector<DMatch>& mq = matches.back();
mq.reserve(knn);
for( int k = 0; k < knn; k++ )
for( int k = 0; k < nidx.cols; k++ )
{
if( nidxptr[k] < 0 )
break;
-24
View File
@@ -1299,28 +1299,4 @@ void MserFeatureDetector::detectImpl( const Mat& image, vector<KeyPoint>& keypoi
}
}
static Algorithm* createMSER() { return new MSER; }
static AlgorithmInfo mser_info("Feature2D.MSER", createMSER);
AlgorithmInfo* MSER::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
MSER obj;
mser_info.addParam(obj, "delta", obj.delta);
mser_info.addParam(obj, "minArea", obj.minArea);
mser_info.addParam(obj, "maxArea", obj.maxArea);
mser_info.addParam(obj, "maxVariation", obj.maxVariation);
mser_info.addParam(obj, "minDiversity", obj.minDiversity);
mser_info.addParam(obj, "maxEvolution", obj.maxEvolution);
mser_info.addParam(obj, "areaThreshold", obj.areaThreshold);
mser_info.addParam(obj, "minMargin", obj.minMargin);
mser_info.addParam(obj, "edgeBlurSize", obj.edgeBlurSize);
initialized = true;
}
return &mser_info;
}
}
-25
View File
@@ -546,31 +546,6 @@ static void makeRandomPattern(int patchSize, Point* pattern, int npoints)
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createORB() { return new ORB; }
static AlgorithmInfo orb_info("Feature2D.ORB", createORB);
AlgorithmInfo* ORB::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
ORB obj;
orb_info.addParam(obj, "nFeatures", obj.nfeatures);
orb_info.addParam(obj, "scaleFactor", obj.scaleFactor);
orb_info.addParam(obj, "nLevels", obj.nlevels);
orb_info.addParam(obj, "firstLevel", obj.firstLevel);
orb_info.addParam(obj, "edgeThreshold", obj.edgeThreshold);
orb_info.addParam(obj, "patchSize", obj.patchSize);
orb_info.addParam(obj, "WTA_K", obj.WTA_K);
orb_info.addParam(obj, "scoreType", obj.scoreType);
initialized = true;
}
return &orb_info;
}
static inline float getScale(int level, int firstLevel, double scaleFactor)
{
return (float)std::pow(scaleFactor, (double)(level - firstLevel));
-21
View File
@@ -447,25 +447,4 @@ void StarDetector::operator()(const Mat& img, vector<KeyPoint>& keypoints) const
lineThresholdBinarized, suppressNonmaxSize );
}
static Algorithm* createStarDetector() { return new StarDetector; }
static AlgorithmInfo star_info("Feature2D.STAR", createStarDetector);
AlgorithmInfo* StarDetector::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
StarDetector obj;
star_info.addParam(obj, "maxSize", obj.maxSize);
star_info.addParam(obj, "responseThreshold", obj.responseThreshold);
star_info.addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
star_info.addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
star_info.addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize);
initialized = true;
}
return &star_info;
}
}
+7 -5
View File
@@ -269,13 +269,15 @@ static Mat readMatFromBin( const string& filename )
if( f )
{
int rows, cols, type, dataSize;
fread( (void*)&rows, sizeof(int), 1, f );
fread( (void*)&cols, sizeof(int), 1, f );
fread( (void*)&type, sizeof(int), 1, f );
fread( (void*)&dataSize, sizeof(int), 1, f );
size_t elements_read1 = fread( (void*)&rows, sizeof(int), 1, f );
size_t elements_read2 = fread( (void*)&cols, sizeof(int), 1, f );
size_t elements_read3 = fread( (void*)&type, sizeof(int), 1, f );
size_t elements_read4 = fread( (void*)&dataSize, sizeof(int), 1, f );
CV_Assert(elements_read1 == 1 && elements_read2 == 1 && elements_read3 == 1 && elements_read4 == 1);
uchar* data = (uchar*)cvAlloc(dataSize);
fread( (void*)data, 1, dataSize, f );
size_t elements_read = fread( (void*)data, 1, dataSize, f );
CV_Assert(elements_read == (size_t)(dataSize));
fclose(f);
return Mat( rows, cols, type, data );
+2 -1
View File
@@ -75,7 +75,8 @@ int CV_MserTest::LoadBoxes(const char* path, vector<CvBox2D>& boxes)
while (!feof(f))
{
CvBox2D box;
fscanf(f,"%f,%f,%f,%f,%f\n",&box.angle,&box.center.x,&box.center.y,&box.size.width,&box.size.height);
int values_read = fscanf(f,"%f,%f,%f,%f,%f\n",&box.angle,&box.center.x,&box.center.y,&box.size.width,&box.size.height);
CV_Assert(values_read == 5);
boxes.push_back(box);
}
fclose(f);
+7 -5
View File
@@ -3,16 +3,18 @@ Clustering
.. highlight:: cpp
flann::hierarchicalClustering<ET,DT>
flann::hierarchicalClustering<Distance>
--------------------------------------------
Clusters features using hierarchical k-means algorithm.
.. ocv:function:: int flann::hierarchicalClustering<ET,DT>(const Mat& features, Mat& centers, const KMeansIndexParams& params)
.. ocv:function:: template<typename Distance> int flann::hierarchicalClustering(const Mat& features, Mat& centers, const cvflann::KMeansIndexParams& params, Distance d = Distance())
:param features: The points to be clustered. The matrix must have elements of type ET.
:param features: The points to be clustered. The matrix must have elements of type ``Distance::ElementType``.
:param centers: The centers of the clusters obtained. The matrix must have type DT. The number of rows in this matrix represents the number of clusters desired, however, because of the way the cut in the hierarchical tree is chosen, the number of clusters computed will be the highest number of the form ``(branching-1)*k+1`` that's lower than the number of clusters desired, where ``branching`` is the tree's branching factor (see description of the KMeansIndexParams).
:param centers: The centers of the clusters obtained. The matrix must have type ``Distance::ResultType``. The number of rows in this matrix represents the number of clusters desired, however, because of the way the cut in the hierarchical tree is chosen, the number of clusters computed will be the highest number of the form ``(branching-1)*k+1`` that's lower than the number of clusters desired, where ``branching`` is the tree's branching factor (see description of the KMeansIndexParams).
:param params: Parameters used in the construction of the hierarchical k-means tree
:param params: Parameters used in the construction of the hierarchical k-means tree.
:param d: Distance to be used for clustering.
The method clusters the given feature vectors by constructing a hierarchical k-means tree and choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters found.
@@ -71,7 +71,7 @@ The method constructs a fast search structure from a set of features using the s
* **centers_init** The algorithm to use for selecting the initial centers when performing a k-means clustering step. The possible values are ``CENTERS_RANDOM`` (picks the initial cluster centers randomly), ``CENTERS_GONZALES`` (picks the initial centers using Gonzales' algorithm) and ``CENTERS_KMEANSPP`` (picks the initial centers using the algorithm suggested in arthur_kmeanspp_2007 )
* **cb_index** This parameter (cluster boundary index) influences the way exploration is performed in the hierarchical kmeans tree. When ``cb_index`` is zero the next kmeans domain to be explored is choosen to be the one with the closest center. A value greater then zero also takes into account the size of the domain.
* **cb_index** This parameter (cluster boundary index) influences the way exploration is performed in the hierarchical kmeans tree. When ``cb_index`` is zero the next kmeans domain to be explored is chosen to be the one with the closest center. A value greater then zero also takes into account the size of the domain.
*
**CompositeIndexParams** When using a parameters object of this type the index created combines the randomized kd-trees and the hierarchical k-means tree. ::
@@ -205,7 +205,7 @@ Saves the index to a file.
flann::Index_<T>::getIndexParameters
--------------------------------------------
Returns the index paramreters.
Returns the index parameters.
.. ocv:function:: const IndexParams* flann::Index_<T>::getIndexParameters()
@@ -225,7 +225,11 @@ int GenericIndex<Distance>::radiusSearch(const Mat& query, Mat& indices, Mat& di
* @deprecated Use GenericIndex class instead
*/
template <typename T>
class FLANN_DEPRECATED Index_ {
class
#ifndef _MSC_VER
FLANN_DEPRECATED
#endif
Index_ {
public:
typedef typename L2<T>::ElementType ElementType;
typedef typename L2<T>::ResultType DistanceType;
@@ -277,6 +281,10 @@ private:
::cvflann::Index< L1<ElementType> >* nnIndex_L1;
};
#ifdef _MSC_VER
template <typename T>
class FLANN_DEPRECATED Index_;
#endif
template <typename T>
Index_<T>::Index_(const Mat& dataset, const ::cvflann::IndexParams& params)
+8 -10
View File
@@ -33,18 +33,16 @@ if (HAVE_CUDA)
#set (CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} "-keep")
#set (CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} "-Xcompiler;/EHsc-;")
foreach(var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG)
string(REPLACE "/W4" "/W3" ${var} "${${var}}")
endforeach()
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4211 /wd4201 /wd4100 /wd4505 /wd4408 /wd4251")
foreach(var CMAKE_C_FLAGS CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_DEBUG CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG)
string(REPLACE "/EHsc-" "/EHs" ${var} "${${var}}")
endforeach()
if(NOT ENABLE_NOISY_WARNINGS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4211 /wd4201 /wd4100 /wd4505 /wd4408")
foreach(var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG)
string(REPLACE "/W4" "/W3" ${var} "${${var}}")
endforeach()
set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} -Xcompiler /wd4251)
set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} -Xcompiler /wd4251)
endif()
endif()
OCV_CUDA_COMPILE(cuda_objs ${lib_cuda} ${ncv_cuda})
@@ -279,7 +279,7 @@ Class computing stereo correspondence using the constant space belief propagatio
};
The class implements algorithm described in [Yang2010]_. ``StereoConstantSpaceBP`` supports both local minimum and global minimum data cost initialization algortihms. For more details, see the paper mentioned above. By default, a local algorithm is used. To enable a global algorithm, set ``use_local_init_data_cost`` to ``false`` .
The class implements algorithm described in [Yang2010]_. ``StereoConstantSpaceBP`` supports both local minimum and global minimum data cost initialization algorithms. For more details, see the paper mentioned above. By default, a local algorithm is used. To enable a global algorithm, set ``use_local_init_data_cost`` to ``false`` .
@@ -323,7 +323,7 @@ Enables the :ocv:class:`gpu::StereoConstantSpaceBP` constructors.
For more details, see [Yang2010]_.
By default, ``StereoConstantSpaceBP`` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better perfomance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
By default, ``StereoConstantSpaceBP`` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better performance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
.. math::
@@ -359,7 +359,7 @@ gpu::DisparityBilateralFilter
-----------------------------
.. ocv:class:: gpu::DisparityBilateralFilter
Class refinining a disparity map using joint bilateral filtering. ::
Class refining a disparity map using joint bilateral filtering. ::
class CV_EXPORTS DisparityBilateralFilter
{
+1 -1
View File
@@ -172,7 +172,7 @@ Ensures that the size of a matrix is big enough and the matrix has a proper type
:param cols: Minimum desired number of columns.
:param size: Rows and coumns passed as a structure.
:param size: Rows and columns passed as a structure.
:param type: Desired matrix type.
@@ -168,7 +168,7 @@ Constructor.
:param threshold: Threshold on difference between intensity of the central pixel and pixels on a circle around this pixel.
:param nonmaxSupression: If it is true, non-maximum supression is applied to detected corners (keypoints).
:param nonmaxSupression: If it is true, non-maximum suppression is applied to detected corners (keypoints).
:param keypointsRatio: Inner buffer size for keypoints store is determined as (keypointsRatio * image_width * image_height).
@@ -188,7 +188,7 @@ Finds the keypoints using FAST detector.
:param keypoints: The output vector of keypoints. Can be stored both in CPU and GPU memory. For GPU memory:
* keypoints.ptr<Vec2s>(LOCATION_ROW)[i] will contain location of i'th point
* keypoints.ptr<float>(RESPONSE_ROW)[i] will contaion response of i'th point (if non-maximum supression is applied)
* keypoints.ptr<float>(RESPONSE_ROW)[i] will contain response of i'th point (if non-maximum suppression is applied)
@@ -238,7 +238,7 @@ Gets final array of keypoints.
:param keypoints: The output vector of keypoints.
The function performs nonmax supression if needed and returns final count of keypoints.
The function performs non-max suppression if needed and returns final count of keypoints.
@@ -529,7 +529,7 @@ Converts matrices obtained via :ocv:func:`gpu::BruteForceMatcher_GPU::matchSingl
gpu::BruteForceMatcher_GPU::knnMatch
----------------------------------------
Finds the k best matches for each descriptor from a query set with train descriptors.
Finds the ``k`` best matches for each descriptor from a query set with train descriptors.
.. ocv:function:: void gpu::BruteForceMatcher_GPU::knnMatch(const GpuMat& query, const GpuMat& train, std::vector< std::vector<DMatch> >&matches, int k, const GpuMat& mask = GpuMat(), bool compactResult = false)
@@ -551,7 +551,7 @@ Finds the k best matches for each descriptor from a query set with train descrip
:param stream: Stream for the asynchronous version.
The function returns detected k (or less if not possible) matches in the increasing order by distance.
The function returns detected ``k`` (or less if not possible) matches in the increasing order by distance.
The third variant of the method stores the results in GPU memory.
+3 -3
View File
@@ -109,7 +109,7 @@ By using ``FilterEngine_GPU`` instead of functions you can avoid unnecessary mem
filter.release();
``FilterEngine_GPU`` can process a rectangular sub-region of an image. By default, if ``roi == Rect(0,0,-1,-1)`` , ``FilterEngine_GPU`` processes the inner region of an image ( ``Rect(anchor.x, anchor.y, src_size.width - ksize.width, src_size.height - ksize.height)`` ) because some filters do not check whether indices are outside the image for better perfomance. See below to understand which filters support processing the whole image and which do not and identify image type limitations.
``FilterEngine_GPU`` can process a rectangular sub-region of an image. By default, if ``roi == Rect(0,0,-1,-1)`` , ``FilterEngine_GPU`` processes the inner region of an image ( ``Rect(anchor.x, anchor.y, src_size.width - ksize.width, src_size.height - ksize.height)`` ) because some filters do not check whether indices are outside the image for better performance. See below to understand which filters support processing the whole image and which do not and identify image type limitations.
.. note:: The GPU filters do not support the in-place mode.
@@ -469,7 +469,7 @@ Creates a primitive column filter with the specified kernel.
.. ocv:function:: Ptr<BaseColumnFilter_GPU> gpu::getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel, int anchor = -1, int borderType = BORDER_CONSTANT)
:param bufType: Inermediate buffer type with as many channels as ``dstType`` .
:param bufType: Intermediate buffer type with as many channels as ``dstType`` .
:param dstType: Destination array type. ``CV_8UC1`` , ``CV_8UC4`` , ``CV_16SC1`` , ``CV_16SC2`` , ``CV_16SC3`` , ``CV_32SC1`` , ``CV_32FC1`` destination types are supported.
@@ -581,7 +581,7 @@ Applies the generalized Sobel operator to an image.
:param dy: Derivative order in respect of y.
:param ksize: Size of the extended Sobel kernel. Possible valies are 1, 3, 5 or 7.
:param ksize: Size of the extended Sobel kernel. Possible values are 1, 3, 5 or 7.
:param scale: Optional scale factor for the computed derivative values. By default, no scaling is applied. For details, see :ocv:func:`getDerivKernels` .
+5 -5
View File
@@ -61,7 +61,7 @@ Performs a mean-shift segmentation of the source image and eliminates small segm
:param sr: Color window radius.
:param minsize: Minimum segment size. Smaller segements are merged.
:param minsize: Minimum segment size. Smaller segments are merged.
:param criteria: Termination criteria. See :ocv:class:`TermCriteria`.
@@ -229,7 +229,7 @@ The source matrix should be continuous, otherwise reallocation and data copying
* If the source matrix is complex and the output is not specified as real, the destination matrix is complex and has the ``dft_size`` size and ``CV_32FC2`` type. The destination matrix contains a full result of the DFT (forward or inverse).
* If the source matrix is complex and the output is specified as real, the function assumes that its input is the result of the forward transform (see the next item). The destionation matrix has the ``dft_size`` size and ``CV_32FC1`` type. It contains the result of the inverse DFT.
* If the source matrix is complex and the output is specified as real, the function assumes that its input is the result of the forward transform (see the next item). The destination matrix has the ``dft_size`` size and ``CV_32FC1`` type. It contains the result of the inverse DFT.
* If the source matrix is real (its type is ``CV_32FC1`` ), forward DFT is performed. The result of the DFT is packed into complex ( ``CV_32FC2`` ) matrix. So, the width of the destination matrix is ``dft_size.width / 2 + 1`` . But if the source is a single column, the height is reduced instead of the width.
@@ -392,7 +392,7 @@ Converts an image from one color space to another.
:param stream: Stream for the asynchronous version.
3-channel color spaces (like ``HSV``, ``XYZ``, and so on) can be stored in a 4-channel image for better perfomance.
3-channel color spaces (like ``HSV``, ``XYZ``, and so on) can be stored in a 4-channel image for better performance.
.. seealso:: :ocv:func:`cvtColor`
@@ -499,7 +499,7 @@ gpu::buildWarpAffineMaps
------------------------
Builds transformation maps for affine transformation.
.. ocv:function:: void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());
.. ocv:function:: void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null())
:param M: *2x3* transformation matrix.
@@ -543,7 +543,7 @@ gpu::buildWarpPerspectiveMaps
-----------------------------
Builds transformation maps for perspective transformation.
.. ocv:function:: void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());
.. ocv:function:: void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null())
:param M: *3x3* transformation matrix.
+1 -1
View File
@@ -43,7 +43,7 @@ Utilizing Multiple GPUs
-----------------------
In the current version, each of the OpenCV GPU algorithms can use only a single GPU. So, to utilize multiple GPUs, you have to manually distribute the work between GPUs.
Switching active devie can be done using :ocv:func:`gpu::setDevice()' function. For more details please read Cuda C Programing Guid.
Switching active devie can be done using :ocv:func:`gpu::setDevice()` function. For more details please read Cuda C Programing Guide.
While developing algorithms for multiple GPUs, note a data passing overhead. For primitive functions and small images, it can be significant, which may eliminate all the advantages of having multiple GPUs. But for high-level algorithms, consider using multi-GPU acceleration. For example, the Stereo Block Matching algorithm has been successfully parallelized using the following algorithm:
+5 -5
View File
@@ -191,9 +191,9 @@ Computes polar angles of complex matrix elements.
:param y: Source matrix containing imaginary components ( ``CV_32FC1`` ).
:param angle: Destionation matrix of angles ( ``CV_32FC1`` ).
:param angle: Destination matrix of angles ( ``CV_32FC1`` ).
:param angleInDegrees: Flag for angles that must be evaluated in degress.
:param angleInDegrees: Flag for angles that must be evaluated in degrees.
:param stream: Stream for the asynchronous version.
@@ -213,9 +213,9 @@ Converts Cartesian coordinates into polar.
:param magnitude: Destination matrix of float magnitudes ( ``CV_32FC1`` ).
:param angle: Destionation matrix of angles ( ``CV_32FC1`` ).
:param angle: Destination matrix of angles ( ``CV_32FC1`` ).
:param angleInDegrees: Flag for angles that must be evaluated in degress.
:param angleInDegrees: Flag for angles that must be evaluated in degrees.
:param stream: Stream for the asynchronous version.
@@ -237,7 +237,7 @@ Converts polar coordinates into Cartesian.
:param y: Destination matrix of imaginary components ( ``CV_32FC1`` ).
:param angleInDegrees: Flag that indicates angles in degress.
:param angleInDegrees: Flag that indicates angles in degrees.
:param stream: Stream for the asynchronous version.
+20 -20
View File
@@ -1,7 +1,7 @@
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
@@ -64,18 +64,18 @@
/// \brief Model and solver parameters
struct NCVBroxOpticalFlowDescriptor
{
/// flow smoothness
Ncv32f alpha;
/// gradient constancy importance
Ncv32f gamma;
/// pyramid scale factor
Ncv32f scale_factor;
/// number of lagged non-linearity iterations (inner loop)
Ncv32u number_of_inner_iterations;
/// number of warping iterations (number of pyramid levels)
Ncv32u number_of_outer_iterations;
/// number of linear system solver iterations
Ncv32u number_of_solver_iterations;
/// flow smoothness
Ncv32f alpha;
/// gradient constancy importance
Ncv32f gamma;
/// pyramid scale factor
Ncv32f scale_factor;
/// number of lagged non-linearity iterations (inner loop)
Ncv32u number_of_inner_iterations;
/// number of warping iterations (number of pyramid levels)
Ncv32u number_of_outer_iterations;
/// number of linear system solver iterations
Ncv32u number_of_solver_iterations;
};
/////////////////////////////////////////////////////////////////////////////////////////
@@ -93,11 +93,11 @@ struct NCVBroxOpticalFlowDescriptor
NCV_EXPORTS
NCVStatus NCVBroxOpticalFlow(const NCVBroxOpticalFlowDescriptor desc,
INCVMemAllocator &gpu_mem_allocator,
const NCVMatrix<Ncv32f> &frame0,
const NCVMatrix<Ncv32f> &frame1,
NCVMatrix<Ncv32f> &u,
NCVMatrix<Ncv32f> &v,
cudaStream_t stream);
INCVMemAllocator &gpu_mem_allocator,
const NCVMatrix<Ncv32f> &frame0,
const NCVMatrix<Ncv32f> &frame1,
NCVMatrix<Ncv32f> &u,
NCVMatrix<Ncv32f> &v,
cudaStream_t stream);
#endif
@@ -59,6 +59,7 @@
#define _ncvhaarobjectdetection_hpp_
#include <string>
#include <vector_types.h>
#include "NCV.hpp"
@@ -68,41 +69,43 @@
//
//==============================================================================
struct HaarFeature64
{
uint2 _ui2;
union
{
uint2 _ui2;
struct {NcvRect8u__ _rect; Ncv32f _f;};
};
#define HaarFeature64_CreateCheck_MaxRectField 0xFF
__host__ NCVStatus setRect(Ncv32u rectX, Ncv32u rectY, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32u /*clsWidth*/, Ncv32u /*clsHeight*/)
{
ncvAssertReturn(rectWidth <= HaarFeature64_CreateCheck_MaxRectField && rectHeight <= HaarFeature64_CreateCheck_MaxRectField, NCV_HAAR_TOO_LARGE_FEATURES);
((NcvRect8u*)&(this->_ui2.x))->x = (Ncv8u)rectX;
((NcvRect8u*)&(this->_ui2.x))->y = (Ncv8u)rectY;
((NcvRect8u*)&(this->_ui2.x))->width = (Ncv8u)rectWidth;
((NcvRect8u*)&(this->_ui2.x))->height = (Ncv8u)rectHeight;
_rect = NcvRect8u(rectX,rectY,rectWidth,rectHeight);
return NCV_SUCCESS;
}
__host__ NCVStatus setWeight(Ncv32f weight)
{
((Ncv32f*)&(this->_ui2.y))[0] = weight;
_f = weight;
return NCV_SUCCESS;
}
__device__ __host__ void getRect(Ncv32u *rectX, Ncv32u *rectY, Ncv32u *rectWidth, Ncv32u *rectHeight)
{
NcvRect8u tmpRect = *(NcvRect8u*)(&this->_ui2.x);
*rectX = tmpRect.x;
*rectY = tmpRect.y;
*rectWidth = tmpRect.width;
*rectHeight = tmpRect.height;
*rectX = _rect.x;
*rectY = _rect.y;
*rectWidth = _rect.width;
*rectHeight = _rect.height;
}
__device__ __host__ Ncv32f getWeight(void)
{
return *(Ncv32f*)(&this->_ui2.y);
return _f;
}
};
@@ -170,24 +173,28 @@ public:
struct HaarClassifierNodeDescriptor32
{
union
{
uint1 _ui1;
Ncv32f _f;
};
__host__ NCVStatus create(Ncv32f leafValue)
{
*(Ncv32f *)&this->_ui1 = leafValue;
_f = leafValue;
return NCV_SUCCESS;
}
__host__ NCVStatus create(Ncv32u offsetHaarClassifierNode)
{
this->_ui1.x = offsetHaarClassifierNode;
_ui1.x = offsetHaarClassifierNode;
return NCV_SUCCESS;
}
__host__ Ncv32f getLeafValueHost(void)
{
return *(Ncv32f *)&this->_ui1.x;
return _f;
}
#ifdef __CUDACC__
@@ -199,57 +206,67 @@ struct HaarClassifierNodeDescriptor32
__device__ __host__ Ncv32u getNextNodeOffset(void)
{
return this->_ui1.x;
return _ui1.x;
}
};
struct HaarClassifierNode128
{
union
{
uint4 _ui4;
struct
{
HaarFeatureDescriptor32 _f;
Ncv32f _t;
HaarClassifierNodeDescriptor32 _nl;
HaarClassifierNodeDescriptor32 _nr;
};
};
__host__ NCVStatus setFeatureDesc(HaarFeatureDescriptor32 f)
{
this->_ui4.x = *(Ncv32u *)&f;
_f = f;
return NCV_SUCCESS;
}
__host__ NCVStatus setThreshold(Ncv32f t)
{
this->_ui4.y = *(Ncv32u *)&t;
_t = t;
return NCV_SUCCESS;
}
__host__ NCVStatus setLeftNodeDesc(HaarClassifierNodeDescriptor32 nl)
{
this->_ui4.z = *(Ncv32u *)&nl;
_nl = nl;
return NCV_SUCCESS;
}
__host__ NCVStatus setRightNodeDesc(HaarClassifierNodeDescriptor32 nr)
{
this->_ui4.w = *(Ncv32u *)&nr;
_nr = nr;
return NCV_SUCCESS;
}
__host__ __device__ HaarFeatureDescriptor32 getFeatureDesc(void)
{
return *(HaarFeatureDescriptor32 *)&this->_ui4.x;
return _f;
}
__host__ __device__ Ncv32f getThreshold(void)
{
return *(Ncv32f*)&this->_ui4.y;
return _t;
}
__host__ __device__ HaarClassifierNodeDescriptor32 getLeftNodeDesc(void)
{
return *(HaarClassifierNodeDescriptor32 *)&this->_ui4.z;
return _nl;
}
__host__ __device__ HaarClassifierNodeDescriptor32 getRightNodeDesc(void)
{
return *(HaarClassifierNodeDescriptor32 *)&this->_ui4.w;
return _nr;
}
};
@@ -260,11 +277,15 @@ struct HaarStage64
#define HaarStage64_Interpret_MaskRootNodeOffset 0xFFFF0000
#define HaarStage64_Interpret_ShiftRootNodeOffset 16
union
{
uint2 _ui2;
struct {Ncv32f _t; Ncv32u _root;};
};
__host__ NCVStatus setStageThreshold(Ncv32f t)
{
this->_ui2.x = *(Ncv32u *)&t;
_t = t;
return NCV_SUCCESS;
}
@@ -290,7 +311,7 @@ struct HaarStage64
__host__ __device__ Ncv32f getStageThreshold(void)
{
return *(Ncv32f*)&this->_ui2.x;
return _t;
}
__host__ __device__ Ncv32u getStartClassifierRootNodeOffset(void)
@@ -304,14 +325,12 @@ struct HaarStage64
}
};
NCV_CT_ASSERT(sizeof(HaarFeature64) == 8);
NCV_CT_ASSERT(sizeof(HaarFeatureDescriptor32) == 4);
NCV_CT_ASSERT(sizeof(HaarClassifierNodeDescriptor32) == 4);
NCV_CT_ASSERT(sizeof(HaarClassifierNode128) == 16);
NCV_CT_ASSERT(sizeof(HaarStage64) == 8);
//==============================================================================
//
// Classifier cascade descriptor
+13 -4
View File
@@ -134,15 +134,24 @@ typedef unsigned char Ncv8u;
typedef float Ncv32f;
typedef double Ncv64f;
struct NcvRect8u
struct NcvRect8u__
{
Ncv8u x;
Ncv8u y;
Ncv8u width;
Ncv8u height;
__host__ __device__ NcvRect8u() : x(0), y(0), width(0), height(0) {};
__host__ __device__ NcvRect8u(Ncv8u x, Ncv8u y, Ncv8u width, Ncv8u height) : x(x), y(y), width(width), height(height) {}
};
struct NcvRect8u : NcvRect8u__
{
__host__ __device__ NcvRect8u() {}
__host__ __device__ NcvRect8u(Ncv8u x, Ncv8u y, Ncv8u width, Ncv8u height)
{
x = x;
y = y;
width = width;
height = height;
}
};
+1 -1
View File
@@ -33,9 +33,9 @@ private:
TestRectStdDev& operator=(const TestRectStdDev&);
NCVTestSourceProvider<Ncv8u> &src;
NcvRect32u rect;
Ncv32u width;
Ncv32u height;
NcvRect32u rect;
Ncv32f scaleFactor;
NcvBool bTextureCache;
+2 -2
View File
@@ -249,7 +249,7 @@ TEST_P(ProjectPoints, Accuracy)
for (size_t i = 0; i < dst_gold.size(); ++i)
{
cv::Point2f res = h_dst.at<cv::Point2f>(0, i);
cv::Point2f res = h_dst.at<cv::Point2f>(0, (int)i);
cv::Point2f res_gold = dst_gold[i];
ASSERT_LE(cv::norm(res_gold - res) / cv::norm(res_gold), 1e-3f);
@@ -291,7 +291,7 @@ TEST_P(SolvePnPRansac, Accuracy)
cv::Mat rvec, tvec;
std::vector<int> inliers;
cv::gpu::solvePnPRansac(object, cv::Mat(1, image_vec.size(), CV_32FC2, &image_vec[0]),
cv::gpu::solvePnPRansac(object, cv::Mat(1, (int)image_vec.size(), CV_32FC2, &image_vec[0]),
camera_mat, cv::Mat(1, 8, CV_32F, cv::Scalar::all(0)),
rvec, tvec, false, 200, 2.f, 100, &inliers);
+1 -1
View File
@@ -244,7 +244,7 @@ TEST_P(PyrLKOpticalFlow, Sparse)
cv::goodFeaturesToTrack(gray_frame, pts, 1000, 0.01, 0.0);
cv::gpu::GpuMat d_pts;
cv::Mat pts_mat(1, pts.size(), CV_32FC2, (void*)&pts[0]);
cv::Mat pts_mat(1, (int)pts.size(), CV_32FC2, (void*)&pts[0]);
d_pts.upload(pts_mat);
cv::gpu::PyrLKOpticalFlow pyrLK;
+1 -1
View File
@@ -195,7 +195,7 @@ Mat getMat(InputArray arr)
return arr.getMat();
}
double checkNorm(InputArray m1, const InputArray m2)
double checkNorm(InputArray m1, InputArray m2)
{
return norm(getMat(m1), getMat(m2), NORM_INF);
}
+109 -102
View File
@@ -52,19 +52,12 @@ set(grfmt_srcs src/bitstrm.cpp ${grfmt_srcs})
source_group("Src\\grfmts" FILES ${grfmt_hdrs} ${grfmt_srcs})
set(highgui_hdrs src/precomp.hpp src/utils.hpp)
if(NEW_FFMPEG)
set(highgui_srcs
src/cap.cpp
src/cap_images.cpp
src/cap_ffmpeg_v2.cpp
src/loadsave.cpp
src/precomp.cpp
src/utils.cpp
src/window.cpp
)
set(highgui_hdrs src/precomp.hpp src/utils.hpp src/cap_ffmpeg_impl_v2.hpp)
else()
set(highgui_hdrs src/precomp.hpp src/utils.hpp src/cap_ffmpeg_impl.hpp)
endif()
set(highgui_srcs
src/cap.cpp
src/cap_images.cpp
@@ -74,129 +67,144 @@ set(highgui_srcs
src/utils.cpp
src/window.cpp
)
endif()
file(GLOB highgui_ext_hdrs "include/opencv2/${name}/*.hpp" "include/opencv2/${name}/*.h")
#YV
if (HAVE_QT)
if (HAVE_QT_OPENGL)
set(QT_USE_QTOPENGL TRUE)
endif()
INCLUDE(${QT_USE_FILE})
SET(_RCCS_FILES src/window_QT.qrc)
QT4_ADD_RESOURCES(_RCC_OUTFILES ${_RCCS_FILES})
if (HAVE_QT_OPENGL)
set(QT_USE_QTOPENGL TRUE)
endif()
INCLUDE(${QT_USE_FILE})
SET(_MOC_HEADERS src/window_QT.h )
QT4_WRAP_CPP(_MOC_OUTFILES ${_MOC_HEADERS})
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} ${QT_LIBRARIES} ${QT_QTTEST_LIBRARY})
set(highgui_srcs ${highgui_srcs} src/window_QT.cpp ${_MOC_OUTFILES} ${_RCC_OUTFILES} )
SET(_RCCS_FILES src/window_QT.qrc)
QT4_ADD_RESOURCES(_RCC_OUTFILES ${_RCCS_FILES})
SET(_MOC_HEADERS src/window_QT.h )
QT4_WRAP_CPP(_MOC_OUTFILES ${_MOC_HEADERS})
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} ${QT_LIBRARIES} ${QT_QTTEST_LIBRARY})
set(highgui_srcs ${highgui_srcs} src/window_QT.cpp ${_MOC_OUTFILES} ${_RCC_OUTFILES} )
endif()
if(WIN32)
if(NOT HAVE_QT)
set(highgui_srcs ${highgui_srcs} src/window_w32.cpp)
endif()
set(highgui_srcs ${highgui_srcs} src/cap_vfw.cpp src/cap_cmu.cpp src/cap_dshow.cpp)
if(HAVE_MIL)
set(highgui_srcs ${highgui_srcs} src/cap_mil.cpp)
endif()
if(NOT HAVE_QT)
set(highgui_srcs ${highgui_srcs} src/window_w32.cpp)
endif()
set(highgui_srcs ${highgui_srcs} src/cap_vfw.cpp src/cap_cmu.cpp src/cap_dshow.cpp)
if(HAVE_MIL)
set(highgui_srcs ${highgui_srcs} src/cap_mil.cpp)
endif()
endif()
if(UNIX)
if(NOT HAVE_QT)
if(HAVE_GTK)
set(highgui_srcs ${highgui_srcs} src/window_gtk.cpp)
endif()
if(NOT HAVE_QT)
if(HAVE_GTK)
set(highgui_srcs ${highgui_srcs} src/window_gtk.cpp)
endif()
endif()
if(HAVE_XINE)
set(highgui_srcs ${highgui_srcs} src/cap_xine.cpp)
endif()
if(HAVE_XINE)
set(highgui_srcs ${highgui_srcs} src/cap_xine.cpp)
endif()
if(HAVE_DC1394_2)
set(highgui_srcs ${highgui_srcs} src/cap_dc1394_v2.cpp)
endif()
if(HAVE_DC1394_2)
set(highgui_srcs ${highgui_srcs} src/cap_dc1394_v2.cpp)
endif()
if(HAVE_DC1394)
set(highgui_srcs ${highgui_srcs} src/cap_dc1394.cpp)
endif()
if(HAVE_DC1394)
set(highgui_srcs ${highgui_srcs} src/cap_dc1394.cpp)
endif()
if(HAVE_FFMPEG)
if(BZIP2_LIBRARIES)
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} ${BZIP2_LIBRARIES})
endif()
if(HAVE_FFMPEG)
if(BZIP2_LIBRARIES)
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} ${BZIP2_LIBRARIES})
endif()
endif()
if(HAVE_PVAPI)
add_definitions(-DHAVE_PVAPI)
set(highgui_srcs src/cap_pvapi.cpp ${highgui_srcs})
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} PvAPI)
if(HAVE_PVAPI)
add_definitions(-DHAVE_PVAPI)
ocv_include_directories(${PVAPI_INCLUDE_PATH})
if(X86)
set(PVAPI_SDK_SUBDIR x86)
elseif(X86_64)
set(PVAPI_SDK_SUBDIR x64)
elseif(CMAKE_SYSTEM_PROCESSOR MATCHES arm)
set(PVAPI_SDK_SUBDIR arm)
endif()
if(HAVE_GSTREAMER)
set(highgui_srcs ${highgui_srcs} src/cap_gstreamer.cpp)
if(PVAPI_SDK_SUBDIR AND CMAKE_COMPILER_IS_GNUCXX)
get_filename_component(PVAPI_EXPECTED_LIB_PATH "${PVAPI_INCLUDE_PATH}/../lib-pc/${PVAPI_SDK_SUBDIR}/${CMAKE_OPENCV_GCC_VERSION_MAJOR}.${CMAKE_OPENCV_GCC_VERSION_MINOR}" ABSOLUTE)
link_directories(${PVAPI_EXPECTED_LIB_PATH})
endif()
set(highgui_srcs src/cap_pvapi.cpp ${highgui_srcs})
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} PvAPI)
endif()
if(HAVE_UNICAP)
set(highgui_srcs ${highgui_srcs} src/cap_unicap.cpp)
if(HAVE_GSTREAMER)
set(highgui_srcs ${highgui_srcs} src/cap_gstreamer.cpp)
endif()
if(HAVE_UNICAP)
set(highgui_srcs ${highgui_srcs} src/cap_unicap.cpp)
endif()
if(HAVE_LIBV4L)
set(highgui_srcs ${highgui_srcs} src/cap_libv4l.cpp)
else()
if(HAVE_CAMV4L OR HAVE_CAMV4L2)
set(highgui_srcs ${highgui_srcs} src/cap_v4l.cpp)
endif()
endif()
if(HAVE_LIBV4L)
set(highgui_srcs ${highgui_srcs} src/cap_libv4l.cpp)
else()
if(HAVE_CAMV4L OR HAVE_CAMV4L2)
set(highgui_srcs ${highgui_srcs} src/cap_v4l.cpp)
endif()
endif()
foreach(P ${HIGHGUI_INCLUDE_DIRS})
ocv_include_directories(${P})
endforeach()
foreach(P ${HIGHGUI_INCLUDE_DIRS})
ocv_include_directories(${P})
endforeach()
foreach(P ${HIGHGUI_LIBRARY_DIRS})
link_directories(${P})
endforeach()
foreach(P ${HIGHGUI_LIBRARY_DIRS})
link_directories(${P})
endforeach()
endif()
#OpenNI
if(WITH_OPENNI AND HAVE_OPENNI)
set(highgui_srcs ${highgui_srcs} src/cap_openni.cpp)
ocv_include_directories(${OPENNI_INCLUDE_DIR})
set(highgui_srcs ${highgui_srcs} src/cap_openni.cpp)
ocv_include_directories(${OPENNI_INCLUDE_DIR})
endif()
#YV
if(APPLE)
if (NOT IOS)
add_definitions(-DHAVE_QUICKTIME=1)
endif()
if (NOT IOS)
add_definitions(-DHAVE_QUICKTIME=1)
endif()
if(NOT OPENCV_BUILD_3RDPARTY_LIBS)
add_definitions(-DHAVE_IMAGEIO=1)
endif()
if(NOT OPENCV_BUILD_3RDPARTY_LIBS)
add_definitions(-DHAVE_IMAGEIO=1)
endif()
if (NOT HAVE_QT)
if(WITH_CARBON)
add_definitions(-DHAVE_CARBON=1)
set(highgui_srcs ${highgui_srcs} src/window_carbon.cpp)
else()
add_definitions(-DHAVE_COCOA=1)
set(highgui_srcs ${highgui_srcs} src/window_cocoa.mm)
endif()
endif()
if(WITH_QUICKTIME)
set(highgui_srcs ${highgui_srcs} src/cap_qt.cpp)
if (NOT HAVE_QT)
if(WITH_CARBON)
add_definitions(-DHAVE_CARBON=1)
set(highgui_srcs ${highgui_srcs} src/window_carbon.cpp)
else()
if (WITH_AVFOUNDATION)
add_definitions(-DHAVE_AVFOUNDATION=1)
set(highgui_srcs ${highgui_srcs} src/cap_avfoundation.mm)
else()
set(highgui_srcs ${highgui_srcs} src/cap_qtkit.mm)
endif()
add_definitions(-DHAVE_COCOA=1)
set(highgui_srcs ${highgui_srcs} src/window_cocoa.mm)
endif()
endif()
if(WITH_QUICKTIME)
set(highgui_srcs ${highgui_srcs} src/cap_qt.cpp)
else()
if(WITH_AVFOUNDATION)
add_definitions(-DHAVE_AVFOUNDATION=1)
set(highgui_srcs ${highgui_srcs} src/cap_avfoundation.mm)
else()
set(highgui_srcs ${highgui_srcs} src/cap_qtkit.mm)
endif()
endif()
if(HAVE_FFMPEG)
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} "-framework VideoDecodeAcceleration")
endif()
endif(APPLE)
if(HAVE_opencv_androidcamera)
@@ -234,14 +242,13 @@ if(IOS)
endif()
if(WIN32)
link_directories("${CMAKE_CURRENT_SOURCE_DIR}/../../3rdparty/lib")
include_directories(AFTER "${CMAKE_CURRENT_SOURCE_DIR}/../../3rdparty/include") #for directshow
link_directories("${OpenCV_SOURCE_DIR}/3rdparty/lib")
include_directories(AFTER "${OpenCV_SOURCE_DIR}/3rdparty/include") #for directshow
endif()
source_group("Src" FILES ${highgui_srcs} ${highgui_hdrs})
source_group("Include" FILES ${highgui_ext_hdrs})
ocv_set_module_sources(HEADERS ${highgui_ext_hdrs} SOURCES ${highgui_srcs} ${highgui_hdrs} ${grfmt_srcs} ${grfmt_hdrs})
ocv_module_include_directories()
ocv_create_module(${GRFMT_LIBS} ${HIGHGUI_LIBRARIES})
@@ -259,11 +266,11 @@ set_target_properties(${the_module} PROPERTIES LINK_INTERFACE_LIBRARIES "")
ocv_add_precompiled_headers(${the_module})
if(CMAKE_COMPILER_IS_GNUCXX)
if(CMAKE_COMPILER_IS_GNUCXX AND NOT ENABLE_NOISY_WARNINGS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations")
endif()
if(WIN32)
if(WIN32 AND WITH_FFMPEG)
#copy ffmpeg dll to the output folder
if(MSVC64 OR MINGW64)
set(FFMPEG_SUFFIX _64)
+1 -1
View File
@@ -8,7 +8,7 @@ applications and can be used within functionally rich UI frameworks (such as Qt*
It provides easy interface to:
* Create and manipulate windows that can display images and "remember" their content (no need to handle repaint events from OS).
* Add trackbars to the windows, handle simple mouse events as well as keyboard commmands.
* Add trackbars to the windows, handle simple mouse events as well as keyboard commands.
* Read and write images to/from disk or memory.
* Read video from camera or file and write video to a file.
+3 -3
View File
@@ -105,7 +105,7 @@ Provides parameters of a window.
:param name: Name of the window.
:param prop_id: Window property to retrive. The following operation flags are available:
:param prop_id: Window property to retrieve. The following operation flags are available:
* **CV_WND_PROP_FULLSCREEN** Change if the window is fullscreen ( ``CV_WINDOW_NORMAL`` or ``CV_WINDOW_FULLSCREEN`` ).
@@ -224,11 +224,11 @@ Displays a text on the window statusbar during the specified period of time.
The function ``displayOverlay`` displays useful information/tips on top of the window for a certain amount of time
*delayms*
. This information is displayed on the window statubar (the window must be created with the ``CV_GUI_EXPANDED`` flags).
. This information is displayed on the window statusbar (the window must be created with the ``CV_GUI_EXPANDED`` flags).
createOpenGLCallback
------------------------
Creates a callback function called to draw OpenGL on top the the image display by ``windowname``.
Creates a callback function called to draw OpenGL on top the image display by ``windowname``.
.. ocv:function:: void createOpenGLCallback( const string& window_name, OpenGLCallback callbackOpenGL, void* userdata =NULL, double angle=-1, double zmin=-1, double zmax=-1)
@@ -128,6 +128,51 @@ The function ``imwrite`` saves the image to the specified file. The image format
:ocv:func:`Mat::convertTo` , and
:ocv:func:`cvtColor` to convert it before saving. Or, use the universal XML I/O functions to save the image to XML or YAML format.
It is possible to store PNG images with an alpha channel using this function. To do this, create 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535. The sample below shows how to create such a BGRA image and store to PNG file. It also demonstrates how to set custom compression parameters ::
#include <vector>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void createAlphaMat(Mat &mat)
{
for (int i = 0; i < mat.rows; ++i) {
for (int j = 0; j < mat.cols; ++j) {
Vec4b& rgba = mat.at<Vec4b>(i, j);
rgba[0] = UCHAR_MAX;
rgba[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX);
rgba[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX);
rgba[3] = saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2]));
}
}
}
int main(int argv, char **argc)
{
// Create mat with alpha channel
Mat mat(480, 640, CV_8UC4);
createAlphaMat(mat);
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
try {
imwrite("alpha.png", mat, compression_params);
}
catch (runtime_error& ex) {
fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
return 1;
}
fprintf(stdout, "Saved PNG file with alpha data.\n");
return 0;
}
VideoCapture
------------
.. ocv:class:: VideoCapture
@@ -264,7 +309,7 @@ Decodes and returns the grabbed video frame.
.. ocv:pyoldfunction:: cv.RetrieveFrame(capture) -> iplimage
The methods/functions decode and retruen the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
The methods/functions decode and return the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
.. note:: OpenCV 1.x functions ``cvRetrieveFrame`` and ``cv.RetrieveFrame`` return image stored inside the video capturing structure. It is not allowed to modify or release the image! You can copy the frame using :ocv:cfunc:`cvCloneImage` and then do whatever you want with the copy.
@@ -283,7 +328,7 @@ Grabs, decodes and returns the next video frame.
.. ocv:pyoldfunction:: cv.QueryFrame(capture) -> iplimage
The methods/functions combine :ocv:func:`VideoCapture::grab` and :ocv:func:`VideoCapture::retrieve` in one call. This is the most convenient method for reading video files or capturing data from decode and retruen the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
The methods/functions combine :ocv:func:`VideoCapture::grab` and :ocv:func:`VideoCapture::retrieve` in one call. This is the most convenient method for reading video files or capturing data from decode and return the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
.. note:: OpenCV 1.x functions ``cvRetrieveFrame`` and ``cv.RetrieveFrame`` return image stored inside the video capturing structure. It is not allowed to modify or release the image! You can copy the frame using :ocv:cfunc:`cvCloneImage` and then do whatever you want with the copy.
+1 -1
View File
@@ -24,7 +24,7 @@ Creates a trackbar and attaches it to the specified window.
:param userdata: User data that is passed as is to the callback. It can be used to handle trackbar events without using global variables.
The function ``createTrackbar`` creates a trackbar (a slider or range control) with the specified name and range, assigns a variable ``value`` to be a position syncronized with the trackbar and specifies the callback function ``onChange`` to be called on the trackbar position change. The created trackbar is displayed in the specified window ``winname``.
The function ``createTrackbar`` creates a trackbar (a slider or range control) with the specified name and range, assigns a variable ``value`` to be a position synchronized with the trackbar and specifies the callback function ``onChange`` to be called on the trackbar position change. The created trackbar is displayed in the specified window ``winname``.
.. note::
@@ -232,8 +232,9 @@ public:
virtual ~VideoWriter();
CV_WRAP virtual bool open(const string& filename, int fourcc, double fps,
Size frameSize, bool isColor=true);
Size frameSize, bool isColor=true);
CV_WRAP virtual bool isOpened() const;
CV_WRAP virtual void release();
virtual VideoWriter& operator << (const Mat& image);
CV_WRAP virtual void write(const Mat& image);
@@ -436,6 +436,16 @@ enum
CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %)
CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds
// Properties for Android cameras
CV_CAP_PROP_ANDROID_FLASH_MODE = 8001,
CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002,
CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003,
CV_CAP_PROP_ANDROID_ANTIBANDING = 8004,
CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008,
// Properties of cameras available through AVFOUNDATION interface
CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001,
CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002,
@@ -477,6 +487,45 @@ enum
CV_CAP_ANDROID_COLOR_FRAME_RGBA = 4
};
// supported Android camera flash modes
enum {
CV_CAP_ANDROID_FLASH_MODE_AUTO = 0,
CV_CAP_ANDROID_FLASH_MODE_OFF,
CV_CAP_ANDROID_FLASH_MODE_ON,
CV_CAP_ANDROID_FLASH_MODE_RED_EYE,
CV_CAP_ANDROID_FLASH_MODE_TORCH
};
// supported Android camera focus modes
enum {
CV_CAP_ANDROID_FOCUS_MODE_AUTO = 0,
CV_CAP_ANDROID_FOCUS_MODE_CONTINUOUS_VIDEO,
CV_CAP_ANDROID_FOCUS_MODE_EDOF,
CV_CAP_ANDROID_FOCUS_MODE_FIXED,
CV_CAP_ANDROID_FOCUS_MODE_INFINITY,
CV_CAP_ANDROID_FOCUS_MODE_MACRO
};
// supported Android camera white balance modes
enum {
CV_CAP_ANDROID_WHITE_BALANCE_AUTO = 0,
CV_CAP_ANDROID_WHITE_BALANCE_CLOUDY_DAYLIGHT,
CV_CAP_ANDROID_WHITE_BALANCE_DAYLIGHT,
CV_CAP_ANDROID_WHITE_BALANCE_FLUORESCENT,
CV_CAP_ANDROID_WHITE_BALANCE_INCANDESCENT,
CV_CAP_ANDROID_WHITE_BALANCE_SHADE,
CV_CAP_ANDROID_WHITE_BALANCE_TWILIGHT,
CV_CAP_ANDROID_WHITE_BALANCE_WARM_FLUORESCENT
};
// supported Android camera antibanding modes
enum {
CV_CAP_ANDROID_ANTIBANDING_50HZ = 0,
CV_CAP_ANDROID_ANTIBANDING_60HZ,
CV_CAP_ANDROID_ANTIBANDING_AUTO,
CV_CAP_ANDROID_ANTIBANDING_OFF
};
/* retrieve or set capture properties */
CVAPI(double) cvGetCaptureProperty( CvCapture* capture, int property_id );
CVAPI(int) cvSetCaptureProperty( CvCapture* capture, int property_id, double value );
+27
View File
@@ -0,0 +1,27 @@
#include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
typedef std::tr1::tuple<String, bool> VideoCapture_Reading_t;
typedef perf::TestBaseWithParam<VideoCapture_Reading_t> VideoCapture_Reading;
PERF_TEST_P(VideoCapture_Reading, ReadFile,
testing::Combine( testing::Values( "highgui/video/big_buck_bunny.avi",
"highgui/video/big_buck_bunny.mov",
"highgui/video/big_buck_bunny.mp4",
"highgui/video/big_buck_bunny.mpg",
"highgui/video/big_buck_bunny.wmv" ),
testing::Values(true, true, true, true, true) ))
{
string filename = getDataPath(get<0>(GetParam()));
VideoCapture cap;
TEST_CYCLE() cap.open(filename);
SANITY_CHECK(cap.isOpened());
}
+3
View File
@@ -0,0 +1,3 @@
#include "perf_precomp.hpp"
CV_PERF_TEST_MAIN(highgui)
+29
View File
@@ -0,0 +1,29 @@
#include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
typedef std::tr1::tuple<String, bool> VideoWriter_Writing_t;
typedef perf::TestBaseWithParam<VideoWriter_Writing_t> VideoWriter_Writing;
PERF_TEST_P(VideoWriter_Writing, WriteFrame,
testing::Combine( testing::Values( "python/images/QCIF_00.bmp",
"python/images/QCIF_01.bmp",
"python/images/QCIF_02.bmp",
"python/images/QCIF_03.bmp",
"python/images/QCIF_04.bmp",
"python/images/QCIF_05.bmp" ),
testing::Bool()))
{
string filename = getDataPath(get<0>(GetParam()));
bool isColor = get<1>(GetParam());
VideoWriter writer("perf_writer.avi", CV_FOURCC('X', 'V', 'I', 'D'), 25, cv::Size(640, 480), isColor);
TEST_CYCLE() { Mat image = imread(filename, 1); writer << image; }
SANITY_CHECK(writer.isOpened());
}
+1
View File
@@ -0,0 +1 @@
#include "perf_precomp.hpp"
+11
View File
@@ -0,0 +1,11 @@
#ifndef __OPENCV_PERF_PRECOMP_HPP__
#define __OPENCV_PERF_PRECOMP_HPP__
#include "opencv2/ts/ts.hpp"
#include "opencv2/highgui/highgui.hpp"
#if GTEST_CREATE_SHARED_LIBRARY
#error no modules except ts should have GTEST_CREATE_SHARED_LIBRARY defined
#endif
#endif
+6 -1
View File
@@ -493,9 +493,14 @@ VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size fr
open(filename, fourcc, fps, frameSize, isColor);
}
VideoWriter::~VideoWriter()
void VideoWriter::release()
{
writer.release();
}
VideoWriter::~VideoWriter()
{
release();
}
bool VideoWriter::open(const string& filename, int fourcc, double fps, Size frameSize, bool isColor)
+36 -4
View File
@@ -263,11 +263,30 @@ double CvCapture_Android::getProperty( int propIdx )
return (double)m_activity->getFrameWidth();
case CV_CAP_PROP_FRAME_HEIGHT:
return (double)m_activity->getFrameHeight();
case CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_SUPPORTED_PREVIEW_SIZES_STRING);
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_SUPPORTED_PREVIEW_SIZES_STRING);
case CV_CAP_PROP_PREVIEW_FORMAT:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_PREVIEW_FORMAT_STRING);
case CV_CAP_PROP_FPS:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FPS);
case CV_CAP_PROP_EXPOSURE:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_EXPOSURE);
case CV_CAP_PROP_ANDROID_FLASH_MODE:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FLASH_MODE);
case CV_CAP_PROP_ANDROID_FOCUS_MODE:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_MODE);
case CV_CAP_PROP_ANDROID_WHITE_BALANCE:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_WHITE_BALANCE);
case CV_CAP_PROP_ANDROID_ANTIBANDING:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_ANTIBANDING);
case CV_CAP_PROP_ANDROID_FOCAL_LENGTH:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCAL_LENGTH);
case CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_NEAR);
case CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_OPTIMAL);
case CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR:
return (double)m_activity->getProperty(ANDROID_CAMERA_PROPERTY_FOCUS_DISTANCE_FAR);
default:
CV_Error( CV_StsOutOfRange, "Failed attempt to GET unsupported camera property." );
break;
@@ -288,11 +307,24 @@ bool CvCapture_Android::setProperty( int propIdx, double propValue )
case CV_CAP_PROP_FRAME_HEIGHT:
m_activity->setProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT, propValue);
break;
case CV_CAP_PROP_AUTOGRAB:
m_shouldAutoGrab=(propValue != 0);
break;
case CV_CAP_PROP_EXPOSURE:
m_activity->setProperty(ANDROID_CAMERA_PROPERTY_EXPOSURE, propValue);
break;
case CV_CAP_PROP_ANDROID_FLASH_MODE:
m_activity->setProperty(ANDROID_CAMERA_PROPERTY_FLASH_MODE, propValue);
break;
case CV_CAP_PROP_ANDROID_FOCUS_MODE:
m_activity->setProperty(ANDROID_CAMERA_PROPERTY_FOCUS_MODE, propValue);
break;
case CV_CAP_PROP_ANDROID_WHITE_BALANCE:
m_activity->setProperty(ANDROID_CAMERA_PROPERTY_WHITE_BALANCE, propValue);
break;
case CV_CAP_PROP_ANDROID_ANTIBANDING:
m_activity->setProperty(ANDROID_CAMERA_PROPERTY_ANTIBANDING, propValue);
break;
default:
CV_Error( CV_StsOutOfRange, "Failed attempt to SET unsupported camera property." );
return false;
+18 -9
View File
@@ -207,6 +207,7 @@ DEFINE_GUID(MEDIASUBTYPE_RGB24,0xe436eb7d,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf
DEFINE_GUID(MEDIASUBTYPE_RGB32,0xe436eb7e,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70);
DEFINE_GUID(MEDIASUBTYPE_RGB555,0xe436eb7c,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70);
DEFINE_GUID(MEDIASUBTYPE_RGB565,0xe436eb7b,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70);
DEFINE_GUID(MEDIASUBTYPE_I420,0x49343230,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71);
DEFINE_GUID(MEDIASUBTYPE_UYVY,0x59565955,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71);
DEFINE_GUID(MEDIASUBTYPE_Y211,0x31313259,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71);
DEFINE_GUID(MEDIASUBTYPE_Y411,0x31313459,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71);
@@ -339,7 +340,7 @@ static bool verbose = true;
//videoInput defines
#define VI_VERSION 0.1995
#define VI_MAX_CAMERAS 20
#define VI_NUM_TYPES 19 //MGB
#define VI_NUM_TYPES 20 //MGB
#define VI_NUM_FORMATS 18 //DON'T TOUCH
//defines for setPhyCon - tuner is not as well supported as composite and s-video
@@ -1066,6 +1067,7 @@ videoInput::videoInput(){
mediaSubtypes[16] = MEDIASUBTYPE_Y800;
mediaSubtypes[17] = MEDIASUBTYPE_Y8;
mediaSubtypes[18] = MEDIASUBTYPE_GREY;
mediaSubtypes[19] = MEDIASUBTYPE_I420;
//The video formats we support
formatTypes[VI_NTSC_M] = AnalogVideo_NTSC_M;
@@ -2171,6 +2173,7 @@ void videoInput::getMediaSubtypeAsString(GUID type, char * typeAsString){
else if(type == MEDIASUBTYPE_Y800) sprintf(tmpStr, "Y800");
else if(type == MEDIASUBTYPE_Y8) sprintf(tmpStr, "Y8");
else if(type == MEDIASUBTYPE_GREY) sprintf(tmpStr, "GREY");
else if(type == MEDIASUBTYPE_I420) sprintf(tmpStr, "I420");
else sprintf(tmpStr, "OTHER");
memcpy(typeAsString, tmpStr, sizeof(char)*8);
@@ -3279,8 +3282,7 @@ bool CvCaptureCAM_DShow::setProperty( int property_id, double value )
{
// image capture properties
bool handled = false;
switch( property_id )
switch( property_id )
{
case CV_CAP_PROP_FRAME_WIDTH:
width = cvRound(value);
@@ -3302,8 +3304,13 @@ bool CvCaptureCAM_DShow::setProperty( int property_id, double value )
break;
case CV_CAP_PROP_FPS:
VI.setIdealFramerate(index,cvRound(value));
handled = true;
int fps = cvRound(value);
if (fps != VI.getFPS(0))
{
VI.stopDevice(index);
VI.setIdealFramerate(index,fps);
VI.setupDevice(index);
}
break;
}
@@ -3311,16 +3318,18 @@ bool CvCaptureCAM_DShow::setProperty( int property_id, double value )
if ( handled ) {
// a stream setting
if( width > 0 && height > 0 )
{
if( width != VI.getWidth(index) || height != VI.getHeight(index) )//|| fourcc != VI.getFourcc(index) )
{
if( width != VI.getWidth(index) || height != VI.getHeight(index) ) //|| fourcc != VI.getFourcc(index) )
{
int fps = static_cast<int>(VI.getFPS(index));
VI.stopDevice(index);
VI.setupDeviceFourcc(index, width, height,fourcc);
VI.setIdealFramerate(index, fps);
VI.setupDeviceFourcc(index, width, height, fourcc);
}
width = height = fourcc = -1;
return VI.isDeviceSetup(index);
}
return true;
return true;
}
// show video/camera filter dialog
+4
View File
@@ -42,7 +42,11 @@
#include "precomp.hpp"
#ifdef HAVE_FFMPEG
#ifdef NEW_FFMPEG
#include "cap_ffmpeg_impl_v2.hpp"
#else
#include "cap_ffmpeg_impl.hpp"
#endif
#else
#include "cap_ffmpeg_api.hpp"
#endif
+366 -347
View File
@@ -245,7 +245,7 @@ void CvCapture_FFMPEG::init()
void CvCapture_FFMPEG::close()
{
if( picture )
av_free(picture);
av_free(picture);
if( video_st )
{
@@ -316,13 +316,13 @@ bool CvCapture_FFMPEG::reopen()
}
#ifndef AVSEEK_FLAG_FRAME
#define AVSEEK_FLAG_FRAME 0
#define AVSEEK_FLAG_FRAME 0
#endif
#ifndef AVSEEK_FLAG_ANY
#define AVSEEK_FLAG_ANY 1
#define AVSEEK_FLAG_ANY 1
#endif
#ifndef SHORTER_DISTANCE_FOR_SEEK_TO_MAKE_IT_FASTER
#define SHORTER_DISTANCE_FOR_SEEK_TO_MAKE_IT_FASTER 25
#define SHORTER_DISTANCE_FOR_SEEK_TO_MAKE_IT_FASTER 25
#endif
bool CvCapture_FFMPEG::open( const char* _filename )
@@ -358,24 +358,24 @@ bool CvCapture_FFMPEG::open( const char* _filename )
avcodec_thread_init(enc, get_number_of_cpus());
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
#define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
#endif
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
#define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
#endif
if( AVMEDIA_TYPE_VIDEO == enc->codec_type && video_stream < 0) {
AVCodec *codec = avcodec_find_decoder(enc->codec_id);
if (!codec ||
avcodec_open(enc, codec) < 0)
goto exit_func;
avcodec_open(enc, codec) < 0)
goto exit_func;
video_stream = i;
video_st = ic->streams[i];
picture = avcodec_alloc_frame();
rgb_picture.data[0] = (uint8_t*)malloc(
avpicture_get_size( PIX_FMT_BGR24,
enc->width, enc->height ));
avpicture_get_size( PIX_FMT_BGR24,
enc->width, enc->height ));
avpicture_fill( (AVPicture*)&rgb_picture, rgb_picture.data[0],
PIX_FMT_BGR24, enc->width, enc->height );
PIX_FMT_BGR24, enc->width, enc->height );
frame.width = enc->width;
frame.height = enc->height;
@@ -406,7 +406,7 @@ bool CvCapture_FFMPEG::open( const char* _filename )
int flags = AVSEEK_FLAG_FRAME | AVSEEK_FLAG_BACKWARD;
av_seek_frame(ic, video_stream, ts, flags);
}
exit_func:
exit_func:
if( !valid )
close();
@@ -445,22 +445,22 @@ bool CvCapture_FFMPEG::grabFrame()
break;
if( packet.stream_index != video_stream ) {
av_free_packet (&packet);
continue;
}
av_free_packet (&packet);
continue;
}
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
#else
#if LIBAVFORMAT_BUILD > 4628
avcodec_decode_video(video_st->codec,
picture, &got_picture,
packet.data, packet.size);
#else
avcodec_decode_video(&video_st->codec,
picture, &got_picture,
packet.data, packet.size);
#endif
#if LIBAVFORMAT_BUILD > 4628
avcodec_decode_video(video_st->codec,
picture, &got_picture,
packet.data, packet.size);
#else
avcodec_decode_video(&video_st->codec,
picture, &got_picture,
packet.data, packet.size);
#endif
#endif
if (got_picture) {
@@ -496,18 +496,18 @@ bool CvCapture_FFMPEG::retrieveFrame(int, unsigned char** data, int* step, int*
#endif
#else
img_convert_ctx = sws_getContext(video_st->codec->width,
video_st->codec->height,
video_st->codec->pix_fmt,
video_st->codec->width,
video_st->codec->height,
PIX_FMT_BGR24,
SWS_BICUBIC,
NULL, NULL, NULL);
video_st->codec->height,
video_st->codec->pix_fmt,
video_st->codec->width,
video_st->codec->height,
PIX_FMT_BGR24,
SWS_BICUBIC,
NULL, NULL, NULL);
sws_scale(img_convert_ctx, picture->data,
picture->linesize, 0,
video_st->codec->height,
rgb_picture.data, rgb_picture.linesize);
sws_scale(img_convert_ctx, picture->data,
picture->linesize, 0,
video_st->codec->height,
rgb_picture.data, rgb_picture.linesize);
sws_freeContext(img_convert_ctx);
#endif
*data = frame.data;
@@ -554,31 +554,43 @@ double CvCapture_FFMPEG::getProperty( int property_id )
if(video_st->cur_dts != AV_NOPTS_VALUE_ && video_st->duration != AV_NOPTS_VALUE_)
return(((video_st->cur_dts-video_st->first_dts)+(1.0/frameScale)) / (double)video_st->duration);
break;
case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
if(video_st->duration != AV_NOPTS_VALUE_)
return (double)ceil(ic->duration * av_q2d(video_st->r_frame_rate) / AV_TIME_BASE);
break;
case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
{
int64_t nbf = ic->streams[video_stream]->nb_frames;
double eps = 0.000025;
if (nbf == 0)
{
double fps = static_cast<double>(ic->streams[video_stream]->r_frame_rate.num) / static_cast<double>(ic->streams[video_stream]->r_frame_rate.den);
if (fps < eps)
{
fps = 1.0 / (static_cast<double>(ic->streams[video_stream]->codec->time_base.num) / static_cast<double>(ic->streams[video_stream]->codec->time_base.den));
}
nbf = static_cast<int64_t>(round(ic->duration * fps) / AV_TIME_BASE);
}
return nbf;
}
break;
case CV_FFMPEG_CAP_PROP_FRAME_WIDTH:
return (double)frame.width;
break;
break;
case CV_FFMPEG_CAP_PROP_FRAME_HEIGHT:
return (double)frame.height;
break;
break;
case CV_FFMPEG_CAP_PROP_FPS:
#if LIBAVCODEC_BUILD > 4753
return av_q2d (video_st->r_frame_rate);
#else
return (double)video_st->codec.frame_rate
/ (double)video_st->codec.frame_rate_base;
/ (double)video_st->codec.frame_rate_base;
#endif
break;
break;
case CV_FFMPEG_CAP_PROP_FOURCC:
#if LIBAVFORMAT_BUILD > 4628
return (double)video_st->codec->codec_tag;
#else
return (double)video_st->codec.codec_tag;
#endif
break;
break;
}
return 0;
@@ -605,24 +617,24 @@ bool CvCapture_FFMPEG::seekKeyAndRunOverFrames(int framenumber)
{
int ret;
if (framenumber > video_st->cur_dts-1) {
if (framenumber-(video_st->cur_dts-1) > SHORTER_DISTANCE_FOR_SEEK_TO_MAKE_IT_FASTER) {
ret = av_seek_frame(ic, video_stream, framenumber, 1);
assert(ret >= 0);
if( ret < 0 )
return false;
}
grabFrame();
while ((video_st->cur_dts-1) < framenumber)
if ( !grabFrame() ) return false;
if (framenumber-(video_st->cur_dts-1) > SHORTER_DISTANCE_FOR_SEEK_TO_MAKE_IT_FASTER) {
ret = av_seek_frame(ic, video_stream, framenumber, 1);
assert(ret >= 0);
if( ret < 0 )
return false;
}
grabFrame();
while ((video_st->cur_dts-1) < framenumber)
if ( !grabFrame() ) return false;
}
else if ( framenumber < (video_st->cur_dts-1) ) {
ret=av_seek_frame(ic, video_stream, framenumber, 1);
assert( ret >= 0 );
if( ret < 0 )
return false;
grabFrame();
while ((video_st->cur_dts-1) < framenumber )
if ( !grabFrame() ) return false;
ret=av_seek_frame(ic, video_stream, framenumber, 1);
assert( ret >= 0 );
if( ret < 0 )
return false;
grabFrame();
while ((video_st->cur_dts-1) < framenumber )
if ( !grabFrame() ) return false;
}
return true;
}
@@ -666,7 +678,7 @@ bool CvCapture_FFMPEG::setProperty( int property_id, double value )
if (!slowSeek((int)timestamp))
{
fprintf(stderr, "HIGHGUI ERROR: AVI: could not (slow) seek to position %0.3f\n",
(double)timestamp / AV_TIME_BASE);
(double)timestamp / AV_TIME_BASE);
return false;
}
}
@@ -674,7 +686,7 @@ bool CvCapture_FFMPEG::setProperty( int property_id, double value )
{
int flags = AVSEEK_FLAG_ANY;
if (timestamp < ic->streams[video_stream]->cur_dts)
flags |= AVSEEK_FLAG_BACKWARD;
flags |= AVSEEK_FLAG_BACKWARD;
int ret = av_seek_frame(ic, video_stream, timestamp, flags);
if (ret < 0)
{
@@ -698,7 +710,7 @@ bool CvCapture_FFMPEG::setProperty( int property_id, double value )
struct CvVideoWriter_FFMPEG
{
bool open( const char* filename, int fourcc,
double fps, int width, int height, bool isColor );
double fps, int width, int height, bool isColor );
void close();
bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );
@@ -724,34 +736,34 @@ static const char * icvFFMPEGErrStr(int err)
{
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
switch(err) {
case AVERROR_BSF_NOT_FOUND:
return "Bitstream filter not found";
case AVERROR_DECODER_NOT_FOUND:
return "Decoder not found";
case AVERROR_DEMUXER_NOT_FOUND:
return "Demuxer not found";
case AVERROR_ENCODER_NOT_FOUND:
return "Encoder not found";
case AVERROR_EOF:
return "End of file";
case AVERROR_EXIT:
return "Immediate exit was requested; the called function should not be restarted";
case AVERROR_FILTER_NOT_FOUND:
return "Filter not found";
case AVERROR_INVALIDDATA:
return "Invalid data found when processing input";
case AVERROR_MUXER_NOT_FOUND:
return "Muxer not found";
case AVERROR_OPTION_NOT_FOUND:
return "Option not found";
case AVERROR_PATCHWELCOME:
return "Not yet implemented in FFmpeg, patches welcome";
case AVERROR_PROTOCOL_NOT_FOUND:
return "Protocol not found";
case AVERROR_STREAM_NOT_FOUND:
return "Stream not found";
default:
break;
case AVERROR_BSF_NOT_FOUND:
return "Bitstream filter not found";
case AVERROR_DECODER_NOT_FOUND:
return "Decoder not found";
case AVERROR_DEMUXER_NOT_FOUND:
return "Demuxer not found";
case AVERROR_ENCODER_NOT_FOUND:
return "Encoder not found";
case AVERROR_EOF:
return "End of file";
case AVERROR_EXIT:
return "Immediate exit was requested; the called function should not be restarted";
case AVERROR_FILTER_NOT_FOUND:
return "Filter not found";
case AVERROR_INVALIDDATA:
return "Invalid data found when processing input";
case AVERROR_MUXER_NOT_FOUND:
return "Muxer not found";
case AVERROR_OPTION_NOT_FOUND:
return "Option not found";
case AVERROR_PATCHWELCOME:
return "Not yet implemented in FFmpeg, patches welcome";
case AVERROR_PROTOCOL_NOT_FOUND:
return "Protocol not found";
case AVERROR_STREAM_NOT_FOUND:
return "Stream not found";
default:
break;
}
#else
switch(err) {
@@ -818,7 +830,7 @@ static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bo
return NULL;
}
avpicture_fill((AVPicture *)picture, picture_buf,
(PixelFormat) pix_fmt, width, height);
(PixelFormat) pix_fmt, width, height);
}
else {
}
@@ -875,11 +887,11 @@ static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
of which frame timestamps are represented. for fixed-fps content,
timebase should be 1/framerate and timestamp increments should be
identically 1. */
frame_rate = static_cast<int>(fps+0.5);
frame_rate_base = 1;
while (fabs(static_cast<double>(frame_rate)/frame_rate_base) - fps > 0.001){
frame_rate_base *= 10;
frame_rate = static_cast<int>(fps*frame_rate_base + 0.5);
frame_rate = static_cast<int>(fps+0.5);
frame_rate_base = 1;
while (fabs(static_cast<double>(frame_rate)/frame_rate_base) - fps > 0.001){
frame_rate_base *= 10;
frame_rate = static_cast<int>(fps*frame_rate_base + 0.5);
}
#if LIBAVFORMAT_BUILD > 4752
c->time_base.den = frame_rate;
@@ -947,9 +959,9 @@ int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st, uint8_
AVPacket pkt;
av_init_packet(&pkt);
#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif
#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif
pkt.flags |= PKT_FLAG_KEY;
pkt.stream_index= video_st->index;
@@ -966,7 +978,8 @@ int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st, uint8_
av_init_packet(&pkt);
#if LIBAVFORMAT_BUILD > 4752
pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
if(c->coded_frame->pts != (int64_t)AV_NOPTS_VALUE)
pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
#else
pkt.pts = c->coded_frame->pts;
#endif
@@ -1054,7 +1067,7 @@ bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int
}
// check if buffer sizes match, i.e. image has expected format (size, channels, bitdepth, alignment)
/*#if LIBAVCODEC_VERSION_INT >= ((52<<16)+(37<<8)+0)
/*#if LIBAVCODEC_VERSION_INT >= ((52<<16)+(37<<8)+0)
assert (image->imageSize == avpicture_get_size( (PixelFormat)input_pix_fmt, image->width, image->height ));
#else
assert (image->imageSize == avpicture_get_size( input_pix_fmt, image->width, image->height ));
@@ -1064,38 +1077,38 @@ bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int
assert( input_picture );
// let input_picture point to the raw data buffer of 'image'
avpicture_fill((AVPicture *)input_picture, (uint8_t *) data,
(PixelFormat)input_pix_fmt, width, height);
(PixelFormat)input_pix_fmt, width, height);
#if !defined(HAVE_FFMPEG_SWSCALE)
// convert to the color format needed by the codec
if( img_convert((AVPicture *)picture, c->pix_fmt,
(AVPicture *)input_picture, (PixelFormat)input_pix_fmt,
width, height) < 0){
(AVPicture *)input_picture, (PixelFormat)input_pix_fmt,
width, height) < 0){
return false;
}
#else
img_convert_ctx = sws_getContext(width,
height,
(PixelFormat)input_pix_fmt,
c->width,
c->height,
c->pix_fmt,
SWS_BICUBIC,
NULL, NULL, NULL);
height,
(PixelFormat)input_pix_fmt,
c->width,
c->height,
c->pix_fmt,
SWS_BICUBIC,
NULL, NULL, NULL);
if ( sws_scale(img_convert_ctx, input_picture->data,
input_picture->linesize, 0,
height,
picture->data, picture->linesize) < 0 )
{
return false;
}
if ( sws_scale(img_convert_ctx, input_picture->data,
input_picture->linesize, 0,
height,
picture->data, picture->linesize) < 0 )
{
return false;
}
sws_freeContext(img_convert_ctx);
#endif
}
else{
avpicture_fill((AVPicture *)picture, (uint8_t *) data,
(PixelFormat)input_pix_fmt, width, height);
(PixelFormat)input_pix_fmt, width, height);
}
ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, picture) >= 0;
@@ -1124,306 +1137,312 @@ void CvVideoWriter_FFMPEG::close()
#if LIBAVFORMAT_BUILD > 4628
if( video_st->codec->pix_fmt != input_pix_fmt){
#else
if( video_st->codec.pix_fmt != input_pix_fmt){
if( video_st->codec.pix_fmt != input_pix_fmt){
#endif
if(picture->data[0])
free(picture->data[0]);
picture->data[0] = 0;
}
av_free(picture);
if(picture->data[0])
free(picture->data[0]);
picture->data[0] = 0;
}
av_free(picture);
if (input_picture) {
av_free(input_picture);
}
if (input_picture) {
av_free(input_picture);
}
/* close codec */
/* close codec */
#if LIBAVFORMAT_BUILD > 4628
avcodec_close(video_st->codec);
avcodec_close(video_st->codec);
#else
avcodec_close(&(video_st->codec));
avcodec_close(&(video_st->codec));
#endif
av_free(outbuf);
av_free(outbuf);
/* free the streams */
for(i = 0; i < oc->nb_streams; i++) {
av_freep(&oc->streams[i]->codec);
av_freep(&oc->streams[i]);
}
/* free the streams */
for(i = 0; i < oc->nb_streams; i++) {
av_freep(&oc->streams[i]->codec);
av_freep(&oc->streams[i]);
}
if (!(fmt->flags & AVFMT_NOFILE)) {
/* close the output file */
if (!(fmt->flags & AVFMT_NOFILE)) {
/* close the output file */
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
url_fclose(oc->pb);
url_fclose(oc->pb);
#else
url_fclose(&oc->pb);
url_fclose(&oc->pb);
#endif
}
}
/* free the stream */
av_free(oc);
/* free the stream */
av_free(oc);
if( temp_image.data )
{
free(temp_image.data);
temp_image.data = 0;
if( temp_image.data )
{
free(temp_image.data);
temp_image.data = 0;
}
init();
}
init();
}
/// Create a video writer object that uses FFMPEG
bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
double fps, int width, int height, bool is_color )
{
CodecID codec_id = CODEC_ID_NONE;
/// Create a video writer object that uses FFMPEG
bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
double fps, int width, int height, bool is_color )
{
CodecID codec_id = CODEC_ID_NONE;
int err, codec_pix_fmt, bitrate_scale = 64;
close();
close();
// check arguments
// check arguments
assert(filename);
assert(fps > 0);
assert(width > 0 && height > 0);
// tell FFMPEG to register codecs
// tell FFMPEG to register codecs
av_register_all();
/* auto detect the output format from the name and fourcc code. */
/* auto detect the output format from the name and fourcc code. */
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
fmt = av_guess_format(NULL, filename, NULL);
fmt = av_guess_format(NULL, filename, NULL);
#else
fmt = guess_format(NULL, filename, NULL);
fmt = guess_format(NULL, filename, NULL);
#endif
if (!fmt)
return false;
/* determine optimal pixel format */
if (is_color) {
input_pix_fmt = PIX_FMT_BGR24;
}
else {
input_pix_fmt = PIX_FMT_GRAY8;
}
if (!fmt)
return false;
/* Lookup codec_id for given fourcc */
/* determine optimal pixel format */
if (is_color) {
input_pix_fmt = PIX_FMT_BGR24;
}
else {
input_pix_fmt = PIX_FMT_GRAY8;
}
/* Lookup codec_id for given fourcc */
#if LIBAVCODEC_VERSION_INT<((51<<16)+(49<<8)+0)
if( (codec_id = codec_get_bmp_id( fourcc )) == CODEC_ID_NONE )
return false;
if( (codec_id = codec_get_bmp_id( fourcc )) == CODEC_ID_NONE )
return false;
#else
const struct AVCodecTag * tags[] = { codec_bmp_tags, NULL};
if( (codec_id = av_codec_get_id(tags, fourcc)) == CODEC_ID_NONE )
return false;
const struct AVCodecTag * tags[] = { codec_bmp_tags, NULL};
if( (codec_id = av_codec_get_id(tags, fourcc)) == CODEC_ID_NONE )
return false;
#endif
// alloc memory for context
// alloc memory for context
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
oc = avformat_alloc_context();
oc = avformat_alloc_context();
#else
oc = av_alloc_format_context();
oc = av_alloc_format_context();
#endif
assert (oc);
assert (oc);
/* set file name */
oc->oformat = fmt;
snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
/* set file name */
oc->oformat = fmt;
snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
/* set some options */
oc->max_delay = (int)(0.7*AV_TIME_BASE); /* This reduces buffer underrun warnings with MPEG */
/* set some options */
oc->max_delay = (int)(0.7*AV_TIME_BASE); /* This reduces buffer underrun warnings with MPEG */
// set a few optimal pixel formats for lossless codecs of interest..
switch (codec_id) {
// set a few optimal pixel formats for lossless codecs of interest..
switch (codec_id) {
#if LIBAVCODEC_VERSION_INT>((50<<16)+(1<<8)+0)
case CODEC_ID_JPEGLS:
// BGR24 or GRAY8 depending on is_color...
codec_pix_fmt = input_pix_fmt;
break;
case CODEC_ID_JPEGLS:
// BGR24 or GRAY8 depending on is_color...
codec_pix_fmt = input_pix_fmt;
break;
#endif
case CODEC_ID_HUFFYUV:
codec_pix_fmt = PIX_FMT_YUV422P;
break;
case CODEC_ID_MJPEG:
case CODEC_ID_LJPEG:
codec_pix_fmt = PIX_FMT_YUVJ420P;
bitrate_scale = 128;
break;
case CODEC_ID_RAWVIDEO:
codec_pix_fmt = input_pix_fmt == PIX_FMT_GRAY8 ||
input_pix_fmt == PIX_FMT_GRAY16LE ||
input_pix_fmt == PIX_FMT_GRAY16BE ? input_pix_fmt : PIX_FMT_YUV420P;
break;
default:
// good for lossy formats, MPEG, etc.
codec_pix_fmt = PIX_FMT_YUV420P;
break;
}
case CODEC_ID_HUFFYUV:
codec_pix_fmt = PIX_FMT_YUV422P;
break;
case CODEC_ID_MJPEG:
case CODEC_ID_LJPEG:
codec_pix_fmt = PIX_FMT_YUVJ420P;
bitrate_scale = 128;
break;
case CODEC_ID_RAWVIDEO:
codec_pix_fmt = input_pix_fmt == PIX_FMT_GRAY8 ||
input_pix_fmt == PIX_FMT_GRAY16LE ||
input_pix_fmt == PIX_FMT_GRAY16BE ? input_pix_fmt : PIX_FMT_YUV420P;
break;
default:
// good for lossy formats, MPEG, etc.
codec_pix_fmt = PIX_FMT_YUV420P;
break;
}
// TODO -- safe to ignore output audio stream?
video_st = icv_add_video_stream_FFMPEG(oc, codec_id,
width, height, width*height*bitrate_scale,
fps, codec_pix_fmt);
// TODO -- safe to ignore output audio stream?
video_st = icv_add_video_stream_FFMPEG(oc, codec_id,
width, height, width*height*bitrate_scale,
fps, codec_pix_fmt);
/* set the output parameters (must be done even if no
/* set the output parameters (must be done even if no
parameters). */
if (av_set_parameters(oc, NULL) < 0) {
return false;
}
if (av_set_parameters(oc, NULL) < 0) {
return false;
}
dump_format(oc, 0, filename, 1);
dump_format(oc, 0, filename, 1);
/* now that all the parameters are set, we can open the audio and
/* now that all the parameters are set, we can open the audio and
video codecs and allocate the necessary encode buffers */
if (!video_st){
return false;
}
if (!video_st){
return false;
}
AVCodec *codec;
AVCodecContext *c;
AVCodec *codec;
AVCodecContext *c;
#if LIBAVFORMAT_BUILD > 4628
c = (video_st->codec);
c = (video_st->codec);
#else
c = &(video_st->codec);
c = &(video_st->codec);
#endif
c->codec_tag = fourcc;
/* find the video encoder */
codec = avcodec_find_encoder(c->codec_id);
if (!codec) {
return false;
}
c->codec_tag = fourcc;
/* find the video encoder */
codec = avcodec_find_encoder(c->codec_id);
if (!codec) {
fprintf(stderr, "Could not find encoder for codec id %d: %s", c->codec_id, icvFFMPEGErrStr(
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
AVERROR_ENCODER_NOT_FOUND
#else
-1
#endif
));
return false;
}
c->bit_rate_tolerance = c->bit_rate;
c->bit_rate_tolerance = c->bit_rate;
/* open the codec */
if ( (err=avcodec_open(c, codec)) < 0) {
char errtext[256];
sprintf(errtext, "Could not open codec '%s': %s", codec->name, icvFFMPEGErrStr(err));
return false;
}
/* open the codec */
if ( (err=avcodec_open(c, codec)) < 0 ) {
fprintf(stderr, "Could not open codec '%s': %s", codec->name, icvFFMPEGErrStr(err));
return false;
}
outbuf = NULL;
outbuf = NULL;
if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
/* allocate output buffer */
/* assume we will never get codec output with more than 4 bytes per pixel... */
outbuf_size = width*height*4;
outbuf = (uint8_t *) av_malloc(outbuf_size);
}
if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
/* allocate output buffer */
/* assume we will never get codec output with more than 4 bytes per pixel... */
outbuf_size = width*height*4;
outbuf = (uint8_t *) av_malloc(outbuf_size);
}
bool need_color_convert;
need_color_convert = (c->pix_fmt != input_pix_fmt);
bool need_color_convert;
need_color_convert = (c->pix_fmt != input_pix_fmt);
/* allocate the encoded raw picture */
picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
if (!picture) {
return false;
}
/* allocate the encoded raw picture */
picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
if (!picture) {
return false;
}
/* if the output format is not our input format, then a temporary
/* if the output format is not our input format, then a temporary
picture of the input format is needed too. It is then converted
to the required output format */
input_picture = NULL;
if ( need_color_convert ) {
input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, c->width, c->height, false);
if (!input_picture) {
return false;
input_picture = NULL;
if ( need_color_convert ) {
input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, c->width, c->height, false);
if (!input_picture) {
return false;
}
}
/* open the output file, if needed */
if (!(fmt->flags & AVFMT_NOFILE)) {
if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
return false;
}
}
/* write the stream header, if any */
av_write_header( oc );
return true;
}
CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
{
CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
capture->init();
if( capture->open( filename ))
return capture;
capture->close();
free(capture);
return 0;
}
void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
{
if( capture && *capture )
{
(*capture)->close();
free(*capture);
*capture = 0;
}
}
/* open the output file, if needed */
if (!(fmt->flags & AVFMT_NOFILE)) {
if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
return false;
int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
{
return capture->setProperty(prop_id, value);
}
double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
{
return capture->getProperty(prop_id);
}
int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
{
return capture->grabFrame();
}
int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
{
return capture->retrieveFrame(0, data, step, width, height, cn);
}
CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
int width, int height, int isColor )
{
CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
writer->init();
if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
return writer;
writer->close();
free(writer);
return 0;
}
void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
{
if( writer && *writer )
{
(*writer)->close();
free(*writer);
*writer = 0;
}
}
/* write the stream header, if any */
av_write_header( oc );
return true;
}
CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename )
{
CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture));
capture->init();
if( capture->open( filename ))
return capture;
capture->close();
free(capture);
return 0;
}
void cvReleaseCapture_FFMPEG(CvCapture_FFMPEG** capture)
{
if( capture && *capture )
int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
const unsigned char* data, int step,
int width, int height, int cn, int origin)
{
(*capture)->close();
free(*capture);
*capture = 0;
return writer->writeFrame(data, step, width, height, cn, origin);
}
}
int cvSetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id, double value)
{
return capture->setProperty(prop_id, value);
}
double cvGetCaptureProperty_FFMPEG(CvCapture_FFMPEG* capture, int prop_id)
{
return capture->getProperty(prop_id);
}
int cvGrabFrame_FFMPEG(CvCapture_FFMPEG* capture)
{
return capture->grabFrame();
}
int cvRetrieveFrame_FFMPEG(CvCapture_FFMPEG* capture, unsigned char** data, int* step, int* width, int* height, int* cn)
{
return capture->retrieveFrame(0, data, step, width, height, cn);
}
CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int fourcc, double fps,
int width, int height, int isColor )
{
CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer));
writer->init();
if( writer->open( filename, fourcc, fps, width, height, isColor != 0 ))
return writer;
writer->close();
free(writer);
return 0;
}
void cvReleaseVideoWriter_FFMPEG( CvVideoWriter_FFMPEG** writer )
{
if( writer && *writer )
{
(*writer)->close();
free(*writer);
*writer = 0;
}
}
int cvWriteFrame_FFMPEG( CvVideoWriter_FFMPEG* writer,
const unsigned char* data, int step,
int width, int height, int cn, int origin)
{
return writer->writeFrame(data, step, width, height, cn, origin);
}
File diff suppressed because it is too large Load Diff
-251
View File
@@ -1,251 +0,0 @@
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#ifdef HAVE_FFMPEG
#include "cap_ffmpeg_impl_v2.hpp"
#else
#include "cap_ffmpeg_api.hpp"
#endif
static CvCreateFileCapture_Plugin icvCreateFileCapture_FFMPEG_p = 0;
static CvReleaseCapture_Plugin icvReleaseCapture_FFMPEG_p = 0;
static CvGrabFrame_Plugin icvGrabFrame_FFMPEG_p = 0;
static CvRetrieveFrame_Plugin icvRetrieveFrame_FFMPEG_p = 0;
static CvSetCaptureProperty_Plugin icvSetCaptureProperty_FFMPEG_p = 0;
static CvGetCaptureProperty_Plugin icvGetCaptureProperty_FFMPEG_p = 0;
static CvCreateVideoWriter_Plugin icvCreateVideoWriter_FFMPEG_p = 0;
static CvReleaseVideoWriter_Plugin icvReleaseVideoWriter_FFMPEG_p = 0;
static CvWriteFrame_Plugin icvWriteFrame_FFMPEG_p = 0;
static void
icvInitFFMPEG(void)
{
static int ffmpegInitialized = 0;
if( !ffmpegInitialized )
{
#if defined WIN32 || defined _WIN32
const char* module_name = "opencv_ffmpeg"
#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__)
"_64"
#endif
".dll";
static HMODULE icvFFOpenCV = LoadLibrary( module_name );
if( icvFFOpenCV )
{
icvCreateFileCapture_FFMPEG_p =
(CvCreateFileCapture_Plugin)GetProcAddress(icvFFOpenCV, "cvCreateFileCapture_FFMPEG");
icvReleaseCapture_FFMPEG_p =
(CvReleaseCapture_Plugin)GetProcAddress(icvFFOpenCV, "cvReleaseCapture_FFMPEG");
icvGrabFrame_FFMPEG_p =
(CvGrabFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvGrabFrame_FFMPEG");
icvRetrieveFrame_FFMPEG_p =
(CvRetrieveFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvRetrieveFrame_FFMPEG");
icvSetCaptureProperty_FFMPEG_p =
(CvSetCaptureProperty_Plugin)GetProcAddress(icvFFOpenCV, "cvSetCaptureProperty_FFMPEG");
icvGetCaptureProperty_FFMPEG_p =
(CvGetCaptureProperty_Plugin)GetProcAddress(icvFFOpenCV, "cvGetCaptureProperty_FFMPEG");
icvCreateVideoWriter_FFMPEG_p =
(CvCreateVideoWriter_Plugin)GetProcAddress(icvFFOpenCV, "cvCreateVideoWriter_FFMPEG");
icvReleaseVideoWriter_FFMPEG_p =
(CvReleaseVideoWriter_Plugin)GetProcAddress(icvFFOpenCV, "cvReleaseVideoWriter_FFMPEG");
icvWriteFrame_FFMPEG_p =
(CvWriteFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvWriteFrame_FFMPEG");
#if 0
if( icvCreateFileCapture_FFMPEG_p != 0 &&
icvReleaseCapture_FFMPEG_p != 0 &&
icvGrabFrame_FFMPEG_p != 0 &&
icvRetrieveFrame_FFMPEG_p != 0 &&
icvSetCaptureProperty_FFMPEG_p != 0 &&
icvGetCaptureProperty_FFMPEG_p != 0 &&
icvCreateVideoWriter_FFMPEG_p != 0 &&
icvReleaseVideoWriter_FFMPEG_p != 0 &&
icvWriteFrame_FFMPEG_p != 0 )
{
printf("Successfully initialized ffmpeg plugin!\n");
}
else
{
printf("Failed to load FFMPEG plugin: module handle=%p\n", icvFFOpenCV);
}
#endif
}
#elif defined HAVE_FFMPEG
icvCreateFileCapture_FFMPEG_p = (CvCreateFileCapture_Plugin)cvCreateFileCapture_FFMPEG;
icvReleaseCapture_FFMPEG_p = (CvReleaseCapture_Plugin)cvReleaseCapture_FFMPEG;
icvGrabFrame_FFMPEG_p = (CvGrabFrame_Plugin)cvGrabFrame_FFMPEG;
icvRetrieveFrame_FFMPEG_p = (CvRetrieveFrame_Plugin)cvRetrieveFrame_FFMPEG;
icvSetCaptureProperty_FFMPEG_p = (CvSetCaptureProperty_Plugin)cvSetCaptureProperty_FFMPEG;
icvGetCaptureProperty_FFMPEG_p = (CvGetCaptureProperty_Plugin)cvGetCaptureProperty_FFMPEG;
icvCreateVideoWriter_FFMPEG_p = (CvCreateVideoWriter_Plugin)cvCreateVideoWriter_FFMPEG;
icvReleaseVideoWriter_FFMPEG_p = (CvReleaseVideoWriter_Plugin)cvReleaseVideoWriter_FFMPEG;
icvWriteFrame_FFMPEG_p = (CvWriteFrame_Plugin)cvWriteFrame_FFMPEG;
#endif
ffmpegInitialized = 1;
}
}
class CvCapture_FFMPEG_proxy : public CvCapture
{
public:
CvCapture_FFMPEG_proxy() { ffmpegCapture = 0; }
virtual ~CvCapture_FFMPEG_proxy() { close(); }
virtual double getProperty(int propId)
{
return ffmpegCapture ? icvGetCaptureProperty_FFMPEG_p(ffmpegCapture, propId) : 0;
}
virtual bool setProperty(int propId, double value)
{
return ffmpegCapture ? icvSetCaptureProperty_FFMPEG_p(ffmpegCapture, propId, value)!=0 : false;
}
virtual bool grabFrame()
{
return ffmpegCapture ? icvGrabFrame_FFMPEG_p(ffmpegCapture)!=0 : false;
}
virtual IplImage* retrieveFrame(int)
{
unsigned char* data = 0;
int step=0, width=0, height=0, cn=0;
if(!ffmpegCapture ||
!icvRetrieveFrame_FFMPEG_p(ffmpegCapture,&data,&step,&width,&height,&cn))
return 0;
cvInitImageHeader(&frame, cvSize(width, height), 8, cn);
cvSetData(&frame, data, step);
return &frame;
}
virtual bool open( const char* filename )
{
close();
icvInitFFMPEG();
if( !icvCreateFileCapture_FFMPEG_p )
return false;
ffmpegCapture = icvCreateFileCapture_FFMPEG_p( filename );
return ffmpegCapture != 0;
}
virtual void close()
{
if( ffmpegCapture && icvReleaseCapture_FFMPEG_p )
icvReleaseCapture_FFMPEG_p( &ffmpegCapture );
assert( ffmpegCapture == 0 );
ffmpegCapture = 0;
}
protected:
void* ffmpegCapture;
IplImage frame;
};
CvCapture* cvCreateFileCapture_FFMPEG_proxy(const char * filename)
{
CvCapture_FFMPEG_proxy* result = new CvCapture_FFMPEG_proxy;
if( result->open( filename ))
return result;
delete result;
#if defined WIN32 || defined _WIN32
return cvCreateFileCapture_VFW(filename);
#else
return 0;
#endif
}
class CvVideoWriter_FFMPEG_proxy : public CvVideoWriter
{
public:
CvVideoWriter_FFMPEG_proxy() { ffmpegWriter = 0; }
virtual ~CvVideoWriter_FFMPEG_proxy() { close(); }
virtual bool writeFrame( const IplImage* image )
{
if(!ffmpegWriter)
return false;
CV_Assert(image->depth == 8);
return icvWriteFrame_FFMPEG_p(ffmpegWriter, (const uchar*)image->imageData,
image->widthStep, image->width, image->height, image->nChannels, image->origin) !=0;
}
virtual bool open( const char* filename, int fourcc, double fps, CvSize frameSize, bool isColor )
{
close();
icvInitFFMPEG();
if( !icvCreateVideoWriter_FFMPEG_p )
return false;
ffmpegWriter = icvCreateVideoWriter_FFMPEG_p( filename, fourcc, fps, frameSize.width, frameSize.height, isColor );
return ffmpegWriter != 0;
}
virtual void close()
{
if( ffmpegWriter && icvReleaseVideoWriter_FFMPEG_p )
icvReleaseVideoWriter_FFMPEG_p( &ffmpegWriter );
assert( ffmpegWriter == 0 );
ffmpegWriter = 0;
}
protected:
void* ffmpegWriter;
};
CvVideoWriter* cvCreateVideoWriter_FFMPEG_proxy( const char* filename, int fourcc,
double fps, CvSize frameSize, int isColor )
{
CvVideoWriter_FFMPEG_proxy* result = new CvVideoWriter_FFMPEG_proxy;
if( result->open( filename, fourcc, fps, frameSize, isColor != 0 ))
return result;
delete result;
#if defined WIN32 || defined _WIN32
return cvCreateVideoWriter_VFW(filename, fourcc, fps, frameSize, isColor);
#else
return 0;
#endif
}
+4
View File
@@ -44,6 +44,10 @@
#ifdef HAVE_OPENNI
#if TBB_INTERFACE_VERSION < 5000
# undef HAVE_TBB
#endif
#include <iostream>
#include <queue>
#include "XnCppWrapper.h"
+1
View File
@@ -109,6 +109,7 @@ protected:
CvCaptureCAM_PvAPI::CvCaptureCAM_PvAPI()
{
monocrome=false;
memset(&this->Camera, 0, sizeof(this->Camera));
}
void CvCaptureCAM_PvAPI::Sleep(unsigned int time)
{
+5
View File
@@ -59,6 +59,11 @@
#include <zlib.h>
#include "grfmt_png.hpp"
#if defined _MSC_VER && _MSC_VER >= 1200
// disable warnings related to _setjmp
#pragma warning( disable: 4611 )
#endif
namespace cv
{

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