resolved conflicts, updated retina class interface and optimized a heavy retinacolor process

This commit is contained in:
alexandre benoit
2013-04-29 19:06:35 +02:00
2166 changed files with 342437 additions and 211189 deletions

View File

@@ -81,14 +81,14 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
objpt.resize(imgpt.size(),objpt[0]);
Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
if( flags & CV_CALIB_FIX_ASPECT_RATIO )
if( flags & CALIB_FIX_ASPECT_RATIO )
cameraMatrix.at<double>(0,0) = aspectRatio;
Mat distCoeffs = Mat::zeros(5, 1, CV_64F);
double err = calibrateCamera(objpt, imgpt, imageSize, cameraMatrix,
distCoeffs, rvecs, tvecs,
flags|CV_CALIB_FIX_K3/*|CV_CALIB_FIX_K4|CV_CALIB_FIX_K5|CV_CALIB_FIX_K6*/);
flags|CALIB_FIX_K3/*|CALIB_FIX_K4|CALIB_FIX_K5|CALIB_FIX_K6*/);
bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
if(!ok)
{
@@ -138,7 +138,7 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
cameraMatrix, distCoeffs,
imageSize, R, T, E, F,
TermCriteria(TermCriteria::COUNT, 30, 0),
CV_CALIB_FIX_INTRINSIC);
CALIB_FIX_INTRINSIC);
printf("Pair (1,%d) calibration reprojection error = %g\n", c, sqrt(err/(N*2)));
if( c == 2 )
{
@@ -212,15 +212,15 @@ int main( int argc, char** argv )
{
if( sscanf( argv[++i], "%f", &aspectRatio ) != 1 || aspectRatio <= 0 )
return printf("Invalid aspect ratio\n" ), -1;
flags |= CV_CALIB_FIX_ASPECT_RATIO;
flags |= CALIB_FIX_ASPECT_RATIO;
}
else if( strcmp( s, "-zt" ) == 0 )
{
flags |= CV_CALIB_ZERO_TANGENT_DIST;
flags |= CALIB_ZERO_TANGENT_DIST;
}
else if( strcmp( s, "-p" ) == 0 )
{
flags |= CV_CALIB_FIX_PRINCIPAL_POINT;
flags |= CALIB_FIX_PRINCIPAL_POINT;
}
else if( strcmp( s, "-o" ) == 0 )
{
@@ -271,8 +271,8 @@ int main( int argc, char** argv )
{
vector<Point2f> ptvec;
imageSize = view.size();
cvtColor(view, viewGray, CV_BGR2GRAY);
bool found = findChessboardCorners( view, boardSize, ptvec, CV_CALIB_CB_ADAPTIVE_THRESH );
cvtColor(view, viewGray, COLOR_BGR2GRAY);
bool found = findChessboardCorners( view, boardSize, ptvec, CALIB_CB_ADAPTIVE_THRESH );
drawChessboardCorners( view, boardSize, Mat(ptvec), found );
if( found )
@@ -291,13 +291,13 @@ int main( int argc, char** argv )
printf("Running calibration ...\n");
run3Calibration(imgpt[0], imgpt[1], imgpt[2], imageSize,
boardSize, squareSize, aspectRatio, flags|CV_CALIB_FIX_K4|CV_CALIB_FIX_K5,
boardSize, squareSize, aspectRatio, flags|CALIB_FIX_K4|CALIB_FIX_K5,
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
cameraMatrix[2], distCoeffs[2],
R12, T12, R13, T13);
fs.open(outputFilename, CV_STORAGE_WRITE);
fs.open(outputFilename, FileStorage::WRITE);
fs << "cameraMatrix1" << cameraMatrix[0];
fs << "cameraMatrix2" << cameraMatrix[1];
@@ -323,7 +323,7 @@ int main( int argc, char** argv )
imgpt[0], imgpt[2],
imageSize, R12, T12, R13, T13,
R[0], R[1], R[2], P[0], P[1], P[2], Q, -1.,
imageSize, 0, 0, CV_CALIB_ZERO_DISPARITY);
imageSize, 0, 0, CALIB_ZERO_DISPARITY);
Mat map1[3], map2[3];
fs << "R1" << R[0];
@@ -359,7 +359,7 @@ int main( int argc, char** argv )
continue;
Mat rview = canvas.colRange(k2*imageSize.width, (k2+1)*imageSize.width);
remap(view, rview, map1[k1], map2[k1], CV_INTER_LINEAR);
remap(view, rview, map1[k1], map2[k1], INTER_LINEAR);
}
printf("%s %s %s\n", imageList[i*3].c_str(), imageList[i*3+1].c_str(), imageList[i*3+2].c_str());
resize( canvas, small_canvas, Size(1500, 1500/3) );

View File

@@ -4,7 +4,7 @@
# ----------------------------------------------------------------------------
SET(OPENCV_CPP_SAMPLES_REQUIRED_DEPS opencv_core opencv_flann opencv_imgproc
opencv_highgui opencv_ml opencv_video opencv_objdetect opencv_photo opencv_nonfree
opencv_highgui opencv_ml opencv_video opencv_objdetect opencv_photo opencv_nonfree opencv_softcascade
opencv_features2d opencv_calib3d opencv_legacy opencv_contrib opencv_stitching opencv_videostab)
ocv_check_dependencies(${OPENCV_CPP_SAMPLES_REQUIRED_DEPS})
@@ -16,7 +16,7 @@ if(BUILD_EXAMPLES AND OCV_DEPENDENCIES_FOUND)
ocv_include_directories("${OpenCV_SOURCE_DIR}/include")#for opencv.hpp
ocv_include_modules(${OPENCV_CPP_SAMPLES_REQUIRED_DEPS})
if (HAVE_opencv_gpu)
if(HAVE_opencv_gpu)
ocv_include_directories("${OpenCV_SOURCE_DIR}/modules/gpu/include")
endif()
@@ -28,20 +28,31 @@ if(BUILD_EXAMPLES AND OCV_DEPENDENCIES_FOUND)
# Define executable targets
# ---------------------------------------------
MACRO(OPENCV_DEFINE_CPP_EXAMPLE name srcs)
set(the_target "example_${name}")
if("${srcs}" MATCHES "tutorial_code")
set(sample_kind tutorial)
set(sample_KIND TUTORIAL)
set(sample_folder "samples//tutorials")
else()
set(sample_kind example)
set(sample_KIND EXAMPLE)
set(sample_folder "samples//cpp")
endif()
set(the_target "${sample_kind}_${name}")
add_executable(${the_target} ${srcs})
target_link_libraries(${the_target} ${OPENCV_LINKER_LIBS} ${OPENCV_CPP_SAMPLES_REQUIRED_DEPS})
if (HAVE_opencv_gpu)
if(HAVE_opencv_gpu)
target_link_libraries(${the_target} opencv_gpu)
endif()
set_target_properties(${the_target} PROPERTIES
OUTPUT_NAME "${name}"
PROJECT_LABEL "(EXAMPLE) ${name}")
OUTPUT_NAME "cpp-${sample_kind}-${name}"
PROJECT_LABEL "(${sample_KIND}) ${name}")
if(ENABLE_SOLUTION_FOLDERS)
set_target_properties(${the_target} PROPERTIES FOLDER "samples//cpp")
set_target_properties(${the_target} PROPERTIES FOLDER "${sample_folder}")
endif()
if(WIN32)
@@ -49,11 +60,19 @@ if(BUILD_EXAMPLES AND OCV_DEPENDENCIES_FOUND)
set_target_properties(${the_target} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:atlthunk.lib /NODEFAULTLIB:atlsd.lib /DEBUG")
endif()
install(TARGETS ${the_target}
RUNTIME DESTINATION "samples/cpp" COMPONENT main)
RUNTIME DESTINATION "${sample_folder}" COMPONENT main)
endif()
ENDMACRO()
file(GLOB cpp_samples RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp)
file(GLOB_RECURSE cpp_samples RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp)
if(NOT HAVE_OPENGL)
ocv_list_filterout(cpp_samples Qt_sample)
endif()
if(NOT HAVE_opencv_gpu)
ocv_list_filterout(cpp_samples "/gpu/")
endif()
foreach(sample_filename ${cpp_samples})
get_filename_component(sample ${sample_filename} NAME_WE)

View File

@@ -10,7 +10,8 @@
#include <iostream>
#include <cstring>
#include "opencv2/opencv.hpp"
#include "opencv2/contrib.hpp"
#include "opencv2/highgui.hpp"
static void help(std::string errorMessage)
{
@@ -28,7 +29,7 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i
cv::Mat displayedCurveImage = cv::Mat::ones(200, curve.size().height, CV_8U);
cv::Mat windowNormalizedCurve;
normalize(curve, windowNormalizedCurve, 0, 200, CV_MINMAX, CV_32F);
normalize(curve, windowNormalizedCurve, 0, 200, cv::NORM_MINMAX, CV_32F);
displayedCurveImage = cv::Scalar::all(255); // set a white background
int binW = cvRound((double)displayedCurveImage.cols/curve.size().height);
@@ -69,7 +70,7 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i
{
cv::Mat rgbIntImg;
outputMat.convertTo(rgbIntImg, CV_8UC3);
cvtColor(rgbIntImg, intGrayImage, CV_BGR2GRAY);
cv::cvtColor(rgbIntImg, intGrayImage, cv::COLOR_BGR2GRAY);
}
// get histogram density probability in order to cut values under above edges limits (here 5-95%)... usefull for HDR pixel errors cancellation
@@ -80,8 +81,7 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i
normalize(hist, normalizedHist, 1, 0, cv::NORM_L1, CV_32F); // normalize histogram so that its sum equals 1
double min_val, max_val;
CvMat histArr(normalizedHist);
cvMinMaxLoc(&histArr, &min_val, &max_val);
minMaxLoc(normalizedHist, &min_val, &max_val);
//std::cout<<"Hist max,min = "<<max_val<<", "<<min_val<<std::endl;
// compute density probability

View File

@@ -14,7 +14,8 @@
#include <stdio.h>
#include <cstring>
#include "opencv2/opencv.hpp"
#include "opencv2/contrib.hpp"
#include "opencv2/highgui.hpp"
static void help(std::string errorMessage)
{
@@ -38,7 +39,7 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i
cv::Mat displayedCurveImage = cv::Mat::ones(200, curve.size().height, CV_8U);
cv::Mat windowNormalizedCurve;
normalize(curve, windowNormalizedCurve, 0, 200, CV_MINMAX, CV_32F);
normalize(curve, windowNormalizedCurve, 0, 200, cv::NORM_MINMAX, CV_32F);
displayedCurveImage = cv::Scalar::all(255); // set a white background
int binW = cvRound((double)displayedCurveImage.cols/curve.size().height);
@@ -88,7 +89,7 @@ static void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, con
{
cv::Mat rgbIntImg;
normalisedImage.convertTo(rgbIntImg, CV_8UC3);
cvtColor(rgbIntImg, intGrayImage, CV_BGR2GRAY);
cv::cvtColor(rgbIntImg, intGrayImage, cv::COLOR_BGR2GRAY);
}
// get histogram density probability in order to cut values under above edges limits (here 5-95%)... usefull for HDR pixel errors cancellation

View File

@@ -5,20 +5,40 @@
#include <iostream>
#include <vector>
#include <opencv/highgui.h>
#include <GL/gl.h>
#include <opencv/cxcore.h>
#include <opencv/cv.h>
#include <opencv2/core/core_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/legacy/compat.hpp>
#include <opencv2/calib3d/calib3d_c.h>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#if defined WIN32 || defined _WIN32 || defined WINCE
#include <windows.h>
#undef small
#undef min
#undef max
#undef abs
#endif
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
using namespace std;
using namespace cv;
void help()
static void help()
{
cout << "\nThis demo demonstrates the use of the Qt enhanced version of the highgui GUI interface\n"
" and dang if it doesn't throw in the use of of the POSIT 3D tracking algorithm too\n"
"It works off of the video: cube4.avi\n"
"Using OpenCV version %s\n" << CV_VERSION << "\n\n"
" 1). This demo is mainly based on work from Javier Barandiaran Martirena\n"
" See this page http://opencv.willowgarage.com/wiki/Posit.\n"
" See this page http://code.opencv.org/projects/opencv/wiki/Posit.\n"
" 2). This is a demo to illustrate how to use **OpenGL Callback**.\n"
" 3). You need Qt binding to compile this sample with OpenGL support enabled.\n"
" 4). The features' detection is very basic and could highly be improved \n"
@@ -29,7 +49,7 @@ void help()
#define FOCAL_LENGTH 600
#define CUBE_SIZE 10
void renderCube(float size)
static void renderCube(float size)
{
glBegin(GL_QUADS);
// Front Face
@@ -72,7 +92,7 @@ void renderCube(float size)
}
void on_opengl(void* param)
static void on_opengl(void* param)
{
//Draw the object with the estimated pose
glLoadIdentity();
@@ -87,7 +107,7 @@ void on_opengl(void* param)
glDisable( GL_LIGHTING );
}
void initPOSIT(std::vector<CvPoint3D32f> *modelPoints)
static void initPOSIT(std::vector<CvPoint3D32f> *modelPoints)
{
//Create the model pointss
modelPoints->push_back(cvPoint3D32f(0.0f, 0.0f, 0.0f)); //The first must be (0,0,0)
@@ -96,19 +116,19 @@ void initPOSIT(std::vector<CvPoint3D32f> *modelPoints)
modelPoints->push_back(cvPoint3D32f(0.0f, CUBE_SIZE, 0.0f));
}
void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImage* grayImage)
static void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImage* grayImage)
{
cvCvtColor(source,grayImage,CV_RGB2GRAY);
cvSmooth( grayImage, grayImage,CV_GAUSSIAN,11);
cvNormalize(grayImage, grayImage, 0, 255, CV_MINMAX);
cvThreshold( grayImage, grayImage, 26, 255, CV_THRESH_BINARY_INV);//25
Mat MgrayImage = grayImage;
Mat MgrayImage = cv::cvarrToMat(grayImage);
//For debug
//MgrayImage = MgrayImage.clone();//deep copy
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(MgrayImage, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
findContours(MgrayImage, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE);
Point p;
vector<CvPoint2D32f> srcImagePoints_temp(4,cvPoint2D32f(0,0));
@@ -116,12 +136,12 @@ void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImag
if (contours.size() == srcImagePoints_temp.size())
{
for(int i = 0 ; i<contours.size(); i++ )
for(size_t i = 0 ; i<contours.size(); i++ )
{
p.x = p.y = 0;
for(int j = 0 ; j<contours[i].size(); j++ )
for(size_t j = 0 ; j<contours[i].size(); j++ )
p+=contours[i][j];
srcImagePoints_temp.at(i)=cvPoint2D32f(float(p.x)/contours[i].size(),float(p.y)/contours[i].size());
@@ -134,8 +154,8 @@ void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImag
//< y = 3
//get point 0;
int index = 0;
for(int i = 1 ; i<srcImagePoints_temp.size(); i++ )
size_t index = 0;
for(size_t i = 1 ; i<srcImagePoints_temp.size(); i++ )
{
if (srcImagePoints_temp.at(i).y > srcImagePoints_temp.at(index).y)
index = i;
@@ -144,7 +164,7 @@ void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImag
//get point 1;
index = 0;
for(int i = 1 ; i<srcImagePoints_temp.size(); i++ )
for(size_t i = 1 ; i<srcImagePoints_temp.size(); i++ )
{
if (srcImagePoints_temp.at(i).x > srcImagePoints_temp.at(index).x)
index = i;
@@ -153,7 +173,7 @@ void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImag
//get point 2;
index = 0;
for(int i = 1 ; i<srcImagePoints_temp.size(); i++ )
for(size_t i = 1 ; i<srcImagePoints_temp.size(); i++ )
{
if (srcImagePoints_temp.at(i).x < srcImagePoints_temp.at(index).x)
index = i;
@@ -162,16 +182,16 @@ void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImag
//get point 3;
index = 0;
for(int i = 1 ; i<srcImagePoints_temp.size(); i++ )
for(size_t i = 1 ; i<srcImagePoints_temp.size(); i++ )
{
if (srcImagePoints_temp.at(i).y < srcImagePoints_temp.at(index).y)
index = i;
}
srcImagePoints->at(3) = srcImagePoints_temp.at(index);
Mat Msource = source;
Mat Msource = cv::cvarrToMat(source);
stringstream ss;
for(int i = 0 ; i<srcImagePoints_temp.size(); i++ )
for(size_t i = 0 ; i<srcImagePoints_temp.size(); i++ )
{
ss<<i;
circle(Msource,srcImagePoints->at(i),5,CV_RGB(255,0,0));
@@ -185,7 +205,7 @@ void foundCorners(vector<CvPoint2D32f> *srcImagePoints,IplImage* source, IplImag
}
void createOpenGLMatrixFrom(float *posePOSIT,const CvMatr32f &rotationMatrix, const CvVect32f &translationVector)
static void createOpenGLMatrixFrom(float *posePOSIT,const CvMatr32f &rotationMatrix, const CvVect32f &translationVector)
{
@@ -206,21 +226,23 @@ void createOpenGLMatrixFrom(float *posePOSIT,const CvMatr32f &rotationMatrix, co
posePOSIT[15] = 1.0;
}
int main(int argc, char *argv[])
int main(void)
{
CvCapture* video = cvCaptureFromFile("cube4.avi");
CV_Assert(video);
help();
VideoCapture video("cube4.avi");
CV_Assert(video.isOpened());
IplImage* source = cvCreateImage(cvGetSize(cvQueryFrame(video)),8,3);
IplImage* grayImage = cvCreateImage(cvGetSize(cvQueryFrame(video)),8,1);
Mat frame; video >> frame;
cvNamedWindow("original",CV_WINDOW_AUTOSIZE | CV_WINDOW_FREERATIO);
cvNamedWindow("POSIT",CV_WINDOW_AUTOSIZE | CV_WINDOW_FREERATIO);
IplImage* grayImage = cvCreateImage(frame.size(),8,1);
namedWindow("original", WINDOW_AUTOSIZE | WINDOW_FREERATIO);
namedWindow("POSIT", WINDOW_AUTOSIZE | WINDOW_FREERATIO);
displayOverlay("POSIT", "We lost the 4 corners' detection quite often (the red circles disappear). This demo is only to illustrate how to use OpenGL callback.\n -- Press ESC to exit.", 10000);
//For debug
//cvNamedWindow("tempGray",CV_WINDOW_AUTOSIZE);
float OpenGLMatrix[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
cvCreateOpenGLCallback("POSIT",on_opengl,OpenGLMatrix);
setOpenGlDrawCallback("POSIT",on_opengl,OpenGLMatrix);
vector<CvPoint3D32f> modelPoints;
initPOSIT(&modelPoints);
@@ -235,26 +257,27 @@ int main(int argc, char *argv[])
vector<CvPoint2D32f> srcImagePoints(4,cvPoint2D32f(0,0));
while(cvWaitKey(33) != 27)
while(waitKey(33) != 27)
{
source=cvQueryFrame(video);
cvShowImage("original",source);
video >> frame;
imshow("original", frame);
foundCorners(&srcImagePoints,source,grayImage);
IplImage source = frame;
foundCorners(&srcImagePoints, &source, grayImage);
cvPOSIT( positObject, &srcImagePoints[0], FOCAL_LENGTH, criteria, rotation_matrix, translation_vector );
createOpenGLMatrixFrom(OpenGLMatrix,rotation_matrix,translation_vector);
cvShowImage("POSIT",source);
imshow("POSIT", frame);
//For debug
//cvShowImage("tempGray",grayImage);
if (cvGetCaptureProperty(video,CV_CAP_PROP_POS_AVI_RATIO)>0.99)
cvSetCaptureProperty(video,CV_CAP_PROP_POS_AVI_RATIO,0);
if (video.get(CAP_PROP_POS_AVI_RATIO) > 0.99)
video.set(CAP_PROP_POS_AVI_RATIO, 0);
}
cvDestroyAllWindows();
destroyAllWindows();
cvReleaseImage(&grayImage);
cvReleaseCapture(&video);
video.release();
cvReleasePOSITObject(&positObject);
return 0;

View File

@@ -1453,7 +1453,7 @@ void VocData::readClassifierGroundTruth(const string& filename, vector<string>&
string line;
string image;
int obj_present;
int obj_present = 0;
while (!gtfile.eof())
{
std::getline(gtfile,line);
@@ -1826,7 +1826,7 @@ void VocData::readFileToString(const string filename, string& file_contents)
int VocData::stringToInteger(const string input_str)
{
int result;
int result = 0;
stringstream ss(input_str);
if ((ss >> result).fail())

View File

@@ -5,7 +5,9 @@
* Author: Andrew B. Godbehere
*/
#include <opencv2/opencv.hpp>
#include "opencv2/video.hpp"
#include "opencv2/highgui.hpp"
#include <opencv2/core/utility.hpp>
#include <iostream>
using namespace cv;
@@ -32,16 +34,13 @@ int main(int argc, char** argv)
setUseOptimized(true);
setNumThreads(8);
Ptr<BackgroundSubtractorGMG> fgbg = Algorithm::create<BackgroundSubtractorGMG>("BackgroundSubtractor.GMG");
Ptr<BackgroundSubtractor> fgbg = createBackgroundSubtractorGMG(20, 0.7);
if (fgbg.empty())
{
std::cerr << "Failed to create BackgroundSubtractor.GMG Algorithm." << std::endl;
return -1;
}
fgbg->set("initializationFrames", 20);
fgbg->set("decisionThreshold", 0.7);
VideoCapture cap;
if (argc > 1)
cap.open(argv[1]);
@@ -65,9 +64,9 @@ int main(int argc, char** argv)
if (frame.empty())
break;
(*fgbg)(frame, fgmask);
fgbg->apply(frame, fgmask);
frame.copyTo(segm);
frame.convertTo(segm, CV_8U, 0.5);
add(frame, Scalar(100, 100, 0), segm, fgmask);
imshow("FG Segmentation", segm);

View File

@@ -1,7 +1,8 @@
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
using namespace std;
@@ -46,12 +47,12 @@ int main(int argc, const char** argv)
return -1;
}
namedWindow("image", CV_WINDOW_NORMAL);
namedWindow("foreground mask", CV_WINDOW_NORMAL);
namedWindow("foreground image", CV_WINDOW_NORMAL);
namedWindow("mean background image", CV_WINDOW_NORMAL);
namedWindow("image", WINDOW_NORMAL);
namedWindow("foreground mask", WINDOW_NORMAL);
namedWindow("foreground image", WINDOW_NORMAL);
namedWindow("mean background image", WINDOW_NORMAL);
BackgroundSubtractorMOG2 bg_model;//(100, 3, 0.3, 5);
Ptr<BackgroundSubtractor> bg_model = createBackgroundSubtractorMOG2();
Mat img, fgmask, fgimg;
@@ -68,13 +69,13 @@ int main(int argc, const char** argv)
fgimg.create(img.size(), img.type());
//update the model
bg_model(img, fgmask, update_bg_model ? -1 : 0);
bg_model->apply(img, fgmask, update_bg_model ? -1 : 0);
fgimg = Scalar::all(0);
img.copyTo(fgimg, fgmask);
Mat bgimg;
bg_model.getBackgroundImage(bgimg);
bg_model->getBackgroundImage(bgimg);
imshow("image", img);
imshow("foreground mask", fgmask);

View File

@@ -4,11 +4,12 @@
* Created on: Oct 17, 2010
* Author: ethan
*/
#include "opencv2/core/core.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/calib3d.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <vector>
#include <iostream>
@@ -62,11 +63,11 @@ int main(int argc, const char ** argv)
help();
CommandLineParser parser(argc, argv, keys);
string im1_name = parser.get<string>(1);
string im2_name = parser.get<string>(2);
string im1_name = parser.get<string>(0);
string im2_name = parser.get<string>(1);
Mat im1 = imread(im1_name, CV_LOAD_IMAGE_GRAYSCALE);
Mat im2 = imread(im2_name, CV_LOAD_IMAGE_GRAYSCALE);
Mat im1 = imread(im1_name, IMREAD_GRAYSCALE);
Mat im2 = imread(im2_name, IMREAD_GRAYSCALE);
if (im1.empty() || im2.empty())
{

View File

@@ -1,8 +1,9 @@
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/highgui.hpp"
#include <map>
@@ -359,7 +360,7 @@ static void triangulatePoint_test(void)
pts[0] = imgpt1[i]; pts[1] = imgpt2[i];
objptt[i] = triangulatePoint(pts, Rv, tv, cameraMatrix);
}
double err = norm(Mat(objpt), Mat(objptt), CV_C);
double err = norm(Mat(objpt), Mat(objptt), NORM_INF);
CV_Assert(err < 1e-1);
}
@@ -381,6 +382,96 @@ struct EqKeypoints
const Set2i* pairs;
};
template<typename _Tp, class _EqPredicate> static
int partition( const std::vector<_Tp>& _vec, std::vector<int>& labels,
_EqPredicate predicate=_EqPredicate())
{
int i, j, N = (int)_vec.size();
const _Tp* vec = &_vec[0];
const int PARENT=0;
const int RANK=1;
std::vector<int> _nodes(N*2);
int (*nodes)[2] = (int(*)[2])&_nodes[0];
// The first O(N) pass: create N single-vertex trees
for(i = 0; i < N; i++)
{
nodes[i][PARENT]=-1;
nodes[i][RANK] = 0;
}
// The main O(N^2) pass: merge connected components
for( i = 0; i < N; i++ )
{
int root = i;
// find root
while( nodes[root][PARENT] >= 0 )
root = nodes[root][PARENT];
for( j = 0; j < N; j++ )
{
if( i == j || !predicate(vec[i], vec[j]))
continue;
int root2 = j;
while( nodes[root2][PARENT] >= 0 )
root2 = nodes[root2][PARENT];
if( root2 != root )
{
// unite both trees
int rank = nodes[root][RANK], rank2 = nodes[root2][RANK];
if( rank > rank2 )
nodes[root2][PARENT] = root;
else
{
nodes[root][PARENT] = root2;
nodes[root2][RANK] += rank == rank2;
root = root2;
}
CV_Assert( nodes[root][PARENT] < 0 );
int k = j, parent;
// compress the path from node2 to root
while( (parent = nodes[k][PARENT]) >= 0 )
{
nodes[k][PARENT] = root;
k = parent;
}
// compress the path from node to root
k = i;
while( (parent = nodes[k][PARENT]) >= 0 )
{
nodes[k][PARENT] = root;
k = parent;
}
}
}
}
// Final O(N) pass: enumerate classes
labels.resize(N);
int nclasses = 0;
for( i = 0; i < N; i++ )
{
int root = i;
while( nodes[root][PARENT] >= 0 )
root = nodes[root][PARENT];
// re-use the rank as the class label
if( nodes[root][RANK] >= 0 )
nodes[root][RANK] = ~nclasses++;
labels[i] = ~nodes[root][RANK];
}
return nclasses;
}
static void build3dmodel( const Ptr<FeatureDetector>& detector,
const Ptr<DescriptorExtractor>& descriptorExtractor,
const vector<Point3f>& /*modelBox*/,
@@ -418,7 +509,7 @@ static void build3dmodel( const Ptr<FeatureDetector>& detector,
for( size_t i = 0; i < nimages; i++ )
{
Mat img = imread(imageList[i], 1), gray;
cvtColor(img, gray, CV_BGR2GRAY);
cvtColor(img, gray, COLOR_BGR2GRAY);
vector<KeyPoint> keypoints;
detector->detect(gray, keypoints);
@@ -603,7 +694,7 @@ static void build3dmodel( const Ptr<FeatureDetector>& detector,
projectPoints(Mat(model.points), Rs[i], ts[i], cameraMatrix, Mat(), imagePoints);
for( int k = 0; k < (int)imagePoints.size(); k++ )
circle(img, imagePoints[k], 2, Scalar(0,255,0), -1, CV_AA, 0);
circle(img, imagePoints[k], 2, Scalar(0,255,0), -1, LINE_AA, 0);
imshow("Test", img);
int c = waitKey();

View File

@@ -1,7 +1,10 @@
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/highgui.hpp"
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <time.h>
@@ -93,7 +96,7 @@ static double computeReprojectionErrors(
{
projectPoints(Mat(objectPoints[i]), rvecs[i], tvecs[i],
cameraMatrix, distCoeffs, imagePoints2);
err = norm(Mat(imagePoints[i]), Mat(imagePoints2), CV_L2);
err = norm(Mat(imagePoints[i]), Mat(imagePoints2), NORM_L2);
int n = (int)objectPoints[i].size();
perViewErrors[i] = (float)std::sqrt(err*err/n);
totalErr += err*err;
@@ -125,7 +128,7 @@ static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point
break;
default:
CV_Error(CV_StsBadArg, "Unknown pattern type\n");
CV_Error(Error::StsBadArg, "Unknown pattern type\n");
}
}
@@ -138,7 +141,7 @@ static bool runCalibration( vector<vector<Point2f> > imagePoints,
double& totalAvgErr)
{
cameraMatrix = Mat::eye(3, 3, CV_64F);
if( flags & CV_CALIB_FIX_ASPECT_RATIO )
if( flags & CALIB_FIX_ASPECT_RATIO )
cameraMatrix.at<double>(0,0) = aspectRatio;
distCoeffs = Mat::zeros(8, 1, CV_64F);
@@ -149,8 +152,8 @@ static bool runCalibration( vector<vector<Point2f> > imagePoints,
objectPoints.resize(imagePoints.size(),objectPoints[0]);
double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
distCoeffs, rvecs, tvecs, flags|CV_CALIB_FIX_K4|CV_CALIB_FIX_K5);
///*|CV_CALIB_FIX_K3*/|CV_CALIB_FIX_K4|CV_CALIB_FIX_K5);
distCoeffs, rvecs, tvecs, flags|CALIB_FIX_K4|CALIB_FIX_K5);
///*|CALIB_FIX_K3*/|CALIB_FIX_K4|CALIB_FIX_K5);
printf("RMS error reported by calibrateCamera: %g\n", rms);
bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
@@ -189,17 +192,17 @@ static void saveCameraParams( const string& filename,
fs << "board_height" << boardSize.height;
fs << "square_size" << squareSize;
if( flags & CV_CALIB_FIX_ASPECT_RATIO )
if( flags & CALIB_FIX_ASPECT_RATIO )
fs << "aspectRatio" << aspectRatio;
if( flags != 0 )
{
sprintf( buf, "flags: %s%s%s%s",
flags & CV_CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
flags & CV_CALIB_FIX_ASPECT_RATIO ? "+fix_aspectRatio" : "",
flags & CV_CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
flags & CV_CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
cvWriteComment( *fs, buf, 0 );
flags & CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
flags & CALIB_FIX_ASPECT_RATIO ? "+fix_aspectRatio" : "",
flags & CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
flags & CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
//cvWriteComment( *fs, buf, 0 );
}
fs << "flags" << flags;
@@ -226,7 +229,7 @@ static void saveCameraParams( const string& filename,
r = rvecs[i].t();
t = tvecs[i].t();
}
cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
//cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
fs << "extrinsic_parameters" << bigmat;
}
@@ -358,7 +361,7 @@ int main( int argc, char** argv )
{
if( sscanf( argv[++i], "%f", &aspectRatio ) != 1 || aspectRatio <= 0 )
return printf("Invalid aspect ratio\n" ), -1;
flags |= CV_CALIB_FIX_ASPECT_RATIO;
flags |= CALIB_FIX_ASPECT_RATIO;
}
else if( strcmp( s, "-d" ) == 0 )
{
@@ -375,11 +378,11 @@ int main( int argc, char** argv )
}
else if( strcmp( s, "-zt" ) == 0 )
{
flags |= CV_CALIB_ZERO_TANGENT_DIST;
flags |= CALIB_ZERO_TANGENT_DIST;
}
else if( strcmp( s, "-p" ) == 0 )
{
flags |= CV_CALIB_FIX_PRINCIPAL_POINT;
flags |= CALIB_FIX_PRINCIPAL_POINT;
}
else if( strcmp( s, "-v" ) == 0 )
{
@@ -459,14 +462,14 @@ int main( int argc, char** argv )
flip( view, view, 0 );
vector<Point2f> pointbuf;
cvtColor(view, viewGray, CV_BGR2GRAY);
cvtColor(view, viewGray, COLOR_BGR2GRAY);
bool found;
switch( pattern )
{
case CHESSBOARD:
found = findChessboardCorners( view, boardSize, pointbuf,
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);
CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE);
break;
case CIRCLES_GRID:
found = findCirclesGrid( view, boardSize, pointbuf );
@@ -480,7 +483,7 @@ int main( int argc, char** argv )
// improve the found corners' coordinate accuracy
if( pattern == CHESSBOARD && found) cornerSubPix( viewGray, pointbuf, Size(11,11),
Size(-1,-1), TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 30, 0.1 ));
Size(-1,-1), TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 30, 0.1 ));
if( mode == CAPTURING && found &&
(!capture.isOpened() || clock() - prevTimestamp > delay*1e-3*CLOCKS_PER_SEC) )

View File

@@ -120,7 +120,7 @@ int main()
imshow("Current chessboard", boards[i]); waitKey(1000);
}
cout << "Done" << endl;
cvDestroyAllWindows();
destroyAllWindows();
Mat camMat_est;
Mat distCoeffs_est;
@@ -150,7 +150,7 @@ int main()
ChessBoardGenerator::ChessBoardGenerator(const Size& _patternSize) : sensorWidth(32), sensorHeight(24),
squareEdgePointsNum(200), min_cos(sqrt(2.f)*0.5f), cov(0.5),
squareEdgePointsNum(200), min_cos(std::sqrt(2.f)*0.5f), cov(0.5),
patternSize(_patternSize), rendererResolutionMultiplier(4), tvec(Mat::zeros(1, 3, CV_32F))
{
Rodrigues(Mat::eye(3, 3, CV_32F), rvec);
@@ -259,15 +259,15 @@ Mat cv::ChessBoardGenerator::generageChessBoard(const Mat& bg, const Mat& camMat
if (rendererResolutionMultiplier == 1)
{
result = bg.clone();
drawContours(result, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA);
drawContours(result, squares_black, -1, Scalar::all(0), CV_FILLED, CV_AA);
drawContours(result, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA);
drawContours(result, squares_black, -1, Scalar::all(0), FILLED, LINE_AA);
}
else
{
Mat tmp;
resize(bg, tmp, bg.size() * rendererResolutionMultiplier);
drawContours(tmp, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA);
drawContours(tmp, squares_black, -1, Scalar::all(0), CV_FILLED, CV_AA);
drawContours(tmp, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA);
drawContours(tmp, squares_black, -1, Scalar::all(0), FILLED, LINE_AA);
resize(tmp, result, bg.size(), 0, 0, INTER_AREA);
}
return result;
@@ -275,7 +275,7 @@ Mat cv::ChessBoardGenerator::generageChessBoard(const Mat& bg, const Mat& camMat
Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector<Point2f>& corners) const
{
cov = min(cov, 0.8);
cov = std::min(cov, 0.8);
double fovx, fovy, focalLen;
Point2d principalPoint;
double aspect;
@@ -296,7 +296,7 @@ Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = static_cast<float>(norm(p) * sin( min(fovx, fovy) * 0.5 * CV_PI / 180));
float cbHalfWidth = static_cast<float>(norm(p) * sin( std::min(fovx, fovy) * 0.5 * CV_PI / 180));
float cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
vector<Point3f> pts3d(4);

View File

@@ -1,6 +1,7 @@
#include <opencv2/core/utility.hpp>
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <ctype.h>
@@ -32,12 +33,12 @@ static void onMouse( int event, int x, int y, int, void* )
switch( event )
{
case CV_EVENT_LBUTTONDOWN:
case EVENT_LBUTTONDOWN:
origin = Point(x,y);
selection = Rect(x,y,0,0);
selectObject = true;
break;
case CV_EVENT_LBUTTONUP:
case EVENT_LBUTTONUP:
selectObject = false;
if( selection.width > 0 && selection.height > 0 )
trackObject = -1;
@@ -77,7 +78,7 @@ int main( int argc, const char** argv )
float hranges[] = {0,180};
const float* phranges = hranges;
CommandLineParser parser(argc, argv, keys);
int camNum = parser.get<int>(1);
int camNum = parser.get<int>(0);
cap.open(camNum);
@@ -113,7 +114,7 @@ int main( int argc, const char** argv )
if( !paused )
{
cvtColor(image, hsv, CV_BGR2HSV);
cvtColor(image, hsv, COLOR_BGR2HSV);
if( trackObject )
{
@@ -129,7 +130,7 @@ int main( int argc, const char** argv )
{
Mat roi(hue, selection), maskroi(mask, selection);
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
normalize(hist, hist, 0, 255, CV_MINMAX);
normalize(hist, hist, 0, 255, NORM_MINMAX);
trackWindow = selection;
trackObject = 1;
@@ -139,7 +140,7 @@ int main( int argc, const char** argv )
Mat buf(1, hsize, CV_8UC3);
for( int i = 0; i < hsize; i++ )
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255);
cvtColor(buf, buf, CV_HSV2BGR);
cvtColor(buf, buf, COLOR_HSV2BGR);
for( int i = 0; i < hsize; i++ )
{
@@ -153,7 +154,7 @@ int main( int argc, const char** argv )
calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
backproj &= mask;
RotatedRect trackBox = CamShift(backproj, trackWindow,
TermCriteria( CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1 ));
TermCriteria( TermCriteria::EPS | TermCriteria::COUNT, 10, 1 ));
if( trackWindow.area() <= 1 )
{
int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6;
@@ -163,8 +164,8 @@ int main( int argc, const char** argv )
}
if( backprojMode )
cvtColor( backproj, image, CV_GRAY2BGR );
ellipse( image, trackBox, Scalar(0,0,255), 3, CV_AA );
cvtColor( backproj, image, COLOR_GRAY2BGR );
ellipse( image, trackBox, Scalar(0,0,255), 3, LINE_AA );
}
}
else if( trackObject < 0 )

View File

@@ -1,6 +1,7 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/contrib.hpp"
#include <iostream>
@@ -29,8 +30,8 @@ int main( int argc, const char** argv )
help();
CommandLineParser parser(argc, argv, keys);
string image = parser.get<string>(1);
string templ = parser.get<string>(2);
string image = parser.get<string>(0);
string templ = parser.get<string>(1);
Mat img = imread(image.c_str(), 0);
Mat tpl = imread(templ.c_str(), 0);
@@ -40,7 +41,7 @@ int main( int argc, const char** argv )
return -1;
}
Mat cimg;
cvtColor(img, cimg, CV_GRAY2BGR);
cvtColor(img, cimg, COLOR_GRAY2BGR);
// if the image and the template are not edge maps but normal grayscale images,
// you might want to uncomment the lines below to produce the maps. You can also

View File

@@ -1,5 +1,6 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
using namespace cv;
@@ -11,25 +12,21 @@ int threshval = 100;
static void on_trackbar(int, void*)
{
Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( bw, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
Mat dst = Mat::zeros(img.size(), CV_8UC3);
if( !contours.empty() && !hierarchy.empty() )
{
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
Scalar color( (rand()&255), (rand()&255), (rand()&255) );
drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
}
Mat labelImage(img.size(), CV_32S);
int nLabels = connectedComponents(bw, labelImage, 8);
std::vector<Vec3b> colors(nLabels);
colors[0] = Vec3b(0, 0, 0);//background
for(int label = 1; label < nLabels; ++label){
colors[label] = Vec3b( (rand()&255), (rand()&255), (rand()&255) );
}
Mat dst(img.size(), CV_8UC3);
for(int r = 0; r < dst.rows; ++r){
for(int c = 0; c < dst.cols; ++c){
int label = labelImage.at<int>(r, c);
Vec3b &pixel = dst.at<Vec3b>(r, c);
pixel = colors[label];
}
}
imshow( "Connected Components", dst );
}
@@ -45,14 +42,14 @@ static void help()
const char* keys =
{
"{@image |stuff.jpg|image for converting to a grayscale}"
"{@image|stuff.jpg|image for converting to a grayscale}"
};
int main( int argc, const char** argv )
{
help();
CommandLineParser parser(argc, argv, keys);
string inputImage = parser.get<string>(1);
string inputImage = parser.get<string>(0);
img = imread(inputImage.c_str(), 0);
if(img.empty())

View File

@@ -28,7 +28,7 @@ static void on_trackbar(int, void*)
Mat cnt_img = Mat::zeros(w, w, CV_8UC3);
int _levels = levels - 3;
drawContours( cnt_img, contours, _levels <= 0 ? 3 : -1, Scalar(128,255,255),
3, CV_AA, hierarchy, std::abs(_levels) );
3, LINE_AA, hierarchy, std::abs(_levels) );
imshow("contours", cnt_img);
}

View File

@@ -41,7 +41,7 @@ int main( int /*argc*/, char** /*argv*/ )
img = Scalar::all(0);
for( i = 0; i < count; i++ )
circle(img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA);
circle(img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA);
int hullcount = (int)hull.size();
Point pt0 = points[hull[hullcount-1]];
@@ -49,7 +49,7 @@ int main( int /*argc*/, char** /*argv*/ )
for( i = 0; i < hullcount; i++ )
{
Point pt = points[hull[i]];
line(img, pt0, pt, Scalar(0, 255, 0), 1, CV_AA);
line(img, pt0, pt, Scalar(0, 255, 0), 1,LINE_AA);
pt0 = pt;
}

View File

@@ -30,16 +30,16 @@ int main(int,char**)
help();
Mat I = Mat::eye(4, 4, CV_64F);
I.at<double>(1,1) = CV_PI;
cout << "I = " << I << ";" << endl;
cout << "I = \n" << I << ";" << endl << endl;
Mat r = Mat(10, 3, CV_8UC3);
randu(r, Scalar::all(0), Scalar::all(255));
cout << "r (default) = " << r << ";" << endl << endl;
cout << "r (python) = " << format(r,"python") << ";" << endl << endl;
cout << "r (numpy) = " << format(r,"numpy") << ";" << endl << endl;
cout << "r (csv) = " << format(r,"csv") << ";" << endl << endl;
cout << "r (c) = " << format(r,"C") << ";" << endl << endl;
cout << "r (default) = \n" << r << ";" << endl << endl;
cout << "r (python) = \n" << format(r, Formatter::FMT_PYTHON) << ";" << endl << endl;
cout << "r (numpy) = \n" << format(r, Formatter::FMT_NUMPY) << ";" << endl << endl;
cout << "r (csv) = \n" << format(r, Formatter::FMT_CSV) << ";" << endl << endl;
cout << "r (c) = \n" << format(r, Formatter::FMT_C) << ";" << endl << endl;
Point2f p(5, 1);
cout << "p = " << p << ";" << endl;

View File

@@ -79,12 +79,12 @@ int main(int , char** )
for (size_t i = 0; i < Faces.size(); i++)
{
rectangle(ReferenceFrame, Faces[i], CV_RGB(0,255,0));
rectangle(ReferenceFrame, Faces[i], Scalar(0,255,0));
}
imshow(WindowName, ReferenceFrame);
if (cvWaitKey(30) >= 0) break;
if (waitKey(30) >= 0) break;
}
Detector.stop();

View File

@@ -18,7 +18,7 @@ static void help()
static void draw_subdiv_point( Mat& img, Point2f fp, Scalar color )
{
circle( img, fp, 3, color, CV_FILLED, 8, 0 );
circle( img, fp, 3, color, FILLED, LINE_8, 0 );
}
static void draw_subdiv( Mat& img, Subdiv2D& subdiv, Scalar delaunay_color )
@@ -34,9 +34,9 @@ static void draw_subdiv( Mat& img, Subdiv2D& subdiv, Scalar delaunay_color )
pt[0] = Point(cvRound(t[0]), cvRound(t[1]));
pt[1] = Point(cvRound(t[2]), cvRound(t[3]));
pt[2] = Point(cvRound(t[4]), cvRound(t[5]));
line(img, pt[0], pt[1], delaunay_color, 1, CV_AA, 0);
line(img, pt[1], pt[2], delaunay_color, 1, CV_AA, 0);
line(img, pt[2], pt[0], delaunay_color, 1, CV_AA, 0);
line(img, pt[0], pt[1], delaunay_color, 1, LINE_AA, 0);
line(img, pt[1], pt[2], delaunay_color, 1, LINE_AA, 0);
line(img, pt[2], pt[0], delaunay_color, 1, LINE_AA, 0);
}
#else
vector<Vec4f> edgeList;
@@ -46,7 +46,7 @@ static void draw_subdiv( Mat& img, Subdiv2D& subdiv, Scalar delaunay_color )
Vec4f e = edgeList[i];
Point pt0 = Point(cvRound(e[0]), cvRound(e[1]));
Point pt1 = Point(cvRound(e[2]), cvRound(e[3]));
line(img, pt0, pt1, delaunay_color, 1, CV_AA, 0);
line(img, pt0, pt1, delaunay_color, 1, LINE_AA, 0);
}
#endif
}
@@ -64,7 +64,7 @@ static void locate_point( Mat& img, Subdiv2D& subdiv, Point2f fp, Scalar active_
{
Point2f org, dst;
if( subdiv.edgeOrg(e, &org) > 0 && subdiv.edgeDst(e, &dst) > 0 )
line( img, org, dst, active_color, 3, CV_AA, 0 );
line( img, org, dst, active_color, 3, LINE_AA, 0 );
e = subdiv.getEdge(e, Subdiv2D::NEXT_AROUND_LEFT);
}
@@ -97,8 +97,8 @@ static void paint_voronoi( Mat& img, Subdiv2D& subdiv )
fillConvexPoly(img, ifacet, color, 8, 0);
ifacets[0] = ifacet;
polylines(img, ifacets, true, Scalar(), 1, CV_AA, 0);
circle(img, centers[i], 3, Scalar(), -1, CV_AA, 0);
polylines(img, ifacets, true, Scalar(), 1, LINE_AA, 0);
circle(img, centers[i], 3, Scalar(), FILLED, LINE_AA, 0);
}
}

View File

@@ -1,5 +1,6 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
@@ -43,7 +44,7 @@ static void updateBrightnessContrast( int /*arg*/, void* )
calcHist(&dst, 1, 0, Mat(), hist, 1, &histSize, 0);
Mat histImage = Mat::ones(200, 320, CV_8U)*255;
normalize(hist, hist, 0, histImage.rows, CV_MINMAX, CV_32F);
normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, CV_32F);
histImage = Scalar::all(255);
int binW = cvRound((double)histImage.cols/histSize);
@@ -70,7 +71,7 @@ int main( int argc, const char** argv )
help();
CommandLineParser parser(argc, argv, keys);
string inputImage = parser.get<string>(1);
string inputImage = parser.get<string>(0);
// Load the source image. HighGUI use.
image = imread( inputImage, 0 );

View File

@@ -45,7 +45,7 @@ static int getMatcherFilterType( const string& str )
return NONE_FILTER;
if( str == "CrossCheckFilter" )
return CROSS_CHECK_FILTER;
CV_Error(CV_StsBadArg, "Invalid filter name");
CV_Error(Error::StsBadArg, "Invalid filter name");
return -1;
}
@@ -109,12 +109,12 @@ static void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
Ptr<DescriptorMatcher>& descriptorMatcher, int matcherFilter, bool eval,
double ransacReprojThreshold, RNG& rng )
{
assert( !img1.empty() );
CV_Assert( !img1.empty() );
Mat H12;
if( isWarpPerspective )
warpPerspectiveRand(img1, img2, H12, rng );
else
assert( !img2.empty()/* && img2.cols==img1.cols && img2.rows==img1.rows*/ );
CV_Assert( !img2.empty()/* && img2.cols==img1.cols && img2.rows==img1.rows*/ );
cout << endl << "< Extracting keypoints from second image..." << endl;
vector<KeyPoint> keypoints2;
@@ -189,7 +189,7 @@ static void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
cout << "< Computing homography (RANSAC)..." << endl;
vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
H12 = findHomography( Mat(points1), Mat(points2), CV_RANSAC, ransacReprojThreshold );
H12 = findHomography( Mat(points1), Mat(points2), RANSAC, ransacReprojThreshold );
cout << ">" << endl;
}
@@ -208,7 +208,7 @@ static void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
matchesMask[i1] = 1;
}
// draw inliers
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, Scalar(0, 255, 0), Scalar(0, 0, 255), matchesMask
#if DRAW_RICH_KEYPOINTS_MODE
, DrawMatchesFlags::DRAW_RICH_KEYPOINTS
#endif
@@ -218,9 +218,11 @@ static void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
// draw outliers
for( size_t i1 = 0; i1 < matchesMask.size(); i1++ )
matchesMask[i1] = !matchesMask[i1];
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, CV_RGB(0, 0, 255), CV_RGB(255, 0, 0), matchesMask,
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, Scalar(0, 0, 255), Scalar(255, 0, 0), matchesMask,
DrawMatchesFlags::DRAW_OVER_OUTIMG | DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
#endif
cout << "Number of inliers: " << countNonZero(matchesMask) << endl;
}
else
drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg );

View File

@@ -1,10 +1,10 @@
#if defined(__linux__) || defined(LINUX) || defined(__APPLE__) || defined(ANDROID)
#include <opencv2/core/core.hpp>
#include <opencv2/core/internal.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/objdetect.hpp>
#include "opencv2/contrib/detection_based_tracker.hpp"
#include <vector>
@@ -144,7 +144,7 @@ static int test_FaceDetector(int argc, char *argv[])
LOGD("\n\nSTEP n=%d from prev step %f ms\n", n, t_ms);
m=images[n-1];
CV_Assert(! m.empty());
cvtColor(m, gray, CV_BGR2GRAY);
cvtColor(m, gray, COLOR_BGR2GRAY);
fd.process(gray);

View File

@@ -39,10 +39,10 @@
//
//M*/
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/legacy/legacy.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/legacy.hpp"
#include <limits>
#include <cstdio>
@@ -93,7 +93,7 @@ static void calcKeyPointProjections( const vector<KeyPoint>& src, const Mat_<dou
{
if( !src.empty() )
{
assert( !H.empty() && H.cols == 3 && H.rows == 3);
CV_Assert( !H.empty() && H.cols == 3 && H.rows == 3);
dst.resize(src.size());
vector<KeyPoint>::const_iterator srcIt = src.begin();
vector<KeyPoint>::iterator dstIt = dst.begin();
@@ -109,7 +109,7 @@ static void calcKeyPointProjections( const vector<KeyPoint>& src, const Mat_<dou
Mat_<double> Aff; linearizeHomographyAt(H, srcIt->pt, Aff);
Mat_<double> dstM; invert(Aff*invM*Aff.t(), dstM);
Mat_<double> eval; eigen( dstM, eval );
assert( eval(0,0) && eval(1,0) );
CV_Assert( eval(0,0) && eval(1,0) );
float dstSize = (float)pow(1./(eval(0,0)*eval(1,0)), 0.25);
// TODO: check angle projection
@@ -526,7 +526,7 @@ inline void writeKeypoints( FileStorage& fs, const vector<KeyPoint>& keypoints,
inline void readKeypoints( FileStorage& fs, vector<KeyPoint>& keypoints, int imgIdx )
{
assert( fs.isOpened() );
CV_Assert( fs.isOpened() );
stringstream imgName; imgName << "img" << imgIdx;
read( fs[imgName.str()], keypoints);
}
@@ -535,7 +535,7 @@ void DetectorQualityEvaluator::readAlgorithm ()
{
defaultDetector = FeatureDetector::create( algName );
specificDetector = FeatureDetector::create( algName );
if( defaultDetector == 0 )
if( defaultDetector.empty() )
{
printf( "Algorithm can not be read\n" );
exit(-1);
@@ -769,14 +769,14 @@ void DescriptorQualityEvaluator::readAlgorithm( )
defaultDescMatcher = GenericDescriptorMatcher::create( algName );
specificDescMatcher = GenericDescriptorMatcher::create( algName );
if( defaultDescMatcher == 0 )
if( defaultDescMatcher.empty() )
{
Ptr<DescriptorExtractor> extractor = DescriptorExtractor::create( algName );
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create( matcherName );
defaultDescMatcher = new VectorDescriptorMatch( extractor, matcher );
specificDescMatcher = new VectorDescriptorMatch( extractor, matcher );
if( extractor == 0 || matcher == 0 )
if( extractor.empty() || matcher.empty() )
{
printf("Algorithm can not be read\n");
exit(-1);

View File

@@ -39,9 +39,10 @@
//
//M*/
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/features2d.hpp"
#include <stdlib.h>
#include <stdio.h>

View File

@@ -1,6 +1,7 @@
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
@@ -24,9 +25,9 @@ int main(int argc, const char ** argv)
{
help();
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>(1);
string filename = parser.get<string>(0);
Mat img = imread(filename.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
Mat img = imread(filename.c_str(), IMREAD_GRAYSCALE);
if( img.empty() )
{
help();
@@ -73,7 +74,7 @@ int main(int argc, const char ** argv)
q2.copyTo(q1);
tmp.copyTo(q2);
normalize(mag, mag, 0, 1, CV_MINMAX);
normalize(mag, mag, 0, 1, NORM_MINMAX);
imshow("spectrum magnitude", mag);
waitKey();

View File

@@ -1,14 +1,16 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
using namespace std;
using namespace cv;
int maskSize0 = CV_DIST_MASK_5;
int maskSize0 = DIST_MASK_5;
int voronoiType = -1;
int edgeThresh = 100;
int distType0 = CV_DIST_L1;
int distType0 = DIST_L1;
// The output and temporary images
Mat gray;
@@ -29,8 +31,8 @@ static void onTrackbar( int, void* )
Scalar(255,0,255)
};
int maskSize = voronoiType >= 0 ? CV_DIST_MASK_5 : maskSize0;
int distType = voronoiType >= 0 ? CV_DIST_L2 : distType0;
int maskSize = voronoiType >= 0 ? DIST_MASK_5 : maskSize0;
int distType = voronoiType >= 0 ? DIST_L2 : distType0;
Mat edge = gray >= edgeThresh, dist, labels, dist8u;
@@ -111,7 +113,7 @@ int main( int argc, const char** argv )
{
help();
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>(1);
string filename = parser.get<string>(0);
gray = imread(filename.c_str(), 0);
if(gray.empty())
{
@@ -128,7 +130,7 @@ int main( int argc, const char** argv )
// Call to update the view
onTrackbar(0, 0);
int c = cvWaitKey(0) & 255;
int c = waitKey() & 255;
if( c == 27 )
break;
@@ -138,17 +140,17 @@ int main( int argc, const char** argv )
voronoiType = -1;
if( c == 'c' || c == 'C' )
distType0 = CV_DIST_C;
distType0 = DIST_C;
else if( c == '1' )
distType0 = CV_DIST_L1;
distType0 = DIST_L1;
else if( c == '2' )
distType0 = CV_DIST_L2;
distType0 = DIST_L2;
else if( c == '3' )
maskSize0 = CV_DIST_MASK_3;
maskSize0 = DIST_MASK_3;
else if( c == '5' )
maskSize0 = CV_DIST_MASK_5;
maskSize0 = DIST_MASK_5;
else if( c == '0' )
maskSize0 = CV_DIST_MASK_PRECISE;
maskSize0 = DIST_MASK_PRECISE;
else if( c == 'v' )
voronoiType = 0;
else if( c == 'p' )
@@ -160,18 +162,18 @@ int main( int argc, const char** argv )
else if( voronoiType == 1 )
{
voronoiType = -1;
maskSize0 = CV_DIST_MASK_3;
distType0 = CV_DIST_C;
maskSize0 = DIST_MASK_3;
distType0 = DIST_C;
}
else if( distType0 == CV_DIST_C )
distType0 = CV_DIST_L1;
else if( distType0 == CV_DIST_L1 )
distType0 = CV_DIST_L2;
else if( maskSize0 == CV_DIST_MASK_3 )
maskSize0 = CV_DIST_MASK_5;
else if( maskSize0 == CV_DIST_MASK_5 )
maskSize0 = CV_DIST_MASK_PRECISE;
else if( maskSize0 == CV_DIST_MASK_PRECISE )
else if( distType0 == DIST_C )
distType0 = DIST_L1;
else if( distType0 == DIST_L1 )
distType0 = DIST_L2;
else if( maskSize0 == DIST_MASK_3 )
maskSize0 = DIST_MASK_5;
else if( maskSize0 == DIST_MASK_5 )
maskSize0 = DIST_MASK_PRECISE;
else if( maskSize0 == DIST_MASK_PRECISE )
voronoiType = 0;
}
}

View File

@@ -21,7 +21,7 @@ int main()
char wndname[] = "Drawing Demo";
const int NUMBER = 100;
const int DELAY = 5;
int lineType = CV_AA; // change it to 8 to see non-antialiased graphics
int lineType = LINE_AA; // change it to LINE_8 to see non-antialiased graphics
int i, width = 1000, height = 700;
int x1 = -width/2, x2 = width*3/2, y1 = -height/2, y2 = height*3/2;
RNG rng(0xFFFFFFFF);
@@ -157,14 +157,14 @@ int main()
return 0;
}
Size textsize = getTextSize("OpenCV forever!", CV_FONT_HERSHEY_COMPLEX, 3, 5, 0);
Size textsize = getTextSize("OpenCV forever!", FONT_HERSHEY_COMPLEX, 3, 5, 0);
Point org((width - textsize.width)/2, (height - textsize.height)/2);
Mat image2;
for( i = 0; i < 255; i += 2 )
{
image2 = image - Scalar::all(i);
putText(image2, "OpenCV forever!", org, CV_FONT_HERSHEY_COMPLEX, 3,
putText(image2, "OpenCV forever!", org, FONT_HERSHEY_COMPLEX, 3,
Scalar(i, i, 255), 5, lineType);
imshow(wndname, image2);

View File

@@ -1,5 +1,6 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
@@ -39,7 +40,7 @@ int main( int argc, const char** argv )
help();
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>(1);
string filename = parser.get<string>(0);
image = imread(filename, 1);
if(image.empty())
@@ -49,7 +50,7 @@ int main( int argc, const char** argv )
return -1;
}
cedge.create(image.size(), image.type());
cvtColor(image, gray, CV_BGR2GRAY);
cvtColor(image, gray, COLOR_BGR2GRAY);
// Create a window
namedWindow("Edge map", 1);

View File

@@ -1,5 +1,5 @@
#include "opencv2/legacy/legacy.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/legacy.hpp"
using namespace cv;
@@ -45,7 +45,7 @@ int main( int /*argc*/, char** /*argv*/ )
params.start_step = CvEM::START_AUTO_STEP;
params.term_crit.max_iter = 300;
params.term_crit.epsilon = 0.1;
params.term_crit.type = CV_TERMCRIT_ITER|CV_TERMCRIT_EPS;
params.term_crit.type = TermCriteria::COUNT|TermCriteria::EPS;
// cluster the data
em_model.train( samples, Mat(), params, &labels );
@@ -76,7 +76,7 @@ int main( int /*argc*/, char** /*argv*/ )
int response = cvRound(em_model.predict( sample ));
Scalar c = colors[response];
circle( img, Point(j, i), 1, c*0.75, CV_FILLED );
circle( img, Point(j, i), 1, c*0.75, FILLED );
}
}
@@ -84,7 +84,7 @@ int main( int /*argc*/, char** /*argv*/ )
for( i = 0; i < nsamples; i++ )
{
Point pt(cvRound(samples.at<float>(i, 0)), cvRound(samples.at<float>(i, 1)));
circle( img, pt, 1, colors[labels.at<int>(i)], CV_FILLED );
circle( img, pt, 1, colors[labels.at<int>(i)], FILLED );
}
imshow( "EM-clustering result", img );

View File

@@ -49,9 +49,11 @@
//
//M*/
#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/contrib.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/nonfree.hpp"
using namespace cv;
using namespace std;
@@ -204,7 +206,7 @@ int main(int argc, char * argv[]) {
}
Mat result_large(100, 100, CV_8UC1);
resize(result_small, result_large, Size(500, 500), 0, 0, CV_INTER_NN);
resize(result_small, result_large, Size(500, 500), 0, 0, INTER_NEAREST);
cout << endl << "Press any key to exit" << endl;
imshow("Confusion Matrix", result_large);

View File

@@ -16,9 +16,10 @@
* See <http://www.opensource.org/licenses/bsd-license>
*/
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/contrib.hpp"
#include <iostream>
#include <fstream>
@@ -31,7 +32,7 @@ static Mat toGrayscale(InputArray _src) {
Mat src = _src.getMat();
// only allow one channel
if(src.channels() != 1) {
CV_Error(CV_StsBadArg, "Only Matrices with one channel are supported");
CV_Error(Error::StsBadArg, "Only Matrices with one channel are supported");
}
// create and return normalized image
Mat dst;
@@ -43,7 +44,7 @@ static void read_csv(const string& filename, vector<Mat>& images, vector<int>& l
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
CV_Error(Error::StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line)) {
@@ -81,7 +82,7 @@ int main(int argc, const char *argv[]) {
// Quit if there are not enough images for this demo.
if(images.size() <= 1) {
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(CV_StsError, error_message);
CV_Error(Error::StsError, error_message);
}
// Get the height from the first image. We'll need this
// later in code to reshape the images to their original

View File

@@ -42,13 +42,13 @@ int main(int, char**)
for(;;)
{
cap >> frame;
cvtColor(frame, gray, CV_BGR2GRAY);
cvtColor(frame, gray, COLOR_BGR2GRAY);
if( prevgray.data )
{
calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, 3, 15, 3, 5, 1.2, 0);
cvtColor(prevgray, cflow, CV_GRAY2BGR);
drawOptFlowMap(flow, cflow, 16, 1.5, CV_RGB(0, 255, 0));
cvtColor(prevgray, cflow, COLOR_GRAY2BGR);
drawOptFlowMap(flow, cflow, 16, 1.5, Scalar(0, 255, 0));
imshow("flow", cflow);
}
if(waitKey(30)>=0)

View File

@@ -34,14 +34,14 @@ int newMaskVal = 255;
static void onMouse( int event, int x, int y, int, void* )
{
if( event != CV_EVENT_LBUTTONDOWN )
if( event != EVENT_LBUTTONDOWN )
return;
Point seed = Point(x,y);
int lo = ffillMode == 0 ? 0 : loDiff;
int up = ffillMode == 0 ? 0 : upDiff;
int flags = connectivity + (newMaskVal << 8) +
(ffillMode == 1 ? CV_FLOODFILL_FIXED_RANGE : 0);
(ffillMode == 1 ? FLOODFILL_FIXED_RANGE : 0);
int b = (unsigned)theRNG() & 255;
int g = (unsigned)theRNG() & 255;
int r = (unsigned)theRNG() & 255;
@@ -53,7 +53,7 @@ static void onMouse( int event, int x, int y, int, void* )
if( useMask )
{
threshold(mask, mask, 1, 128, CV_THRESH_BINARY);
threshold(mask, mask, 1, 128, THRESH_BINARY);
area = floodFill(dst, mask, seed, newVal, &ccomp, Scalar(lo, lo, lo),
Scalar(up, up, up), flags);
imshow( "mask", mask );
@@ -81,7 +81,7 @@ int main( int argc, char** argv )
}
help();
image0.copyTo(image);
cvtColor(image0, gray, CV_BGR2GRAY);
cvtColor(image0, gray, COLOR_BGR2GRAY);
mask.create(image0.rows+2, image0.cols+2, CV_8UC1);
namedWindow( "image", 0 );
@@ -106,7 +106,7 @@ int main( int argc, char** argv )
if( isColor )
{
cout << "Grayscale mode is set\n";
cvtColor(image0, gray, CV_BGR2GRAY);
cvtColor(image0, gray, COLOR_BGR2GRAY);
mask = Scalar::all(0);
isColor = false;
}
@@ -135,7 +135,7 @@ int main( int argc, char** argv )
case 'r':
cout << "Original image is restored\n";
image0.copyTo(image);
cvtColor(image, gray, CV_BGR2GRAY);
cvtColor(image, gray, COLOR_BGR2GRAY);
mask = Scalar::all(0);
break;
case 's':

View File

@@ -64,7 +64,7 @@ void processImage(int /*h*/, void*)
vector<vector<Point> > contours;
Mat bimage = image >= sliderPos;
findContours(bimage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
findContours(bimage, contours, RETR_LIST, CHAIN_APPROX_NONE);
Mat cimage = Mat::zeros(bimage.size(), CV_8UC3);
@@ -82,12 +82,12 @@ void processImage(int /*h*/, void*)
continue;
drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8);
ellipse(cimage, box, Scalar(0,0,255), 1, CV_AA);
ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, Scalar(0,255,255), 1, CV_AA);
ellipse(cimage, box, Scalar(0,0,255), 1, LINE_AA);
ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, Scalar(0,255,255), 1, LINE_AA);
Point2f vtx[4];
box.points(vtx);
for( int j = 0; j < 4; j++ )
line(cimage, vtx[j], vtx[(j+1)%4], Scalar(0,255,0), 1, CV_AA);
line(cimage, vtx[j], vtx[(j+1)%4], Scalar(0,255,0), 1, LINE_AA);
}
imshow("result", cimage);

View File

@@ -38,11 +38,11 @@
#include <string>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <opencv2/core.hpp>
#include "opencv2/core/utility.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/nonfree.hpp>
using namespace cv;
@@ -65,14 +65,14 @@ int main( int argc, char** argv ) {
}
// Load images
Mat imgA = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE );
Mat imgA = imread(argv[1], IMREAD_GRAYSCALE );
if( !imgA.data ) {
std::cout<< " --(!) Error reading image " << argv[1] << std::endl;
return -1;
}
Mat imgB = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE );
if( !imgA.data ) {
Mat imgB = imread(argv[2], IMREAD_GRAYSCALE );
if( !imgB.data ) {
std::cout << " --(!) Error reading image " << argv[2] << std::endl;
return -1;
}
@@ -94,9 +94,9 @@ int main( int argc, char** argv ) {
// MATCHER
// The standard Hamming distance can be used such as
// BruteForceMatcher<Hamming> matcher;
// BFMatcher matcher(NORM_HAMMING);
// or the proposed cascade of hamming distance using SSSE3
BruteForceMatcher<Hamming> matcher;
BFMatcher matcher(NORM_HAMMING);
// detect
double t = (double)getTickCount();
@@ -122,7 +122,7 @@ int main( int argc, char** argv ) {
Mat imgMatch;
drawMatches(imgA, keypointsA, imgB, keypointsB, matches, imgMatch);
namedWindow("matches", CV_WINDOW_KEEPRATIO);
namedWindow("matches", WINDOW_KEEPRATIO);
imshow("matches", imgMatch);
waitKey(0);
}

View File

@@ -6,6 +6,7 @@
#include <cstdio>
using namespace std;
using namespace cv;
static void help()
@@ -32,15 +33,15 @@ int main(int argc, char** argv)
std::string params_filename = std::string(argv[4]);
Ptr<GenericDescriptorMatcher> descriptorMatcher = GenericDescriptorMatcher::create(alg_name, params_filename);
if( descriptorMatcher == 0 )
if( descriptorMatcher.empty() )
{
printf ("Cannot create descriptor\n");
return 0;
}
//printf("Reading the images...\n");
Mat img1 = imread(img1_name, CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(img2_name, CV_LOAD_IMAGE_GRAYSCALE);
Mat img1 = imread(img1_name, IMREAD_GRAYSCALE);
Mat img2 = imread(img2_name, IMREAD_GRAYSCALE);
// extract keypoints from the first image
SURF surf_extractor(5.0e3);
@@ -79,7 +80,7 @@ Mat DrawCorrespondences(const Mat& img1, const vector<KeyPoint>& features1, cons
for (size_t i = 0; i < features1.size(); i++)
{
circle(img_corr, features1[i].pt, 3, CV_RGB(255, 0, 0));
circle(img_corr, features1[i].pt, 3, Scalar(255, 0, 0));
}
for (size_t i = 0; i < features2.size(); i++)

View File

@@ -33,13 +33,13 @@ const Scalar BLUE = Scalar(255,0,0);
const Scalar LIGHTBLUE = Scalar(255,255,160);
const Scalar GREEN = Scalar(0,255,0);
const int BGD_KEY = CV_EVENT_FLAG_CTRLKEY;
const int FGD_KEY = CV_EVENT_FLAG_SHIFTKEY;
const int BGD_KEY = EVENT_FLAG_CTRLKEY;
const int FGD_KEY = EVENT_FLAG_SHIFTKEY;
static void getBinMask( const Mat& comMask, Mat& binMask )
{
if( comMask.empty() || comMask.type()!=CV_8UC1 )
CV_Error( CV_StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)" );
CV_Error( Error::StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)" );
if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols )
binMask.create( comMask.size(), CV_8UC1 );
binMask = comMask & 1;
@@ -132,7 +132,7 @@ void GCApplication::showImage() const
void GCApplication::setRectInMask()
{
assert( !mask.empty() );
CV_Assert( !mask.empty() );
mask.setTo( GC_BGD );
rect.x = max(0, rect.x);
rect.y = max(0, rect.y);
@@ -176,7 +176,7 @@ void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
// TODO add bad args check
switch( event )
{
case CV_EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
case EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
{
bool isb = (flags & BGD_KEY) != 0,
isf = (flags & FGD_KEY) != 0;
@@ -189,7 +189,7 @@ void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
lblsState = IN_PROCESS;
}
break;
case CV_EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels
case EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels
{
bool isb = (flags & BGD_KEY) != 0,
isf = (flags & FGD_KEY) != 0;
@@ -197,13 +197,13 @@ void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
prLblsState = IN_PROCESS;
}
break;
case CV_EVENT_LBUTTONUP:
case EVENT_LBUTTONUP:
if( rectState == IN_PROCESS )
{
rect = Rect( Point(rect.x, rect.y), Point(x,y) );
rectState = SET;
setRectInMask();
assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
showImage();
}
if( lblsState == IN_PROCESS )
@@ -213,7 +213,7 @@ void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
showImage();
}
break;
case CV_EVENT_RBUTTONUP:
case EVENT_RBUTTONUP:
if( prLblsState == IN_PROCESS )
{
setLblsInMask(flags, Point(x,y), true);
@@ -221,11 +221,11 @@ void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
showImage();
}
break;
case CV_EVENT_MOUSEMOVE:
case EVENT_MOUSEMOVE:
if( rectState == IN_PROCESS )
{
rect = Rect( Point(rect.x, rect.y), Point(x,y) );
assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
showImage();
}
else if( lblsState == IN_PROCESS )
@@ -296,15 +296,15 @@ int main( int argc, char** argv )
help();
const string winName = "image";
cvNamedWindow( winName.c_str(), CV_WINDOW_AUTOSIZE );
cvSetMouseCallback( winName.c_str(), on_mouse, 0 );
namedWindow( winName.c_str(), WINDOW_AUTOSIZE );
setMouseCallback( winName.c_str(), on_mouse, 0 );
gcapp.setImageAndWinName( image, winName );
gcapp.showImage();
for(;;)
{
int c = cvWaitKey(0);
int c = waitKey();
switch( (char) c )
{
case '\x1b':
@@ -331,6 +331,6 @@ int main( int argc, char** argv )
}
exit_main:
cvDestroyWindow( winName.c_str() );
destroyWindow( winName.c_str() );
return 0;
}

View File

@@ -27,18 +27,18 @@ int main(int argc, char** argv)
Mat cimg;
medianBlur(img, img, 5);
cvtColor(img, cimg, CV_GRAY2BGR);
cvtColor(img, cimg, COLOR_GRAY2BGR);
vector<Vec3f> circles;
HoughCircles(img, circles, CV_HOUGH_GRADIENT, 1, 10,
HoughCircles(img, circles, HOUGH_GRADIENT, 1, 10,
100, 30, 1, 30 // change the last two parameters
// (min_radius & max_radius) to detect larger circles
);
for( size_t i = 0; i < circles.size(); i++ )
{
Vec3i c = circles[i];
circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, CV_AA);
circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, CV_AA);
circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, LINE_AA);
circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, LINE_AA);
}
imshow("detected circles", cimg);

View File

@@ -27,7 +27,7 @@ int main(int argc, char** argv)
Mat dst, cdst;
Canny(src, dst, 50, 200, 3);
cvtColor(dst, cdst, CV_GRAY2BGR);
cvtColor(dst, cdst, COLOR_GRAY2BGR);
#if 0
vector<Vec2f> lines;
@@ -51,7 +51,7 @@ int main(int argc, char** argv)
for( size_t i = 0; i < lines.size(); i++ )
{
Vec4i l = lines[i];
line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, LINE_AA);
}
#endif
imshow("source", src);

View File

@@ -11,10 +11,6 @@
*
*/
//#include <cv.h>
//#include <ml.h>
//#include <cvaux.h>
//#include <highgui.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
@@ -47,12 +43,12 @@ static void onMouse(int event, int x, int y, int, void*) {
}
switch (event) {
case CV_EVENT_LBUTTONDOWN:
case EVENT_LBUTTONDOWN:
origin = Point(x, y);
selection = Rect(x, y, 0, 0);
selectObject = true;
break;
case CV_EVENT_LBUTTONUP:
case EVENT_LBUTTONUP:
selectObject = false;
trackObject = -1;
break;
@@ -96,8 +92,8 @@ int main(int argc, char** argv)
return 0;
}
cout << "Opened camera" << endl;
cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
cap.set(CAP_PROP_FRAME_WIDTH, 640);
cap.set(CAP_PROP_FRAME_HEIGHT, 480);
cap >> frame;
}
@@ -137,7 +133,7 @@ int main(int argc, char** argv)
int values_read = fscanf(f, "%d %f %f %f %f\n", &i, &w[0], &w[1], &w[2], &w[3]);
CV_Assert(values_read == 5);
sprintf(img_file, "seqG/%04d.png", i);
image = imread(img_file, CV_LOAD_IMAGE_COLOR);
image = imread(img_file, IMREAD_COLOR);
if (image.empty())
break;
selection = Rect(cvRound(w[0]*image.cols), cvRound(w[1]*image.rows),

View File

@@ -1,8 +1,9 @@
#include <stdio.h>
#include <iostream>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/flann/miniflann.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/flann/miniflann.hpp>
#include <opencv2/core/utility.hpp>
using namespace cv; // all the new API is put into "cv" namespace. Export its content
using namespace std;
@@ -21,6 +22,10 @@ static void help()
// enable/disable use of mixed API in the code below.
#define DEMO_MIXED_API_USE 1
#ifdef DEMO_MIXED_API_USE
# include <opencv2/highgui/highgui_c.h>
#endif
int main( int argc, char** argv )
{
help();
@@ -32,7 +37,7 @@ int main( int argc, char** argv )
fprintf(stderr, "Can not load image %s\n", imagename);
return -1;
}
Mat img(iplimg); // cv::Mat replaces the CvMat and IplImage, but it's easy to convert
Mat img = cv::cvarrToMat(iplimg); // cv::Mat replaces the CvMat and IplImage, but it's easy to convert
// between the old and the new data structures (by default, only the header
// is converted, while the data is shared)
#else
@@ -48,7 +53,7 @@ int main( int argc, char** argv )
return -1;
Mat img_yuv;
cvtColor(img, img_yuv, CV_BGR2YCrCb); // convert image to YUV color space. The output image will be created automatically
cvtColor(img, img_yuv, COLOR_BGR2YCrCb); // convert image to YUV color space. The output image will be created automatically
vector<Mat> planes; // Vector is template vector class, similar to STL's vector. It can store matrices too.
split(img_yuv, planes); // split the image into separate color planes
@@ -106,10 +111,10 @@ int main( int argc, char** argv )
// now merge the results back
merge(planes, img_yuv);
// and produce the output RGB image
cvtColor(img_yuv, img, CV_YCrCb2BGR);
cvtColor(img_yuv, img, COLOR_YCrCb2BGR);
// this is counterpart for cvNamedWindow
namedWindow("image with grain", CV_WINDOW_AUTOSIZE);
namedWindow("image with grain", WINDOW_AUTOSIZE);
#if DEMO_MIXED_API_USE
// this is to demonstrate that img and iplimg really share the data - the result of the above
// processing is stored in img and thus in iplimg too.

View File

@@ -0,0 +1,386 @@
/*
* This sample demonstrates the use of the function
* findTransformECC that implements the image alignment ECC algorithm
*
*
* The demo loads an image (defaults to fruits.jpg) and it artificially creates
* a template image based on the given motion type. When two images are given,
* the first image is the input image and the second one defines the template image.
* In the latter case, you can also parse the warp's initialization.
*
* Input and output warp files consist of the raw warp (transform) elements
*
* Authors: G. Evangelidis, INRIA, Grenoble, France
* M. Asbach, Fraunhofer IAIS, St. Augustin, Germany
*/
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/core/utility.hpp>
#include <stdio.h>
#include <string>
#include <time.h>
#include <iostream>
#include <fstream>
using namespace cv;
using namespace std;
static void help(void);
static int readWarp(string iFilename, Mat& warp, int motionType);
static int saveWarp(string fileName, const Mat& warp, int motionType);
static void draw_warped_roi(Mat& image, const int width, const int height, Mat& W);
#define HOMO_VECTOR(H, x, y)\
H.at<float>(0,0) = (float)(x);\
H.at<float>(1,0) = (float)(y);\
H.at<float>(2,0) = 1.;
#define GET_HOMO_VALUES(X, x, y)\
(x) = static_cast<float> (X.at<float>(0,0)/X.at<float>(2,0));\
(y) = static_cast<float> (X.at<float>(1,0)/X.at<float>(2,0));
const std::string keys =
"{@inputImage | fruits.jpg | input image filename }"
"{@templateImage | | template image filename (optional)}"
"{@inputWarp | | input warp (matrix) filename (optional)}"
"{n numOfIter | 50 | ECC's iterations }"
"{e epsilon | 0.0001 | ECC's convergence epsilon }"
"{o outputWarp | outWarp.ecc | output warp (matrix) filename }"
"{m motionType | affine | type of motion (translation, euclidean, affine, homography) }"
"{v verbose | 0 | display initial and final images }"
"{w warpedImfile | warpedECC.png | warped input image }"
;
static void help(void)
{
cout << "\nThis file demostrates the use of the ECC image alignment algorithm. When one image"
" is given, the template image is artificially formed by a random warp. When both images"
" are given, the initialization of the warp by command line parsing is possible. "
"If inputWarp is missing, the identity transformation initializes the algorithm. \n" << endl;
cout << "\nUsage example (one image): \n./ecc fruits.jpg -o=outWarp.ecc "
"-m=euclidean -e=1e-6 -N=70 -v=1 \n" << endl;
cout << "\nUsage example (two images with initialization): \n./ecc yourInput.png yourTemplate.png "
"yourInitialWarp.ecc -o=outWarp.ecc -m=homography -e=1e-6 -N=70 -v=1 -w=yourFinalImage.png \n" << endl;
}
static int readWarp(string iFilename, Mat& warp, int motionType){
// it reads from file a specific number of raw values:
// 9 values for homography, 6 otherwise
CV_Assert(warp.type()==CV_32FC1);
int numOfElements;
if (motionType==MOTION_HOMOGRAPHY)
numOfElements=9;
else
numOfElements=6;
int i;
int ret_value;
ifstream myfile(iFilename.c_str());
if (myfile.is_open()){
float* matPtr = warp.ptr<float>(0);
for(i=0; i<numOfElements; i++){
myfile >> matPtr[i];
}
ret_value = 1;
}
else {
cout << "Unable to open file " << iFilename.c_str() << endl;
ret_value = 0;
}
return ret_value;
}
static int saveWarp(string fileName, const Mat& warp, int motionType)
{
// it saves the raw matrix elements in a file
CV_Assert(warp.type()==CV_32FC1);
const float* matPtr = warp.ptr<float>(0);
int ret_value;
ofstream outfile(fileName.c_str());
if( !outfile ) {
cerr << "error in saving "
<< "Couldn't open file '" << fileName.c_str() << "'!" << endl;
ret_value = 0;
}
else {//save the warp's elements
outfile << matPtr[0] << " " << matPtr[1] << " " << matPtr[2] << endl;
outfile << matPtr[3] << " " << matPtr[4] << " " << matPtr[5] << endl;
if (motionType==MOTION_HOMOGRAPHY){
outfile << matPtr[6] << " " << matPtr[7] << " " << matPtr[8] << endl;
}
ret_value = 1;
}
return ret_value;
}
static void draw_warped_roi(Mat& image, const int width, const int height, Mat& W)
{
Point2f top_left, top_right, bottom_left, bottom_right;
Mat H = Mat (3, 1, CV_32F);
Mat U = Mat (3, 1, CV_32F);
Mat warp_mat = Mat::eye (3, 3, CV_32F);
for (int y = 0; y < W.rows; y++)
for (int x = 0; x < W.cols; x++)
warp_mat.at<float>(y,x) = W.at<float>(y,x);
//warp the corners of rectangle
// top-left
HOMO_VECTOR(H, 1, 1);
gemm(warp_mat, H, 1, 0, 0, U);
GET_HOMO_VALUES(U, top_left.x, top_left.y);
// top-right
HOMO_VECTOR(H, width, 1);
gemm(warp_mat, H, 1, 0, 0, U);
GET_HOMO_VALUES(U, top_right.x, top_right.y);
// bottom-left
HOMO_VECTOR(H, 1, height);
gemm(warp_mat, H, 1, 0, 0, U);
GET_HOMO_VALUES(U, bottom_left.x, bottom_left.y);
// bottom-right
HOMO_VECTOR(H, width, height);
gemm(warp_mat, H, 1, 0, 0, U);
GET_HOMO_VALUES(U, bottom_right.x, bottom_right.y);
// draw the warped perimeter
line(image, top_left, top_right, Scalar(255,0,255));
line(image, top_right, bottom_right, Scalar(255,0,255));
line(image, bottom_right, bottom_left, Scalar(255,0,255));
line(image, bottom_left, top_left, Scalar(255,0,255));
}
int main (const int argc, const char * argv[])
{
CommandLineParser parser(argc, argv, keys);
parser.about("ECC demo");
if (argc<2) {
parser.printMessage();
help();
return 1;
}
string imgFile = parser.get<string>(0);
string tempImgFile = parser.get<string>(1);
string inWarpFile = parser.get<string>(2);
int number_of_iterations = parser.get<int>("n");
double termination_eps = parser.get<double>("e");
string warpType = parser.get<string>("m");
int verbose = parser.get<int>("v");
string finalWarp = parser.get<string>("o");
string warpedImFile = parser.get<string>("w");
if (!(warpType == "translation" || warpType == "euclidean"
|| warpType == "affine" || warpType == "homography"))
{
cerr << "Invalid motion transformation" << endl;
return -1;
}
int mode_temp;
if (warpType == "translation")
mode_temp = MOTION_TRANSLATION;
else if (warpType == "euclidean")
mode_temp = MOTION_EUCLIDEAN;
else if (warpType == "affine")
mode_temp = MOTION_AFFINE;
else
mode_temp = MOTION_HOMOGRAPHY;
Mat inputImage = imread(imgFile,0);
if (inputImage.empty())
{
cerr << "Unable to load the inputImage" << endl;
return -1;
}
Mat target_image;
Mat template_image;
if (tempImgFile!="") {
inputImage.copyTo(target_image);
template_image = imread(tempImgFile,0);
if (template_image.empty()){
cerr << "Unable to load the template image" << endl;
return -1;
}
}
else{ //apply random waro to input image
resize(inputImage, target_image, Size(216, 216));
Mat warpGround;
cv::RNG rng;
double angle;
switch (mode_temp) {
case MOTION_TRANSLATION:
warpGround = (Mat_<float>(2,3) << 1, 0, (rng.uniform(10.f, 20.f)),
0, 1, (rng.uniform(10.f, 20.f)));
warpAffine(target_image, template_image, warpGround,
Size(200,200), INTER_LINEAR + WARP_INVERSE_MAP);
break;
case MOTION_EUCLIDEAN:
angle = CV_PI/30 + CV_PI*rng.uniform((double)-2.f, (double)2.f)/180;
warpGround = (Mat_<float>(2,3) << cos(angle), -sin(angle), (rng.uniform(10.f, 20.f)),
sin(angle), cos(angle), (rng.uniform(10.f, 20.f)));
warpAffine(target_image, template_image, warpGround,
Size(200,200), INTER_LINEAR + WARP_INVERSE_MAP);
break;
case MOTION_AFFINE:
warpGround = (Mat_<float>(2,3) << (1-rng.uniform(-0.05f, 0.05f)),
(rng.uniform(-0.03f, 0.03f)), (rng.uniform(10.f, 20.f)),
(rng.uniform(-0.03f, 0.03f)), (1-rng.uniform(-0.05f, 0.05f)),
(rng.uniform(10.f, 20.f)));
warpAffine(target_image, template_image, warpGround,
Size(200,200), INTER_LINEAR + WARP_INVERSE_MAP);
break;
case MOTION_HOMOGRAPHY:
warpGround = (Mat_<float>(3,3) << (1-rng.uniform(-0.05f, 0.05f)),
(rng.uniform(-0.03f, 0.03f)), (rng.uniform(10.f, 20.f)),
(rng.uniform(-0.03f, 0.03f)), (1-rng.uniform(-0.05f, 0.05f)),(rng.uniform(10.f, 20.f)),
(rng.uniform(0.0001f, 0.0003f)), (rng.uniform(0.0001f, 0.0003f)), 1.f);
warpPerspective(target_image, template_image, warpGround,
Size(200,200), INTER_LINEAR + WARP_INVERSE_MAP);
break;
}
}
const int warp_mode = mode_temp;
// initialize or load the warp matrix
Mat warp_matrix;
if (warpType == "homography")
warp_matrix = Mat::eye(3, 3, CV_32F);
else
warp_matrix = Mat::eye(2, 3, CV_32F);
if (inWarpFile!=""){
int readflag = readWarp(inWarpFile, warp_matrix, warp_mode);
if ((!readflag) || warp_matrix.empty())
{
cerr << "-> Check warp initialization file" << endl << flush;
return -1;
}
}
else {
printf("\n ->Perfomarnce Warning: Identity warp ideally assumes images of "
"similar size. If the deformation is strong, the identity warp may not "
"be a good initialization. \n");
}
if (number_of_iterations > 200)
cout << "-> Warning: too many iterations " << endl;
if (warp_mode != MOTION_HOMOGRAPHY)
warp_matrix.rows = 2;
// start timing
const double tic_init = (double) getTickCount ();
double cc = findTransformECC (template_image, target_image, warp_matrix, warp_mode,
TermCriteria (TermCriteria::COUNT+TermCriteria::EPS,
number_of_iterations, termination_eps));
if (cc == -1)
{
cerr << "The execution was interrupted. The correlation value is going to be minimized." << endl;
cerr << "Check the warp initialization and/or the size of images." << endl << flush;
}
// end timing
const double toc_final = (double) getTickCount ();
const double total_time = (toc_final-tic_init)/(getTickFrequency());
if (verbose){
cout << "Alignment time (" << warpType << " transformation): "
<< total_time << " sec" << endl << flush;
// cout << "Final correlation: " << cc << endl << flush;
}
// save the final warp matrix
saveWarp(finalWarp, warp_matrix, warp_mode);
if (verbose){
cout << "\nThe final warp has been saved in the file: " << finalWarp << endl << flush;
}
// save the final warped image
Mat warped_image = Mat(template_image.rows, template_image.cols, CV_32FC1);
if (warp_mode != MOTION_HOMOGRAPHY)
warpAffine (target_image, warped_image, warp_matrix, warped_image.size(),
INTER_LINEAR + WARP_INVERSE_MAP);
else
warpPerspective (target_image, warped_image, warp_matrix, warped_image.size(),
INTER_LINEAR + WARP_INVERSE_MAP);
//save the warped image
imwrite(warpedImFile, warped_image);
// display resulting images
if (verbose)
{
cout << "The warped image has been saved in the file: " << warpedImFile << endl << flush;
namedWindow ("image", WINDOW_AUTOSIZE);
namedWindow ("template", WINDOW_AUTOSIZE);
namedWindow ("warped image", WINDOW_AUTOSIZE);
namedWindow ("error (black: no error)", WINDOW_AUTOSIZE);
moveWindow ("template", 350, 350);
moveWindow ("warped image", 600, 300);
moveWindow ("error (black: no error)", 900, 300);
// draw boundaries of corresponding regions
Mat identity_matrix = Mat::eye(3,3,CV_32F);
draw_warped_roi (target_image, template_image.cols-2, template_image.rows-2, warp_matrix);
draw_warped_roi (template_image, template_image.cols-2, template_image.rows-2, identity_matrix);
Mat errorImage;
subtract(template_image, warped_image, errorImage);
double max_of_error;
minMaxLoc(errorImage, NULL, &max_of_error);
// show images
cout << "Press any key to exit the demo (you might need to click on the images before)." << endl << flush;
imshow ("image", target_image);
waitKey (200);
imshow ("template", template_image);
waitKey (200);
imshow ("warped image", warped_image);
waitKey(200);
imshow ("error (black: no error)", abs(errorImage)*255/max_of_error);
waitKey(0);
}
// done
return 0;
}

View File

@@ -27,11 +27,11 @@ Point prevPt(-1,-1);
static void onMouse( int event, int x, int y, int flags, void* )
{
if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) )
if( event == EVENT_LBUTTONUP || !(flags & EVENT_FLAG_LBUTTON) )
prevPt = Point(-1,-1);
else if( event == CV_EVENT_LBUTTONDOWN )
else if( event == EVENT_LBUTTONDOWN )
prevPt = Point(x,y);
else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON) )
else if( event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON) )
{
Point pt(x,y);
if( prevPt.x < 0 )
@@ -81,7 +81,7 @@ int main( int argc, char** argv )
if( c == 'i' || c == ' ' )
{
Mat inpainted;
inpaint(img, inpaintMask, inpainted, 3, CV_INPAINT_TELEA);
inpaint(img, inpaintMask, inpainted, 3, INPAINT_TELEA);
imshow("inpainted image", inpainted);
}
}

View File

@@ -40,7 +40,7 @@ int main(int, char**)
for(;;)
{
randn( state, Scalar::all(0), Scalar::all(0.1) );
KF.transitionMatrix = *(Mat_<float>(2, 2) << 1, 1, 0, 1);
KF.transitionMatrix = (Mat_<float>(2, 2) << 1, 1, 0, 1);
setIdentity(KF.measurementMatrix);
setIdentity(KF.processNoiseCov, Scalar::all(1e-5));
@@ -69,18 +69,18 @@ int main(int, char**)
Point measPt = calcPoint(center, R, measAngle);
// plot points
#define drawCross( center, color, d ) \
line( img, Point( center.x - d, center.y - d ), \
Point( center.x + d, center.y + d ), color, 1, CV_AA, 0); \
line( img, Point( center.x + d, center.y - d ), \
Point( center.x - d, center.y + d ), color, 1, CV_AA, 0 )
#define drawCross( center, color, d ) \
line( img, Point( center.x - d, center.y - d ), \
Point( center.x + d, center.y + d ), color, 1, LINE_AA, 0); \
line( img, Point( center.x + d, center.y - d ), \
Point( center.x - d, center.y + d ), color, 1, LINE_AA, 0 )
img = Scalar::all(0);
drawCross( statePt, Scalar(255,255,255), 3 );
drawCross( measPt, Scalar(0,0,255), 3 );
drawCross( predictPt, Scalar(0,255,0), 3 );
line( img, statePt, measPt, Scalar(0,0,255), 3, CV_AA, 0 );
line( img, statePt, predictPt, Scalar(0,255,255), 3, CV_AA, 0 );
line( img, statePt, measPt, Scalar(0,0,255), 3, LINE_AA, 0 );
line( img, statePt, predictPt, Scalar(0,255,255), 3, LINE_AA, 0 );
if(theRNG().uniform(0,4) != 0)
KF.correct(measurement);

View File

@@ -47,13 +47,13 @@ int main( int /*argc*/, char** /*argv*/ )
Mat pointChunk = points.rowRange(k*sampleCount/clusterCount,
k == clusterCount - 1 ? sampleCount :
(k+1)*sampleCount/clusterCount);
rng.fill(pointChunk, CV_RAND_NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));
rng.fill(pointChunk, RNG::NORMAL, Scalar(center.x, center.y), Scalar(img.cols*0.05, img.rows*0.05));
}
randShuffle(points, 1, &rng);
kmeans(points, clusterCount, labels,
TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0),
TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 10, 1.0),
3, KMEANS_PP_CENTERS, centers);
img = Scalar::all(0);
@@ -62,7 +62,7 @@ int main( int /*argc*/, char** /*argv*/ )
{
int clusterIdx = labels.at<int>(i);
Point ipt = points.at<Point2f>(i);
circle( img, ipt, 2, colorTab[clusterIdx], CV_FILLED, CV_AA );
circle( img, ipt, 2, colorTab[clusterIdx], FILLED, LINE_AA );
}
imshow("clusters", img);

View File

@@ -17,8 +17,10 @@ static void help()
"./laplace [camera #, default 0]\n" << endl;
}
enum {GAUSSIAN, BLUR, MEDIAN};
int sigma = 3;
int smoothType = CV_GAUSSIAN;
int smoothType = GAUSSIAN;
int main( int argc, char** argv )
{
@@ -32,15 +34,15 @@ int main( int argc, char** argv )
cap.open(argv[1]);
if( cap.isOpened() )
cout << "Video " << argv[1] <<
": width=" << cap.get(CV_CAP_PROP_FRAME_WIDTH) <<
", height=" << cap.get(CV_CAP_PROP_FRAME_HEIGHT) <<
", nframes=" << cap.get(CV_CAP_PROP_FRAME_COUNT) << endl;
": width=" << cap.get(CAP_PROP_FRAME_WIDTH) <<
", height=" << cap.get(CAP_PROP_FRAME_HEIGHT) <<
", nframes=" << cap.get(CAP_PROP_FRAME_COUNT) << endl;
if( argc > 2 && isdigit(argv[2][0]) )
{
int pos;
sscanf(argv[2], "%d", &pos);
cout << "seeking to frame #" << pos << endl;
cap.set(CV_CAP_PROP_POS_FRAMES, pos);
cap.set(CAP_PROP_POS_FRAMES, pos);
}
}
@@ -63,9 +65,9 @@ int main( int argc, char** argv )
break;
int ksize = (sigma*5)|1;
if(smoothType == CV_GAUSSIAN)
if(smoothType == GAUSSIAN)
GaussianBlur(frame, smoothed, Size(ksize, ksize), sigma, sigma);
else if(smoothType == CV_BLUR)
else if(smoothType == BLUR)
blur(frame, smoothed, Size(ksize, ksize));
else
medianBlur(frame, smoothed, ksize);
@@ -76,7 +78,7 @@ int main( int argc, char** argv )
int c = waitKey(30);
if( c == ' ' )
smoothType = smoothType == CV_GAUSSIAN ? CV_BLUR : smoothType == CV_BLUR ? CV_MEDIAN : CV_GAUSSIAN;
smoothType = smoothType == GAUSSIAN ? BLUR : smoothType == BLUR ? MEDIAN : GAUSSIAN;
if( c == 'q' || c == 'Q' || (c & 255) == 27 )
break;
}

View File

@@ -47,7 +47,7 @@ static void detectAndDrawObjects( Mat& image, LatentSvmDetector& detector, const
cout << "Detection time = " << tm.getTimeSec() << " sec" << endl;
const vector<string> classNames = detector.getClassNames();
const vector<String> classNames = detector.getClassNames();
CV_Assert( colors.size() == classNames.size() );
for( size_t i = 0; i < detections.size(); i++ )
@@ -63,7 +63,7 @@ static void detectAndDrawObjects( Mat& image, LatentSvmDetector& detector, const
}
}
static void readDirectory( const string& directoryName, vector<string>& filenames, bool addDirectoryName=true )
static void readDirectory( const string& directoryName, vector<String>& filenames, bool addDirectoryName=true )
{
filenames.clear();
@@ -123,7 +123,7 @@ int main(int argc, char* argv[])
if( argc > 4 ) numThreads = atoi(argv[4]);
}
vector<string> images_filenames, models_filenames;
vector<String> images_filenames, models_filenames;
readDirectory( images_folder, images_filenames );
readDirectory( models_folder, models_filenames );
@@ -134,7 +134,7 @@ int main(int argc, char* argv[])
exit(-1);
}
const vector<string>& classNames = detector.getClassNames();
const vector<String>& classNames = detector.getClassNames();
cout << "Loaded " << classNames.size() << " models:" << endl;
for( size_t i = 0; i < classNames.size(); i++ )
{

View File

@@ -131,7 +131,7 @@ int build_rtrees_classifier( char* data_filename,
printf( "Could not read the classifier %s\n", filename_to_load );
return -1;
}
printf( "The classifier %s is loaded.\n", data_filename );
printf( "The classifier %s is loaded.\n", filename_to_load );
}
else
{
@@ -262,7 +262,7 @@ int build_boost_classifier( char* data_filename,
printf( "Could not read the classifier %s\n", filename_to_load );
return -1;
}
printf( "The classifier %s is loaded.\n", data_filename );
printf( "The classifier %s is loaded.\n", filename_to_load );
}
else
{
@@ -403,7 +403,7 @@ int build_mlp_classifier( char* data_filename,
printf( "Could not read the classifier %s\n", filename_to_load );
return -1;
}
printf( "The classifier %s is loaded.\n", data_filename );
printf( "The classifier %s is loaded.\n", filename_to_load );
}
else
{
@@ -463,7 +463,7 @@ int build_mlp_classifier( char* data_filename,
int best_class;
CvMat sample;
cvGetRow( data, &sample, i );
CvPoint max_loc = {0,0};
CvPoint max_loc;
mlp.predict( &sample, mlp_response );
cvMinMaxLoc( mlp_response, 0, 0, 0, &max_loc, 0 );
best_class = max_loc.x + 'A';
@@ -639,10 +639,11 @@ int build_nbayes_classifier( char* data_filename )
}
static
int build_svm_classifier( char* data_filename )
int build_svm_classifier( char* data_filename, const char* filename_to_save, const char* filename_to_load )
{
CvMat* data = 0;
CvMat* responses = 0;
CvMat* train_resp = 0;
CvMat train_data;
int nsamples_all = 0, ntrain_samples = 0;
int var_count;
@@ -666,13 +667,29 @@ int build_svm_classifier( char* data_filename )
ntrain_samples = (int)(nsamples_all*0.1);
var_count = data->cols;
// train classifier
printf( "Training the classifier (may take a few minutes)...\n");
cvGetRows( data, &train_data, 0, ntrain_samples );
CvMat* train_resp = cvCreateMat( ntrain_samples, 1, CV_32FC1);
for (int i = 0; i < ntrain_samples; i++)
train_resp->data.fl[i] = responses->data.fl[i];
svm.train(&train_data, train_resp, 0, 0, param);
// Create or load Random Trees classifier
if( filename_to_load )
{
// load classifier from the specified file
svm.load( filename_to_load );
ntrain_samples = 0;
if( svm.get_var_count() == 0 )
{
printf( "Could not read the classifier %s\n", filename_to_load );
return -1;
}
printf( "The classifier %s is loaded.\n", filename_to_load );
}
else
{
// train classifier
printf( "Training the classifier (may take a few minutes)...\n");
cvGetRows( data, &train_data, 0, ntrain_samples );
train_resp = cvCreateMat( ntrain_samples, 1, CV_32FC1);
for (int i = 0; i < ntrain_samples; i++)
train_resp->data.fl[i] = responses->data.fl[i];
svm.train(&train_data, train_resp, 0, 0, param);
}
// classification
std::vector<float> _sample(var_count * (nsamples_all - ntrain_samples));
@@ -691,7 +708,10 @@ int build_svm_classifier( char* data_filename )
CvMat *result = cvCreateMat(1, nsamples_all - ntrain_samples, CV_32FC1);
printf("Classification (may take a few minutes)...\n");
double t = (double)cvGetTickCount();
svm.predict(&sample, result);
t = (double)cvGetTickCount() - t;
printf("Prediction type: %gms\n", t/(cvGetTickFrequency()*1000.));
int true_resp = 0;
for (int i = 0; i < nsamples_all - ntrain_samples; i++)
@@ -702,6 +722,9 @@ int build_svm_classifier( char* data_filename )
printf("true_resp = %f%%\n", (float)true_resp / (nsamples_all - ntrain_samples) * 100);
if( filename_to_save )
svm.save( filename_to_save );
cvReleaseMat( &train_resp );
cvReleaseMat( &result );
cvReleaseMat( &data );
@@ -772,7 +795,7 @@ int main( int argc, char *argv[] )
method == 4 ?
build_nbayes_classifier( data_filename) :
method == 5 ?
build_svm_classifier( data_filename ):
build_svm_classifier( data_filename, filename_to_save, filename_to_load ):
-1) < 0)
{
help();

View File

@@ -1,8 +1,9 @@
#include <opencv2/core/core.hpp>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc/imgproc_c.h> // cvFindContours
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/highgui.hpp>
#include <iterator>
#include <set>
#include <cstdio>
@@ -30,7 +31,7 @@ class Mouse
public:
static void start(const std::string& a_img_name)
{
cvSetMouseCallback(a_img_name.c_str(), Mouse::cv_on_mouse, 0);
cv::setMouseCallback(a_img_name.c_str(), Mouse::cv_on_mouse, 0);
}
static int event(void)
{
@@ -129,7 +130,7 @@ static void writeLinemod(const cv::Ptr<cv::linemod::Detector>& detector, const s
cv::FileStorage fs(filename, cv::FileStorage::WRITE);
detector->write(fs);
std::vector<std::string> ids = detector->classIds();
std::vector<cv::String> ids = detector->classIds();
fs << "classes" << "[";
for (int i = 0; i < (int)ids.size(); ++i)
{
@@ -176,7 +177,7 @@ int main(int argc, char * argv[])
{
detector = readLinemod(argv[1]);
std::vector<std::string> ids = detector->classIds();
std::vector<cv::String> ids = detector->classIds();
num_classes = detector->numClasses();
printf("Loaded %s with %d classes and %d templates\n",
argv[1], num_classes, detector->numTemplates());
@@ -189,14 +190,14 @@ int main(int argc, char * argv[])
int num_modalities = (int)detector->getModalities().size();
// Open Kinect sensor
cv::VideoCapture capture( CV_CAP_OPENNI );
cv::VideoCapture capture( cv::CAP_OPENNI );
if (!capture.isOpened())
{
printf("Could not open OpenNI-capable sensor\n");
return -1;
}
capture.set(CV_CAP_PROP_OPENNI_REGISTRATION, 1);
double focal_length = capture.get(CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH);
capture.set(cv::CAP_PROP_OPENNI_REGISTRATION, 1);
double focal_length = capture.get(cv::CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH);
//printf("Focal length = %f\n", focal_length);
// Main loop
@@ -205,8 +206,8 @@ int main(int argc, char * argv[])
{
// Capture next color/depth pair
capture.grab();
capture.retrieve(depth, CV_CAP_OPENNI_DEPTH_MAP);
capture.retrieve(color, CV_CAP_OPENNI_BGR_IMAGE);
capture.retrieve(depth, cv::CAP_OPENNI_DEPTH_MAP);
capture.retrieve(color, cv::CAP_OPENNI_BGR_IMAGE);
std::vector<cv::Mat> sources;
sources.push_back(color);
@@ -223,7 +224,7 @@ int main(int argc, char * argv[])
cv::Point pt1 = mouse - roi_offset; // top left
cv::Point pt2 = mouse + roi_offset; // bottom right
if (event == CV_EVENT_RBUTTONDOWN)
if (event == cv::EVENT_RBUTTONDOWN)
{
// Compute object mask by subtracting the plane within the ROI
std::vector<CvPoint> chain(4);
@@ -259,7 +260,7 @@ int main(int argc, char * argv[])
// Perform matching
std::vector<cv::linemod::Match> matches;
std::vector<std::string> class_ids;
std::vector<cv::String> class_ids;
std::vector<cv::Mat> quantized_images;
match_timer.start();
detector->match(sources, (float)matching_threshold, matches, class_ids, quantized_images);
@@ -330,7 +331,7 @@ int main(int argc, char * argv[])
cv::imshow("normals", quantized_images[1]);
cv::FileStorage fs;
char key = (char)cvWaitKey(10);
char key = (char)cv::waitKey(10);
if( key == 'q' )
break;

View File

@@ -12,9 +12,8 @@ static void help()
{
// print a welcome message, and the OpenCV version
cout << "\nThis is a demo of Lukas-Kanade optical flow lkdemo(),\n"
"Using OpenCV version %s\n" << CV_VERSION << "\n"
<< endl;
"Using OpenCV version " << CV_VERSION << endl;
cout << "\nIt uses camera by default, but you can provide a path to video as an argument.\n";
cout << "\nHot keys: \n"
"\tESC - quit the program\n"
"\tr - auto-initialize tracking\n"
@@ -28,17 +27,19 @@ bool addRemovePt = false;
static void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
{
if( event == CV_EVENT_LBUTTONDOWN )
if( event == EVENT_LBUTTONDOWN )
{
point = Point2f((float)x,(float)y);
point = Point2f((float)x, (float)y);
addRemovePt = true;
}
}
int main( int argc, char** argv )
{
help();
VideoCapture cap;
TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
TermCriteria termcrit(TermCriteria::COUNT|TermCriteria::EPS,20,0.03);
Size subPixWinSize(10,10), winSize(31,31);
const int MAX_COUNT = 500;
@@ -56,8 +57,6 @@ int main( int argc, char** argv )
return 0;
}
help();
namedWindow( "LK Demo", 1 );
setMouseCallback( "LK Demo", onMouse, 0 );
@@ -72,7 +71,7 @@ int main( int argc, char** argv )
break;
frame.copyTo(image);
cvtColor(image, gray, CV_BGR2GRAY);
cvtColor(image, gray, COLOR_BGR2GRAY);
if( nightMode )
image = Scalar::all(0);
@@ -117,7 +116,7 @@ int main( int argc, char** argv )
{
vector<Point2f> tmp;
tmp.push_back(point);
cornerSubPix( gray, tmp, winSize, cvSize(-1,-1), termcrit);
cornerSubPix( gray, tmp, winSize, Size(-1,-1), termcrit);
points[1].push_back(tmp[0]);
addRemovePt = false;
}
@@ -134,17 +133,16 @@ int main( int argc, char** argv )
needToInit = true;
break;
case 'c':
points[0].clear();
points[1].clear();
break;
case 'n':
nightMode = !nightMode;
break;
default:
;
}
std::swap(points[1], points[0]);
swap(prevGray, gray);
cv::swap(prevGray, gray);
}
return 0;

View File

@@ -6,7 +6,9 @@
* PSPC-lab - University of Genoa
*/
#include "opencv2/opencv.hpp"
#include "opencv2/contrib.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <cmath>

View File

@@ -4,6 +4,7 @@
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/nonfree.hpp"
using namespace std;
using namespace cv;
static void help()
@@ -22,8 +23,8 @@ int main(int argc, char** argv)
return -1;
}
Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
Mat img1 = imread(argv[1], IMREAD_GRAYSCALE);
Mat img2 = imread(argv[2], IMREAD_GRAYSCALE);
if(img1.empty() || img2.empty())
{
printf("Can't read one of the images\n");

View File

@@ -57,7 +57,7 @@ static void readTrainFilenames( const string& filename, string& dirName, vector<
size_t pos = filename.rfind('\\');
char dlmtr = '\\';
if (pos == String::npos)
if (pos == string::npos)
{
pos = filename.rfind('/');
dlmtr = '/';
@@ -95,7 +95,7 @@ static bool readImages( const string& queryImageName, const string& trainFilenam
Mat& queryImage, vector <Mat>& trainImages, vector<string>& trainImageNames )
{
cout << "< Reading the images..." << endl;
queryImage = imread( queryImageName, CV_LOAD_IMAGE_GRAYSCALE);
queryImage = imread( queryImageName, IMREAD_GRAYSCALE);
if( queryImage.empty() )
{
cout << "Query image can not be read." << endl << ">" << endl;
@@ -112,7 +112,7 @@ static bool readImages( const string& queryImageName, const string& trainFilenam
for( size_t i = 0; i < trainImageNames.size(); i++ )
{
string filename = trainDirName + trainImageNames[i];
Mat img = imread( filename, CV_LOAD_IMAGE_GRAYSCALE );
Mat img = imread( filename, IMREAD_GRAYSCALE );
if( img.empty() )
cout << "Train image " << filename << " can not be read." << endl;
else

View File

@@ -65,7 +65,7 @@ int main(int argc, char** argv)
colorRad = 10;
maxPyrLevel = 1;
namedWindow( winName, CV_WINDOW_AUTOSIZE );
namedWindow( winName, WINDOW_AUTOSIZE );
createTrackbar( "spatialRad", winName, &spatialRad, 80, meanShiftSegmentation );
createTrackbar( "colorRad", winName, &colorRad, 60, meanShiftSegmentation );

View File

@@ -13,7 +13,7 @@ static void help()
"Random points are generated and then enclosed.\n"
"Call:\n"
"./minarea\n"
"Using OpenCV version %s\n" << CV_VERSION << "\n" << endl;
"Using OpenCV v" << CV_VERSION << "\n" << endl;
}
int main( int /*argc*/, char** /*argv*/ )
@@ -45,16 +45,16 @@ int main( int /*argc*/, char** /*argv*/ )
img = Scalar::all(0);
for( i = 0; i < count; i++ )
circle( img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA );
circle( img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA );
for( i = 0; i < 4; i++ )
line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, CV_AA);
line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, LINE_AA);
circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, CV_AA);
circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, LINE_AA);
imshow( "rect & circle", img );
char key = (char)cvWaitKey();
char key = (char)waitKey();
if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
break;
}

View File

@@ -1,5 +1,3 @@
#define CV_NO_BACKWARD_COMPATIBILITY
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
@@ -37,9 +35,9 @@ static void OpenClose(int, void*)
int an = n > 0 ? n : -n;
Mat element = getStructuringElement(element_shape, Size(an*2+1, an*2+1), Point(an, an) );
if( n < 0 )
morphologyEx(src, dst, CV_MOP_OPEN, element);
morphologyEx(src, dst, MORPH_OPEN, element);
else
morphologyEx(src, dst, CV_MOP_CLOSE, element);
morphologyEx(src, dst, MORPH_CLOSE, element);
imshow("Open/Close",dst);
}
@@ -79,7 +77,7 @@ int main( int argc, char** argv )
OpenClose(open_close_pos, 0);
ErodeDilate(erode_dilate_pos, 0);
c = cvWaitKey(0);
c = waitKey();
if( (char)c == 27 )
break;

View File

@@ -1,4 +1,4 @@
#include "opencv2/core/core.hpp"
#include <opencv2/core/utility.hpp>
#include <iostream>
const char* keys =

View File

@@ -12,14 +12,14 @@ static void help()
"The user gets some of the supported output images.\n"
"\nAll supported output map types:\n"
"1.) Data given from depth generator\n"
" OPENNI_DEPTH_MAP - depth values in mm (CV_16UC1)\n"
" OPENNI_POINT_CLOUD_MAP - XYZ in meters (CV_32FC3)\n"
" OPENNI_DISPARITY_MAP - disparity in pixels (CV_8UC1)\n"
" OPENNI_DISPARITY_MAP_32F - disparity in pixels (CV_32FC1)\n"
" OPENNI_VALID_DEPTH_MASK - mask of valid pixels (not ocluded, not shaded etc.) (CV_8UC1)\n"
" CV_CAP_OPENNI_DEPTH_MAP - depth values in mm (CV_16UC1)\n"
" CV_CAP_OPENNI_POINT_CLOUD_MAP - XYZ in meters (CV_32FC3)\n"
" CV_CAP_OPENNI_DISPARITY_MAP - disparity in pixels (CV_8UC1)\n"
" CV_CAP_OPENNI_DISPARITY_MAP_32F - disparity in pixels (CV_32FC1)\n"
" CV_CAP_OPENNI_VALID_DEPTH_MASK - mask of valid pixels (not ocluded, not shaded etc.) (CV_8UC1)\n"
"2.) Data given from RGB image generator\n"
" OPENNI_BGR_IMAGE - color image (CV_8UC3)\n"
" OPENNI_GRAY_IMAGE - gray image (CV_8UC1)\n"
" CV_CAP_OPENNI_BGR_IMAGE - color image (CV_8UC3)\n"
" CV_CAP_OPENNI_GRAY_IMAGE - gray image (CV_8UC1)\n"
<< endl;
}
@@ -79,8 +79,8 @@ static void colorizeDisparity( const Mat& gray, Mat& rgb, double maxDisp=-1.f, f
static float getMaxDisparity( VideoCapture& capture )
{
const int minDistance = 400; // mm
float b = (float)capture.get( CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE ); // mm
float F = (float)capture.get( CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH ); // pixels
float b = (float)capture.get( CAP_OPENNI_DEPTH_GENERATOR_BASELINE ); // mm
float F = (float)capture.get( CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH ); // pixels
return b * F / minDistance;
}
@@ -142,7 +142,7 @@ static void parseCommandLine( int argc, char* argv[], bool& isColorizeDisp, bool
{
string mask( argv[++i] );
if( mask.size() != 5)
CV_Error( CV_StsBadArg, "Incorrect length of -m argument string" );
CV_Error( Error::StsBadArg, "Incorrect length of -m argument string" );
int val = atoi(mask.c_str());
int l = 100000, r = 10000, sum = 0;
@@ -191,7 +191,7 @@ int main( int argc, char* argv[] )
if( isVideoReading )
capture.open( filename );
else
capture.open( CV_CAP_OPENNI );
capture.open( CAP_OPENNI );
cout << "done." << endl;
@@ -207,23 +207,23 @@ int main( int argc, char* argv[] )
switch ( imageMode )
{
case 0:
modeRes = capture.set( CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CV_CAP_OPENNI_VGA_30HZ );
modeRes = capture.set( CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CAP_OPENNI_VGA_30HZ );
break;
case 1:
modeRes = capture.set( CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CV_CAP_OPENNI_SXGA_15HZ );
modeRes = capture.set( CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CAP_OPENNI_SXGA_15HZ );
break;
case 2:
modeRes = capture.set( CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CV_CAP_OPENNI_SXGA_30HZ );
modeRes = capture.set( CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CAP_OPENNI_SXGA_30HZ );
break;
//The following modes are only supported by the Xtion Pro Live
case 3:
modeRes = capture.set( CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CV_CAP_OPENNI_QVGA_30HZ );
modeRes = capture.set( CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CAP_OPENNI_QVGA_30HZ );
break;
case 4:
modeRes = capture.set( CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CV_CAP_OPENNI_QVGA_60HZ );
modeRes = capture.set( CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CAP_OPENNI_QVGA_60HZ );
break;
default:
CV_Error( CV_StsBadArg, "Unsupported image mode property.\n");
CV_Error( Error::StsBadArg, "Unsupported image mode property.\n");
}
if (!modeRes)
cout << "\nThis image mode is not supported by the device, the default value (CV_CAP_OPENNI_SXGA_15HZ) will be used.\n" << endl;
@@ -231,18 +231,18 @@ int main( int argc, char* argv[] )
// Print some avalible device settings.
cout << "\nDepth generator output mode:" << endl <<
"FRAME_WIDTH " << capture.get( CV_CAP_PROP_FRAME_WIDTH ) << endl <<
"FRAME_HEIGHT " << capture.get( CV_CAP_PROP_FRAME_HEIGHT ) << endl <<
"FRAME_MAX_DEPTH " << capture.get( CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH ) << " mm" << endl <<
"FPS " << capture.get( CV_CAP_PROP_FPS ) << endl <<
"REGISTRATION " << capture.get( CV_CAP_PROP_OPENNI_REGISTRATION ) << endl;
if( capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT ) )
"FRAME_WIDTH " << capture.get( CAP_PROP_FRAME_WIDTH ) << endl <<
"FRAME_HEIGHT " << capture.get( CAP_PROP_FRAME_HEIGHT ) << endl <<
"FRAME_MAX_DEPTH " << capture.get( CAP_PROP_OPENNI_FRAME_MAX_DEPTH ) << " mm" << endl <<
"FPS " << capture.get( CAP_PROP_FPS ) << endl <<
"REGISTRATION " << capture.get( CAP_PROP_OPENNI_REGISTRATION ) << endl;
if( capture.get( CAP_OPENNI_IMAGE_GENERATOR_PRESENT ) )
{
cout <<
"\nImage generator output mode:" << endl <<
"FRAME_WIDTH " << capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR+CV_CAP_PROP_FRAME_WIDTH ) << endl <<
"FRAME_HEIGHT " << capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR+CV_CAP_PROP_FRAME_HEIGHT ) << endl <<
"FPS " << capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR+CV_CAP_PROP_FPS ) << endl;
"FRAME_WIDTH " << capture.get( CAP_OPENNI_IMAGE_GENERATOR+CAP_PROP_FRAME_WIDTH ) << endl <<
"FRAME_HEIGHT " << capture.get( CAP_OPENNI_IMAGE_GENERATOR+CAP_PROP_FRAME_HEIGHT ) << endl <<
"FPS " << capture.get( CAP_OPENNI_IMAGE_GENERATOR+CAP_PROP_FPS ) << endl;
}
else
{
@@ -266,14 +266,14 @@ int main( int argc, char* argv[] )
}
else
{
if( retrievedImageFlags[0] && capture.retrieve( depthMap, CV_CAP_OPENNI_DEPTH_MAP ) )
if( retrievedImageFlags[0] && capture.retrieve( depthMap, CAP_OPENNI_DEPTH_MAP ) )
{
const float scaleFactor = 0.05f;
Mat show; depthMap.convertTo( show, CV_8UC1, scaleFactor );
imshow( "depth map", show );
}
if( retrievedImageFlags[1] && capture.retrieve( disparityMap, CV_CAP_OPENNI_DISPARITY_MAP ) )
if( retrievedImageFlags[1] && capture.retrieve( disparityMap, CAP_OPENNI_DISPARITY_MAP ) )
{
if( isColorizeDisp )
{
@@ -289,13 +289,13 @@ int main( int argc, char* argv[] )
}
}
if( retrievedImageFlags[2] && capture.retrieve( validDepthMap, CV_CAP_OPENNI_VALID_DEPTH_MASK ) )
if( retrievedImageFlags[2] && capture.retrieve( validDepthMap, CAP_OPENNI_VALID_DEPTH_MASK ) )
imshow( "valid depth mask", validDepthMap );
if( retrievedImageFlags[3] && capture.retrieve( bgrImage, CV_CAP_OPENNI_BGR_IMAGE ) )
if( retrievedImageFlags[3] && capture.retrieve( bgrImage, CAP_OPENNI_BGR_IMAGE ) )
imshow( "rgb image", bgrImage );
if( retrievedImageFlags[4] && capture.retrieve( grayImage, CV_CAP_OPENNI_GRAY_IMAGE ) )
if( retrievedImageFlags[4] && capture.retrieve( grayImage, CAP_OPENNI_GRAY_IMAGE ) )
imshow( "gray image", grayImage );
}

View File

@@ -54,7 +54,7 @@ static void read_imgList(const string& filename, vector<Mat>& images) {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
CV_Error(Error::StsBadArg, error_message);
}
string line;
while (getline(file, line)) {
@@ -64,7 +64,7 @@ static void read_imgList(const string& filename, vector<Mat>& images) {
static Mat formatImagesForPCA(const vector<Mat> &data)
{
Mat dst(data.size(), data[0].rows*data[0].cols, CV_32F);
Mat dst(static_cast<int>(data.size()), data[0].rows*data[0].cols, CV_32F);
for(unsigned int i = 0; i < data.size(); i++)
{
Mat image_row = data[i].clone().reshape(1,1);
@@ -78,7 +78,7 @@ static Mat toGrayscale(InputArray _src) {
Mat src = _src.getMat();
// only allow one channel
if(src.channels() != 1) {
CV_Error(CV_StsBadArg, "Only Matrices with one channel are supported");
CV_Error(Error::StsBadArg, "Only Matrices with one channel are supported");
}
// create and return normalized image
Mat dst;
@@ -104,7 +104,7 @@ static void onTrackbar(int pos, void* ptr)
struct params *p = (struct params *)ptr;
p->pca = PCA(p->data, cv::Mat(), CV_PCA_DATA_AS_ROW, var);
p->pca = PCA(p->data, cv::Mat(), PCA::DATA_AS_ROW, var);
Mat point = p->pca.project(p->data.row(0));
Mat reconstruction = p->pca.backProject(point);
@@ -142,14 +142,14 @@ int main(int argc, char** argv)
// Quit if there are not enough images for this demo.
if(images.size() <= 1) {
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(CV_StsError, error_message);
CV_Error(Error::StsError, error_message);
}
// Reshape and stack images into a rowMatrix
Mat data = formatImagesForPCA(images);
// perform PCA
PCA pca(data, cv::Mat(), CV_PCA_DATA_AS_ROW, 0.95); // trackbar is initially set here, also this is a common value for retainedVariance
PCA pca(data, cv::Mat(), PCA::DATA_AS_ROW, 0.95); // trackbar is initially set here, also this is a common value for retainedVariance
// Demonstration of the effect of retainedVariance on the first image
Mat point = pca.project(data.row(0)); // project into the eigenspace, thus the image becomes a "point"
@@ -159,7 +159,7 @@ int main(int argc, char** argv)
// init highgui window
string winName = "Reconstruction | press 'q' to quit";
namedWindow(winName, CV_WINDOW_NORMAL);
namedWindow(winName, WINDOW_NORMAL);
// params struct to pass to the trackbar handler
params p;

View File

@@ -1,111 +1,180 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/softcascade.hpp>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace cv;
using namespace std;
// static void help()
// {
// printf(
// "\nDemonstrate the use of the HoG descriptor using\n"
// " HOGDescriptor::hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());\n"
// "Usage:\n"
// "./peopledetect (<image_filename> | <image_list>.txt)\n\n");
// }
void filter_rects(const std::vector<cv::Rect>& candidates, std::vector<cv::Rect>& objects);
int main(int argc, char** argv)
{
Mat img;
FILE* f = 0;
char _filename[1024];
const std::string keys =
"{help h usage ? | | print this message and exit }"
"{cascade c | | path to cascade xml, if empty HOG detector will be executed }"
"{frame f | | wildchart pattern to frame source}"
"{min_scale |0.4 | minimum scale to detect }"
"{max_scale |5.0 | maxamum scale to detect }"
"{total_scales |55 | prefered number of scales between min and max }"
"{write_file wf |0 | write to .txt. Disabled by default.}"
"{write_image wi |0 | write to image. Disabled by default.}"
"{show_image si |1 | show image. Enabled by default.}"
"{threshold thr |-1 | detection threshold. Detections with score less then threshold will be ignored.}"
;
if( argc == 1 )
cv::CommandLineParser parser(argc, argv, keys);
parser.about("Soft cascade training application.");
if (parser.has("help"))
{
printf("Usage: peopledetect (<image_filename> | <image_list>.txt)\n");
parser.printMessage();
return 0;
}
img = imread(argv[1]);
if( img.data )
if (!parser.check())
{
strcpy(_filename, argv[1]);
parser.printErrors();
return 1;
}
int wf = parser.get<int>("write_file");
if (wf) std::cout << "resulte will be stored to .txt file with the same name as image." << std::endl;
int wi = parser.get<int>("write_image");
if (wi) std::cout << "resulte will be stored to image with the same name as input plus dt." << std::endl;
int si = parser.get<int>("show_image");
float minScale = parser.get<float>("min_scale");
float maxScale = parser.get<float>("max_scale");
int scales = parser.get<int>("total_scales");
int thr = parser.get<int>("threshold");
cv::HOGDescriptor hog;
cv::softcascade::Detector cascade;
bool useHOG = false;
std::string cascadePath = parser.get<std::string>("cascade");
if (cascadePath.empty())
{
useHOG = true;
hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector());
std::cout << "going to use HOG detector." << std::endl;
}
else
{
f = fopen(argv[1], "rt");
if(!f)
cv::FileStorage fs(cascadePath, cv::FileStorage::READ);
if( !fs.isOpened())
{
fprintf( stderr, "ERROR: the specified file could not be loaded\n");
return -1;
std::cout << "Soft Cascade file " << cascadePath << " can't be opened." << std::endl << std::flush;
return 1;
}
cascade = cv::softcascade::Detector(minScale, maxScale, scales, cv::softcascade::Detector::DOLLAR);
if (!cascade.load(fs.getFirstTopLevelNode()))
{
std::cout << "Soft Cascade can't be parsed." << std::endl << std::flush;
return 1;
}
}
HOGDescriptor hog;
hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
namedWindow("people detector", 1);
std::string src = parser.get<std::string>("frame");
std::vector<cv::String> frames;
cv::glob(parser.get<std::string>("frame"), frames);
std::cout << "collected " << src << " " << frames.size() << " frames." << std::endl;
for(;;)
for (int i = 0; i < (int)frames.size(); ++i)
{
char* filename = _filename;
if(f)
{
if(!fgets(filename, (int)sizeof(_filename)-2, f))
break;
//while(*filename && isspace(*filename))
// ++filename;
if(filename[0] == '#')
continue;
int l = (int)strlen(filename);
while(l > 0 && isspace(filename[l-1]))
--l;
filename[l] = '\0';
img = imread(filename);
}
printf("%s:\n", filename);
if(!img.data)
continue;
std::string frame_sourse = frames[i];
cv::Mat frame = cv::imread(frame_sourse);
fflush(stdout);
vector<Rect> found, found_filtered;
double t = (double)getTickCount();
// run the detector with default parameters. to get a higher hit-rate
// (and more false alarms, respectively), decrease the hitThreshold and
// groupThreshold (set groupThreshold to 0 to turn off the grouping completely).
hog.detectMultiScale(img, found, 0, Size(8,8), Size(32,32), 1.05, 2);
t = (double)getTickCount() - t;
printf("tdetection time = %gms\n", t*1000./cv::getTickFrequency());
size_t i, j;
for( i = 0; i < found.size(); i++ )
if(frame.empty())
{
Rect r = found[i];
for( j = 0; j < found.size(); j++ )
if( j != i && (r & found[j]) == r)
break;
if( j == found.size() )
found_filtered.push_back(r);
std::cout << "Frame source " << frame_sourse << " can't be opened." << std::endl << std::flush;
continue;
}
for( i = 0; i < found_filtered.size(); i++ )
std::ofstream myfile;
if (wf)
myfile.open((frame_sourse.replace(frame_sourse.end() - 3, frame_sourse.end(), "txt")).c_str(), std::ios::out);
////
if (useHOG)
{
Rect r = found_filtered[i];
// the HOG detector returns slightly larger rectangles than the real objects.
// so we slightly shrink the rectangles to get a nicer output.
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), cv::Scalar(0,255,0), 3);
std::vector<cv::Rect> found, found_filtered;
// run the detector with default parameters. to get a higher hit-rate
// (and more false alarms, respectively), decrease the hitThreshold and
// groupThreshold (set groupThreshold to 0 to turn off the grouping completely).
hog.detectMultiScale(frame, found, 0, cv::Size(8,8), cv::Size(32,32), 1.05, 2);
filter_rects(found, found_filtered);
std::cout << "collected: " << (int)found_filtered.size() << " detections." << std::endl;
for (size_t ff = 0; ff < found_filtered.size(); ++ff)
{
cv::Rect r = found_filtered[ff];
cv::rectangle(frame, r.tl(), r.br(), cv::Scalar(0,255,0), 3);
if (wf) myfile << r.x << "," << r.y << "," << r.width << "," << r.height << "," << 0.f << "\n";
}
}
else
{
std::vector<cv::softcascade::Detection> objects;
cascade.detect(frame, cv::noArray(), objects);
std::cout << "collected: " << (int)objects.size() << " detections." << std::endl;
for (int obj = 0; obj < (int)objects.size(); ++obj)
{
cv::softcascade::Detection d = objects[obj];
if(d.confidence > thr)
{
float b = d.confidence * 1.5f;
std::stringstream conf(std::stringstream::in | std::stringstream::out);
conf << d.confidence;
cv::rectangle(frame, cv::Rect((int)d.x, (int)d.y, (int)d.w, (int)d.h), cv::Scalar(b, 0, 255 - b, 255), 2);
cv::putText(frame, conf.str() , cv::Point((int)d.x + 10, (int)d.y - 5),1, 1.1, cv::Scalar(25, 133, 255, 0), 1, cv::LINE_AA);
if (wf)
myfile << d.x << "," << d.y << "," << d.w << "," << d.h << "," << d.confidence << "\n";
}
}
}
if (wi) cv::imwrite(frame_sourse + ".dt.png", frame);
if (wf) myfile.close();
if (si)
{
cv::imshow("pedestrian detector", frame);
cv::waitKey(10);
}
imshow("people detector", img);
int c = waitKey(0) & 255;
if( c == 'q' || c == 'Q' || !f)
break;
}
if(f)
fclose(f);
if (si) cv::waitKey(0);
return 0;
}
void filter_rects(const std::vector<cv::Rect>& candidates, std::vector<cv::Rect>& objects)
{
size_t i, j;
for (i = 0; i < candidates.size(); ++i)
{
cv::Rect r = candidates[i];
for (j = 0; j < candidates.size(); ++j)
if (j != i && (r & candidates[j]) == r)
break;
if (j == candidates.size())
objects.push_back(r);
}
}

View File

@@ -13,7 +13,7 @@ int main(int, char* [])
do
{
video >> frame;
cvtColor(frame, curr, CV_RGB2GRAY);
cvtColor(frame, curr, COLOR_RGB2GRAY);
if(prev.empty())
{
@@ -25,14 +25,14 @@ int main(int, char* [])
curr.convertTo(curr64f, CV_64F);
Point2d shift = phaseCorrelate(prev64f, curr64f, hann);
double radius = cv::sqrt(shift.x*shift.x + shift.y*shift.y);
double radius = std::sqrt(shift.x*shift.x + shift.y*shift.y);
if(radius > 5)
{
// draw a circle and line indicating the shift direction...
Point center(curr.cols >> 1, curr.rows >> 1);
cv::circle(frame, center, (int)radius, cv::Scalar(0, 255, 0), 3, CV_AA);
cv::line(frame, center, Point(center.x + (int)shift.x, center.y + (int)shift.y), cv::Scalar(0, 255, 0), 3, CV_AA);
circle(frame, center, (int)radius, Scalar(0, 255, 0), 3, LINE_AA);
line(frame, center, Point(center.x + (int)shift.x, center.y + (int)shift.y), Scalar(0, 255, 0), 3, LINE_AA);
}
imshow("phase shift", frame);

View File

@@ -1,357 +0,0 @@
#include <cstring>
#include <cmath>
#include <iostream>
#include <sstream>
#include "opencv2/core/core.hpp"
#include "opencv2/core/opengl_interop.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/contrib/contrib.hpp"
using namespace std;
using namespace cv;
using namespace cv::gpu;
class PointCloudRenderer
{
public:
PointCloudRenderer(const Mat& points, const Mat& img, double scale);
void onMouseEvent(int event, int x, int y, int flags);
void draw();
void update(int key, double aspect);
int fov_;
private:
int mouse_dx_;
int mouse_dy_;
double yaw_;
double pitch_;
Point3d pos_;
TickMeter tm_;
static const int step_;
int frame_;
GlCamera camera_;
GlArrays pointCloud_;
string fps_;
};
bool stop = false;
static void mouseCallback(int event, int x, int y, int flags, void* userdata)
{
if (stop)
return;
PointCloudRenderer* renderer = static_cast<PointCloudRenderer*>(userdata);
renderer->onMouseEvent(event, x, y, flags);
}
static void openGlDrawCallback(void* userdata)
{
if (stop)
return;
PointCloudRenderer* renderer = static_cast<PointCloudRenderer*>(userdata);
renderer->draw();
}
int main(int argc, const char* argv[])
{
const char* keys =
"{ l left | | left image file name }"
"{ r right | | right image file name }"
"{ i intrinsic | | intrinsic camera parameters file name }"
"{ e extrinsic | | extrinsic camera parameters file name }"
"{ d ndisp | 256 | number of disparities }"
"{ s scale | 1.0 | scale factor for point cloud }"
"{ h help | | print help message }";
CommandLineParser cmd(argc, argv, keys);
if (cmd.has("help"))
{
cmd.printMessage();
return 0;
}
string left = cmd.get<string>("left");
string right = cmd.get<string>("right");
string intrinsic = cmd.get<string>("intrinsic");
string extrinsic = cmd.get<string>("extrinsic");
int ndisp = cmd.get<int>("ndisp");
double scale = cmd.get<double>("scale");
if (!cmd.check())
{
cmd.printErrors();
return 0;
}
if (left.empty() || right.empty())
{
cout << "Missed input images" << endl;
cout << "Avaible options:" << endl;
cmd.printMessage();
return 0;
}
if (intrinsic.empty() ^ extrinsic.empty())
{
cout << "Boss camera parameters must be specified" << endl;
cout << "Avaible options:" << endl;
cmd.printMessage();
return 0;
}
Mat imgLeftColor = imread(left, IMREAD_COLOR);
Mat imgRightColor = imread(right, IMREAD_COLOR);
if (imgLeftColor.empty())
{
cout << "Can't load image " << left << endl;
return -1;
}
if (imgRightColor.empty())
{
cout << "Can't load image " << right << endl;
return -1;
}
Mat Q = Mat::eye(4, 4, CV_32F);
if (!intrinsic.empty() && !extrinsic.empty())
{
FileStorage fs;
// reading intrinsic parameters
fs.open(intrinsic, CV_STORAGE_READ);
if (!fs.isOpened())
{
cout << "Failed to open file " << intrinsic << endl;
return -1;
}
Mat M1, D1, M2, D2;
fs["M1"] >> M1;
fs["D1"] >> D1;
fs["M2"] >> M2;
fs["D2"] >> D2;
// reading extrinsic parameters
fs.open(extrinsic, CV_STORAGE_READ);
if (!fs.isOpened())
{
cout << "Failed to open file " << extrinsic << endl;
return -1;
}
Mat R, T, R1, P1, R2, P2;
fs["R"] >> R;
fs["T"] >> T;
Size img_size = imgLeftColor.size();
Rect roi1, roi2;
stereoRectify(M1, D1, M2, D2, img_size, R, T, R1, R2, P1, P2, Q, CALIB_ZERO_DISPARITY, -1, img_size, &roi1, &roi2);
Mat map11, map12, map21, map22;
initUndistortRectifyMap(M1, D1, R1, P1, img_size, CV_16SC2, map11, map12);
initUndistortRectifyMap(M2, D2, R2, P2, img_size, CV_16SC2, map21, map22);
Mat img1r, img2r;
remap(imgLeftColor, img1r, map11, map12, INTER_LINEAR);
remap(imgRightColor, img2r, map21, map22, INTER_LINEAR);
imgLeftColor = img1r(roi1);
imgRightColor = img2r(roi2);
}
Mat imgLeftGray, imgRightGray;
cvtColor(imgLeftColor, imgLeftGray, COLOR_BGR2GRAY);
cvtColor(imgRightColor, imgRightGray, COLOR_BGR2GRAY);
cvtColor(imgLeftColor, imgLeftColor, COLOR_BGR2RGB);
Mat disp, points;
StereoBM bm(0, ndisp);
bm(imgLeftGray, imgRightGray, disp);
disp.convertTo(disp, CV_8U, 1.0 / 16.0);
disp = disp(Range(21, disp.rows - 21), Range(ndisp, disp.cols - 21)).clone();
imgLeftColor = imgLeftColor(Range(21, imgLeftColor.rows - 21), Range(ndisp, imgLeftColor.cols - 21)).clone();
reprojectImageTo3D(disp, points, Q);
const string windowName = "OpenGL Sample";
namedWindow(windowName, WINDOW_OPENGL);
resizeWindow(windowName, 400, 400);
PointCloudRenderer renderer(points, imgLeftColor, scale);
createTrackbar("Fov", windowName, &renderer.fov_, 100);
setMouseCallback(windowName, mouseCallback, &renderer);
setOpenGlDrawCallback(windowName, openGlDrawCallback, &renderer);
for(;;)
{
int key = waitKey(10);
if (key >= 0)
key = key & 0xff;
if (key == 27)
{
stop = true;
break;
}
double aspect = getWindowProperty(windowName, WND_PROP_ASPECT_RATIO);
key = tolower(key);
renderer.update(key, aspect);
updateWindow(windowName);
}
return 0;
}
const int PointCloudRenderer::step_ = 20;
PointCloudRenderer::PointCloudRenderer(const Mat& points, const Mat& img, double scale)
{
mouse_dx_ = 0;
mouse_dy_ = 0;
fov_ = 0;
yaw_ = 0.0;
pitch_ = 0.0;
frame_ = 0;
camera_.setScale(Point3d(scale, scale, scale));
pointCloud_.setVertexArray(points);
pointCloud_.setColorArray(img, false);
tm_.start();
}
inline int clamp(int val, int minVal, int maxVal)
{
return max(min(val, maxVal), minVal);
}
void PointCloudRenderer::onMouseEvent(int event, int x, int y, int /*flags*/)
{
static int oldx = x;
static int oldy = y;
static bool moving = false;
if (event == EVENT_LBUTTONDOWN)
{
oldx = x;
oldy = y;
moving = true;
}
else if (event == EVENT_LBUTTONUP)
{
moving = false;
}
if (moving)
{
mouse_dx_ = oldx - x;
mouse_dy_ = oldy - y;
}
else
{
mouse_dx_ = 0;
mouse_dy_ = 0;
}
const int mouseClamp = 300;
mouse_dx_ = clamp(mouse_dx_, -mouseClamp, mouseClamp);
mouse_dy_ = clamp(mouse_dy_, -mouseClamp, mouseClamp);
}
static Point3d rotate(Point3d v, double yaw, double pitch)
{
Point3d t1;
t1.x = v.x * cos(-yaw / 180.0 * CV_PI) - v.z * sin(-yaw / 180.0 * CV_PI);
t1.y = v.y;
t1.z = v.x * sin(-yaw / 180.0 * CV_PI) + v.z * cos(-yaw / 180.0 * CV_PI);
Point3d t2;
t2.x = t1.x;
t2.y = t1.y * cos(pitch / 180.0 * CV_PI) - t1.z * sin(pitch / 180.0 * CV_PI);
t2.z = t1.y * sin(pitch / 180.0 * CV_PI) + t1.z * cos(pitch / 180.0 * CV_PI);
return t2;
}
void PointCloudRenderer::update(int key, double aspect)
{
const Point3d dirVec(0.0, 0.0, -1.0);
const Point3d upVec(0.0, 1.0, 0.0);
const Point3d leftVec(-1.0, 0.0, 0.0);
const double posStep = 0.1;
const double mouseStep = 0.001;
camera_.setPerspectiveProjection(30.0 + fov_ / 100.0 * 40.0, aspect, 0.1, 1000.0);
yaw_ += mouse_dx_ * mouseStep;
pitch_ += mouse_dy_ * mouseStep;
if (key == 'w')
pos_ += posStep * rotate(dirVec, yaw_, pitch_);
else if (key == 's')
pos_ -= posStep * rotate(dirVec, yaw_, pitch_);
else if (key == 'a')
pos_ += posStep * rotate(leftVec, yaw_, pitch_);
else if (key == 'd')
pos_ -= posStep * rotate(leftVec, yaw_, pitch_);
else if (key == 'q')
pos_ += posStep * rotate(upVec, yaw_, pitch_);
else if (key == 'e')
pos_ -= posStep * rotate(upVec, yaw_, pitch_);
camera_.setCameraPos(pos_, yaw_, pitch_, 0.0);
tm_.stop();
if (frame_++ >= step_)
{
ostringstream ostr;
ostr << "FPS: " << step_ / tm_.getTimeSec();
fps_ = ostr.str();
frame_ = 0;
tm_.reset();
}
tm_.start();
}
void PointCloudRenderer::draw()
{
camera_.setupProjectionMatrix();
camera_.setupModelViewMatrix();
render(pointCloud_);
render(fps_, GlFont::get("Courier New", 16), Scalar::all(255), Point2d(3.0, 0.0));
}

View File

@@ -36,7 +36,7 @@ static void on_mouse( int event, int x, int y, int /*flags*/, void* )
int updateFlag = 0;
if( event == CV_EVENT_LBUTTONUP )
if( event == EVENT_LBUTTONUP )
{
if( classColors.empty() )
return;
@@ -45,7 +45,7 @@ static void on_mouse( int event, int x, int y, int /*flags*/, void* )
trainedPointsMarkers.push_back( (int)(classColors.size()-1) );
updateFlag = true;
}
else if( event == CV_EVENT_RBUTTONUP )
else if( event == EVENT_RBUTTONUP )
{
#if _BT_
if( classColors.size() < 2 )
@@ -503,7 +503,7 @@ int main()
imgDst.create( 480, 640, CV_8UC3 );
imshow( "points", img );
cvSetMouseCallback( "points", on_mouse );
setMouseCallback( "points", on_mouse );
for(;;)
{

View File

@@ -9,7 +9,8 @@
#include <iostream>
#include <cstring>
#include "opencv2/opencv.hpp"
#include "opencv2/contrib.hpp"
#include "opencv2/highgui.hpp"
static void help(std::string errorMessage)
{

View File

@@ -125,8 +125,8 @@ int main(int argc, char** argv)
}
Mat grayImage0, grayImage1, depthFlt0, depthFlt1/*in meters*/;
cvtColor( colorImage0, grayImage0, CV_BGR2GRAY );
cvtColor( colorImage1, grayImage1, CV_BGR2GRAY );
cvtColor( colorImage0, grayImage0, COLOR_BGR2GRAY );
cvtColor( colorImage1, grayImage1, COLOR_BGR2GRAY );
depth0.convertTo( depthFlt0, CV_32FC1, 1./1000 );
depth1.convertTo( depthFlt1, CV_32FC1, 1./1000 );

View File

@@ -4,6 +4,7 @@
#include <stdio.h>
#include <string>
using namespace std;
using namespace cv;
static void help()
@@ -29,7 +30,7 @@ static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
erode(temp, temp, Mat(), Point(-1,-1), niters*2);
dilate(temp, temp, Mat(), Point(-1,-1), niters);
findContours( temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
findContours( temp, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE );
dst = Mat::zeros(img.size(), CV_8UC3);
@@ -52,7 +53,7 @@ static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
}
}
Scalar color( 0, 0, 255 );
drawContours( dst, contours, largestComp, color, CV_FILLED, 8, hierarchy );
drawContours( dst, contours, largestComp, color, FILLED, LINE_8, hierarchy );
}
@@ -86,15 +87,15 @@ int main(int argc, char** argv)
namedWindow("video", 1);
namedWindow("segmented", 1);
BackgroundSubtractorMOG bgsubtractor;
bgsubtractor.set("noiseSigma", 10);
Ptr<BackgroundSubtractorMOG> bgsubtractor=createBackgroundSubtractorMOG();
bgsubtractor->setNoiseSigma(10);
for(;;)
{
cap >> tmp_frame;
if( !tmp_frame.data )
break;
bgsubtractor(tmp_frame, bgmask, update_bg_model ? -1 : 0);
bgsubtractor->apply(tmp_frame, bgmask, update_bg_model ? -1 : 0);
//CvMat _bgmask = bgmask;
//cvSegmentFGMask(&_bgmask);
refineSegments(tmp_frame, bgmask, out_frame);

View File

@@ -8,15 +8,17 @@
*
*/
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/highgui.hpp"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
using namespace cv;
const char* helphelp =
@@ -146,25 +148,25 @@ static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFram
if( shownFrame.data )
{
if( nobjpt == 1 )
circle(shownFrame, imgpt[0], 3, Scalar(0,255,0), -1, CV_AA);
circle(shownFrame, imgpt[0], 3, Scalar(0,255,0), -1, LINE_AA);
else if( nobjpt == 2 )
{
circle(shownFrame, imgpt[0], 3, Scalar(0,255,0), -1, CV_AA);
circle(shownFrame, imgpt[1], 3, Scalar(0,255,0), -1, CV_AA);
line(shownFrame, imgpt[0], imgpt[1], Scalar(0,255,0), 3, CV_AA);
circle(shownFrame, imgpt[0], 3, Scalar(0,255,0), -1, LINE_AA);
circle(shownFrame, imgpt[1], 3, Scalar(0,255,0), -1, LINE_AA);
line(shownFrame, imgpt[0], imgpt[1], Scalar(0,255,0), 3, LINE_AA);
}
else if( nobjpt == 3 )
for( int i = 0; i < 4; i++ )
{
circle(shownFrame, imgpt[i], 3, Scalar(0,255,0), -1, CV_AA);
line(shownFrame, imgpt[i], imgpt[(i+1)%4], Scalar(0,255,0), 3, CV_AA);
circle(shownFrame, imgpt[i], 3, Scalar(0,255,0), -1, LINE_AA);
line(shownFrame, imgpt[i], imgpt[(i+1)%4], Scalar(0,255,0), 3, LINE_AA);
}
else
for( int i = 0; i < 8; i++ )
{
circle(shownFrame, imgpt[i], 3, Scalar(0,255,0), -1, CV_AA);
line(shownFrame, imgpt[i], imgpt[(i+1)%4 + (i/4)*4], Scalar(0,255,0), 3, CV_AA);
line(shownFrame, imgpt[i], imgpt[i%4], Scalar(0,255,0), 3, CV_AA);
circle(shownFrame, imgpt[i], 3, Scalar(0,255,0), -1, LINE_AA);
line(shownFrame, imgpt[i], imgpt[(i+1)%4 + (i/4)*4], Scalar(0,255,0), 3, LINE_AA);
line(shownFrame, imgpt[i], imgpt[i%4], Scalar(0,255,0), 3, LINE_AA);
}
}
@@ -210,11 +212,11 @@ static int select3DBox(const string& windowname, const string& selWinName, const
for(;;)
{
float Z = 0.f;
bool dragging = (mouse.buttonState & CV_EVENT_FLAG_LBUTTON) != 0;
bool dragging = (mouse.buttonState & EVENT_FLAG_LBUTTON) != 0;
int npt = nobjpt;
if( (mouse.event == CV_EVENT_LBUTTONDOWN ||
mouse.event == CV_EVENT_LBUTTONUP ||
if( (mouse.event == EVENT_LBUTTONDOWN ||
mouse.event == EVENT_LBUTTONUP ||
dragging) && nobjpt < 4 )
{
Point2f m = mouse.pt;
@@ -257,9 +259,9 @@ static int select3DBox(const string& windowname, const string& selWinName, const
}
box[npt] = image2plane(imgpt[npt], R, tvec, cameraMatrix, npt<3 ? 0 : Z);
if( (npt == 0 && mouse.event == CV_EVENT_LBUTTONDOWN) ||
if( (npt == 0 && mouse.event == EVENT_LBUTTONDOWN) ||
(npt > 0 && norm(box[npt] - box[npt-1]) > eps &&
mouse.event == CV_EVENT_LBUTTONUP) )
mouse.event == EVENT_LBUTTONUP) )
{
nobjpt++;
if( nobjpt < 4 )

View File

@@ -1,6 +1,7 @@
#include <opencv2/core/utility.hpp>
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <cstdio>
#include <iostream>

View File

@@ -83,7 +83,7 @@ static void findSquares( const Mat& image, vector<vector<Point> >& squares )
}
// find contours and store them all as a list
findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);
vector<Point> approx;
@@ -132,7 +132,7 @@ static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
{
const Point* p = &squares[i][0];
int n = (int)squares[i].size();
polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);
polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, LINE_AA);
}
imshow(wndname, image);

View File

@@ -46,15 +46,15 @@ bool readStringList(const string& filename, vector<string>& l)
int process(vector<string> images)
{
namedWindow("image",CV_WINDOW_KEEPRATIO); //resizable window;
for (size_t i = 0; i < images.size(); i++)
{
Mat image = imread(images[i], CV_LOAD_IMAGE_GRAYSCALE); // do grayscale processing?
imshow("image",image);
cout << "Press a key to see the next image in the list." << endl;
waitKey(); // wait indefinitely for a key to be pressed
}
return 0;
namedWindow("image", WINDOW_KEEPRATIO); //resizable window;
for (size_t i = 0; i < images.size(); i++)
{
Mat image = imread(images[i], IMREAD_GRAYSCALE); // do grayscale processing?
imshow("image",image);
cout << "Press a key to see the next image in the list." << endl;
waitKey(); // wait indefinitely for a key to be pressed
}
return 0;
}
}

View File

@@ -36,7 +36,7 @@ namespace {
char filename[200];
string window_name = "video | q or esc to quit";
cout << "press space to save a picture. q or esc to quit" << endl;
namedWindow(window_name, CV_WINDOW_KEEPRATIO); //resizable window;
namedWindow(window_name, WINDOW_KEEPRATIO); //resizable window;
Mat frame;
for (;;) {
capture >> frame;

View File

@@ -22,7 +22,7 @@
* An active user group is at:
http://tech.groups.yahoo.com/group/OpenCV/
* The minutes of weekly OpenCV development meetings are at:
http://pr.willowgarage.com/wiki/OpenCV
http://code.opencv.org/projects/opencv/wiki/Meeting_notes
************************************************** */
#include "opencv2/calib3d/calib3d.hpp"
@@ -106,7 +106,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
else
resize(img, timg, Size(), scale, scale);
found = findChessboardCorners(timg, boardSize, corners,
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE);
if( found )
{
if( scale > 1 )
@@ -121,7 +121,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
{
cout << filename << endl;
Mat cimg, cimg1;
cvtColor(img, cimg, CV_GRAY2BGR);
cvtColor(img, cimg, COLOR_GRAY2BGR);
drawChessboardCorners(cimg, boardSize, corners, found);
double sf = 640./MAX(img.rows, img.cols);
resize(cimg, cimg1, Size(), sf, sf);
@@ -135,7 +135,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
if( !found )
break;
cornerSubPix(img, corners, Size(11,11), Size(-1,-1),
TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
TermCriteria(TermCriteria::COUNT+TermCriteria::EPS,
30, 0.01));
}
if( k == 2 )
@@ -175,12 +175,12 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
imageSize, R, T, E, F,
TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5),
CV_CALIB_FIX_ASPECT_RATIO +
CV_CALIB_ZERO_TANGENT_DIST +
CV_CALIB_SAME_FOCAL_LENGTH +
CV_CALIB_RATIONAL_MODEL +
CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 100, 1e-5),
CALIB_FIX_ASPECT_RATIO +
CALIB_ZERO_TANGENT_DIST +
CALIB_SAME_FOCAL_LENGTH +
CALIB_RATIONAL_MODEL +
CALIB_FIX_K3 + CALIB_FIX_K4 + CALIB_FIX_K5);
cout << "done with RMS error=" << rms << endl;
// CALIBRATION QUALITY CHECK
@@ -214,7 +214,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
cout << "average reprojection err = " << err/npoints << endl;
// save intrinsic parameters
FileStorage fs("intrinsics.yml", CV_STORAGE_WRITE);
FileStorage fs("intrinsics.yml", FileStorage::WRITE);
if( fs.isOpened() )
{
fs << "M1" << cameraMatrix[0] << "D1" << distCoeffs[0] <<
@@ -232,7 +232,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
imageSize, R, T, R1, R2, P1, P2, Q,
CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
fs.open("extrinsics.yml", CV_STORAGE_WRITE);
fs.open("extrinsics.yml", FileStorage::WRITE);
if( fs.isOpened() )
{
fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q;
@@ -304,10 +304,10 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
for( k = 0; k < 2; k++ )
{
Mat img = imread(goodImageList[i*2+k], 0), rimg, cimg;
remap(img, rimg, rmap[k][0], rmap[k][1], CV_INTER_LINEAR);
cvtColor(rimg, cimg, CV_GRAY2BGR);
remap(img, rimg, rmap[k][0], rmap[k][1], INTER_LINEAR);
cvtColor(rimg, cimg, COLOR_GRAY2BGR);
Mat canvasPart = !isVerticalStereo ? canvas(Rect(w*k, 0, w, h)) : canvas(Rect(0, h*k, w, h));
resize(cimg, canvasPart, canvasPart.size(), 0, 0, CV_INTER_AREA);
resize(cimg, canvasPart, canvasPart.size(), 0, 0, INTER_AREA);
if( useCalibrated )
{
Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),

View File

@@ -11,6 +11,7 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/core/utility.hpp"
#include <stdio.h>
@@ -66,8 +67,8 @@ int main(int argc, char** argv)
bool no_display = false;
float scale = 1.f;
StereoBM bm;
StereoSGBM sgbm;
Ptr<StereoBM> bm = createStereoBM(16,9);
Ptr<StereoSGBM> sgbm = createStereoSGBM(0,16,3);
StereoVar var;
for( int i = 1; i < argc; i++ )
@@ -177,7 +178,7 @@ int main(int argc, char** argv)
if( intrinsic_filename )
{
// reading intrinsic parameters
FileStorage fs(intrinsic_filename, CV_STORAGE_READ);
FileStorage fs(intrinsic_filename, FileStorage::READ);
if(!fs.isOpened())
{
printf("Failed to open file %s\n", intrinsic_filename);
@@ -193,7 +194,7 @@ int main(int argc, char** argv)
M1 *= scale;
M2 *= scale;
fs.open(extrinsic_filename, CV_STORAGE_READ);
fs.open(extrinsic_filename, FileStorage::READ);
if(!fs.isOpened())
{
printf("Failed to open file %s\n", extrinsic_filename);
@@ -220,32 +221,33 @@ int main(int argc, char** argv)
numberOfDisparities = numberOfDisparities > 0 ? numberOfDisparities : ((img_size.width/8) + 15) & -16;
bm.state->roi1 = roi1;
bm.state->roi2 = roi2;
bm.state->preFilterCap = 31;
bm.state->SADWindowSize = SADWindowSize > 0 ? SADWindowSize : 9;
bm.state->minDisparity = 0;
bm.state->numberOfDisparities = numberOfDisparities;
bm.state->textureThreshold = 10;
bm.state->uniquenessRatio = 15;
bm.state->speckleWindowSize = 100;
bm.state->speckleRange = 32;
bm.state->disp12MaxDiff = 1;
bm->setROI1(roi1);
bm->setROI2(roi2);
bm->setPreFilterCap(31);
bm->setBlockSize(SADWindowSize > 0 ? SADWindowSize : 9);
bm->setMinDisparity(0);
bm->setNumDisparities(numberOfDisparities);
bm->setTextureThreshold(10);
bm->setUniquenessRatio(15);
bm->setSpeckleWindowSize(100);
bm->setSpeckleRange(32);
bm->setDisp12MaxDiff(1);
sgbm.preFilterCap = 63;
sgbm.SADWindowSize = SADWindowSize > 0 ? SADWindowSize : 3;
sgbm->setPreFilterCap(63);
int sgbmWinSize = SADWindowSize > 0 ? SADWindowSize : 3;
sgbm->setBlockSize(sgbmWinSize);
int cn = img1.channels();
sgbm.P1 = 8*cn*sgbm.SADWindowSize*sgbm.SADWindowSize;
sgbm.P2 = 32*cn*sgbm.SADWindowSize*sgbm.SADWindowSize;
sgbm.minDisparity = 0;
sgbm.numberOfDisparities = numberOfDisparities;
sgbm.uniquenessRatio = 10;
sgbm.speckleWindowSize = bm.state->speckleWindowSize;
sgbm.speckleRange = bm.state->speckleRange;
sgbm.disp12MaxDiff = 1;
sgbm.fullDP = alg == STEREO_HH;
sgbm->setP1(8*cn*sgbmWinSize*sgbmWinSize);
sgbm->setP2(32*cn*sgbmWinSize*sgbmWinSize);
sgbm->setMinDisparity(0);
sgbm->setNumDisparities(numberOfDisparities);
sgbm->setUniquenessRatio(10);
sgbm->setSpeckleWindowSize(100);
sgbm->setSpeckleRange(32);
sgbm->setDisp12MaxDiff(1);
sgbm->setMode(alg == STEREO_HH ? StereoSGBM::MODE_HH : StereoSGBM::MODE_SGBM);
var.levels = 3; // ignored with USE_AUTO_PARAMS
var.pyrScale = 0.5; // ignored with USE_AUTO_PARAMS
@@ -267,12 +269,12 @@ int main(int argc, char** argv)
int64 t = getTickCount();
if( alg == STEREO_BM )
bm(img1, img2, disp);
bm->compute(img1, img2, disp);
else if( alg == STEREO_VAR ) {
var(img1, img2, disp);
}
else if( alg == STEREO_SGBM || alg == STEREO_HH )
sgbm(img1, img2, disp);
sgbm->compute(img1, img2, disp);
t = getTickCount() - t;
printf("Time elapsed: %fms\n", t*1000/getTickFrequency());

View File

@@ -42,8 +42,8 @@
#include <iostream>
#include <fstream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching/stitcher.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/stitching.hpp"
using namespace std;
using namespace cv;

View File

@@ -45,7 +45,8 @@
#include <fstream>
#include <string>
#include "opencv2/opencv_modules.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/highgui.hpp"
#include "opencv2/stitching/detail/autocalib.hpp"
#include "opencv2/stitching/detail/blenders.hpp"
#include "opencv2/stitching/detail/camera.hpp"
@@ -120,7 +121,7 @@ static void printUsage()
// Default command line args
vector<string> img_names;
vector<String> img_names;
bool preview = false;
bool try_gpu = false;
double work_megapix = 0.6;
@@ -326,7 +327,10 @@ static int parseCmdArgs(int argc, char** argv)
int main(int argc, char* argv[])
{
#if ENABLE_LOG
int64 app_start_time = getTickCount();
#endif
cv::setBreakOnError(true);
int retval = parseCmdArgs(argc, argv);
@@ -345,12 +349,14 @@ int main(int argc, char* argv[])
bool is_work_scale_set = false, is_seam_scale_set = false, is_compose_scale_set = false;
LOGLN("Finding features...");
#if ENABLE_LOG
int64 t = getTickCount();
#endif
Ptr<FeaturesFinder> finder;
if (features_type == "surf")
{
#ifdef HAVE_OPENCV_GPU
#if defined(HAVE_OPENCV_NONFREE) && defined(HAVE_OPENCV_GPU)
if (try_gpu && gpu::getCudaEnabledDeviceCount() > 0)
finder = new SurfFeaturesFinderGpu();
else
@@ -420,7 +426,9 @@ int main(int argc, char* argv[])
LOGLN("Finding features, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
LOG("Pairwise matching");
#if ENABLE_LOG
t = getTickCount();
#endif
vector<MatchesInfo> pairwise_matches;
BestOf2NearestMatcher matcher(try_gpu, match_conf);
matcher(features, pairwise_matches);
@@ -438,7 +446,7 @@ int main(int argc, char* argv[])
// Leave only images we are sure are from the same panorama
vector<int> indices = leaveBiggestComponent(features, pairwise_matches, conf_thresh);
vector<Mat> img_subset;
vector<string> img_names_subset;
vector<String> img_names_subset;
vector<Size> full_img_sizes_subset;
for (size_t i = 0; i < indices.size(); ++i)
{
@@ -516,7 +524,9 @@ int main(int argc, char* argv[])
}
LOGLN("Warping images (auxiliary)... ");
#if ENABLE_LOG
t = getTickCount();
#endif
vector<Point> corners(num_images);
vector<Mat> masks_warped(num_images);
@@ -634,7 +644,9 @@ int main(int argc, char* argv[])
masks.clear();
LOGLN("Compositing...");
#if ENABLE_LOG
t = getTickCount();
#endif
Mat img_warped, img_warped_s;
Mat dilated_mask, seam_mask, mask, mask_warped;

View File

@@ -4,8 +4,8 @@
* @author OpenCV team
*/
#include <cv.h>
#include <highgui.h>
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
using namespace cv;
@@ -24,7 +24,7 @@ Mat dst;
* @function on_trackbar
* @brief Callback for trackbar
*/
void on_trackbar( int, void* )
static void on_trackbar( int, void* )
{
alpha = (double) alpha_slider/alpha_slider_max ;
@@ -40,7 +40,7 @@ void on_trackbar( int, void* )
* @function main
* @brief Main function
*/
int main( int argc, char** argv )
int main( void )
{
/// Read image ( same size, same type )
src1 = imread("../images/LinuxLogo.jpg");

View File

@@ -5,8 +5,7 @@
* @author OpenCV team
*/
#include <cv.h>
#include <highgui.h>
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
@@ -18,13 +17,12 @@ int beta; /**< Simple brightness control*/
/** Matrices to store images */
Mat image;
Mat new_image;
/**
* @function on_trackbar
* @brief Called whenever any of alpha or beta changes
*/
void on_trackbar( int, void* )
static void on_trackbar( int, void* )
{
Mat new_image = Mat::zeros( image.size(), image.type() );
@@ -44,7 +42,7 @@ void on_trackbar( int, void* )
* @function main
* @brief Main function
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Read image given by user
image = imread( argv[1] );

View File

@@ -1,10 +1,10 @@
#include <iostream> // for standard I/O
#include <iostream> // for standard I/O
#include <string> // for strings
#include <iomanip> // for controlling float print precision
#include <sstream> // string to number conversion
#include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur
#include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
#include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur
#include <opencv2/highgui/highgui.hpp> // OpenCV window I/O
using namespace std;
@@ -13,55 +13,57 @@ using namespace cv;
double getPSNR ( const Mat& I1, const Mat& I2);
Scalar getMSSIM( const Mat& I1, const Mat& I2);
void help()
static void help()
{
cout
<< "\n--------------------------------------------------------------------------" << endl
<< "This program shows how to read a video file with OpenCV. In addition, it tests the"
<< " similarity of two input videos first with PSNR, and for the frames below a PSNR " << endl
<< "trigger value, also with MSSIM."<< endl
<< "Usage:" << endl
<< "------------------------------------------------------------------------------" << endl
<< "This program shows how to read a video file with OpenCV. In addition, it "
<< "tests the similarity of two input videos first with PSNR, and for the frames "
<< "below a PSNR trigger value, also with MSSIM." << endl
<< "Usage:" << endl
<< "./video-source referenceVideo useCaseTestVideo PSNR_Trigger_Value Wait_Between_Frames " << endl
<< "--------------------------------------------------------------------------" << endl
<< "--------------------------------------------------------------------------" << endl
<< endl;
}
int main(int argc, char *argv[], char *window_name)
int main(int argc, char *argv[])
{
help();
if (argc != 5)
{
cout << "Not enough parameters" << endl;
return -1;
}
stringstream conv;
const string sourceReference = argv[1],sourceCompareWith = argv[2];
const string sourceReference = argv[1], sourceCompareWith = argv[2];
int psnrTriggerValue, delay;
conv << argv[3] << endl << argv[4]; // put in the strings
conv >> psnrTriggerValue >> delay;// take out the numbers
conv << argv[3] << endl << argv[4]; // put in the strings
conv >> psnrTriggerValue >> delay; // take out the numbers
char c;
int frameNum = -1; // Frame counter
int frameNum = -1; // Frame counter
VideoCapture captRefrnc(sourceReference),
captUndTst(sourceCompareWith);
VideoCapture captRefrnc(sourceReference), captUndTst(sourceCompareWith);
if ( !captRefrnc.isOpened())
if (!captRefrnc.isOpened())
{
cout << "Could not open reference " << sourceReference << endl;
return -1;
}
if( !captUndTst.isOpened())
if (!captUndTst.isOpened())
{
cout << "Could not open case test " << sourceCompareWith << endl;
return -1;
}
Size refS = Size((int) captRefrnc.get(CV_CAP_PROP_FRAME_WIDTH),
(int) captRefrnc.get(CV_CAP_PROP_FRAME_HEIGHT)),
uTSi = Size((int) captUndTst.get(CV_CAP_PROP_FRAME_WIDTH),
(int) captUndTst.get(CV_CAP_PROP_FRAME_HEIGHT));
Size refS = Size((int) captRefrnc.get(CAP_PROP_FRAME_WIDTH),
(int) captRefrnc.get(CAP_PROP_FRAME_HEIGHT)),
uTSi = Size((int) captUndTst.get(CAP_PROP_FRAME_WIDTH),
(int) captUndTst.get(CAP_PROP_FRAME_HEIGHT));
if (refS != uTSi)
{
@@ -73,43 +75,43 @@ int main(int argc, char *argv[], char *window_name)
const char* WIN_RF = "Reference";
// Windows
namedWindow(WIN_RF, CV_WINDOW_AUTOSIZE );
namedWindow(WIN_UT, CV_WINDOW_AUTOSIZE );
cvMoveWindow(WIN_RF, 400 , 0); //750, 2 (bernat =0)
cvMoveWindow(WIN_UT, refS.width, 0); //1500, 2
namedWindow(WIN_RF, WINDOW_AUTOSIZE);
namedWindow(WIN_UT, WINDOW_AUTOSIZE);
moveWindow(WIN_RF, 400 , 0); //750, 2 (bernat =0)
moveWindow(WIN_UT, refS.width, 0); //1500, 2
cout << "Reference frame resolution: Width=" << refS.width << " Height=" << refS.height
<< " of nr#: " << captRefrnc.get(CV_CAP_PROP_FRAME_COUNT) << endl;
<< " of nr#: " << captRefrnc.get(CAP_PROP_FRAME_COUNT) << endl;
cout << "PSNR trigger value " <<
setiosflags(ios::fixed) << setprecision(3) << psnrTriggerValue << endl;
cout << "PSNR trigger value " << setiosflags(ios::fixed) << setprecision(3)
<< psnrTriggerValue << endl;
Mat frameReference, frameUnderTest;
double psnrV;
Scalar mssimV;
while( true) //Show the image captured in the window and repeat
for(;;) //Show the image captured in the window and repeat
{
captRefrnc >> frameReference;
captUndTst >> frameUnderTest;
if( frameReference.empty() || frameUnderTest.empty())
if (frameReference.empty() || frameUnderTest.empty())
{
cout << " < < < Game over! > > > ";
break;
}
++frameNum;
cout <<"Frame:" << frameNum <<"# ";
cout << "Frame: " << frameNum << "# ";
///////////////////////////////// PSNR ////////////////////////////////////////////////////
psnrV = getPSNR(frameReference,frameUnderTest); //get PSNR
psnrV = getPSNR(frameReference,frameUnderTest);
cout << setiosflags(ios::fixed) << setprecision(3) << psnrV << "dB";
//////////////////////////////////// MSSIM /////////////////////////////////////////////////
if (psnrV < psnrTriggerValue && psnrV)
{
mssimV = getMSSIM(frameReference,frameUnderTest);
mssimV = getMSSIM(frameReference, frameUnderTest);
cout << " MSSIM: "
<< " R " << setiosflags(ios::fixed) << setprecision(2) << mssimV.val[2] * 100 << "%"
@@ -120,10 +122,10 @@ int main(int argc, char *argv[], char *window_name)
cout << endl;
////////////////////////////////// Show Image /////////////////////////////////////////////
imshow( WIN_RF, frameReference);
imshow( WIN_UT, frameUnderTest);
imshow(WIN_RF, frameReference);
imshow(WIN_UT, frameUnderTest);
c = cvWaitKey(delay);
c = (char)waitKey(delay);
if (c == 27) break;
}
@@ -137,7 +139,7 @@ double getPSNR(const Mat& I1, const Mat& I2)
s1.convertTo(s1, CV_32F); // cannot make a square on 8 bits
s1 = s1.mul(s1); // |I1 - I2|^2
Scalar s = sum(s1); // sum elements per channel
Scalar s = sum(s1); // sum elements per channel
double sse = s.val[0] + s.val[1] + s.val[2]; // sum channels
@@ -145,8 +147,8 @@ double getPSNR(const Mat& I1, const Mat& I2)
return 0;
else
{
double mse =sse /(double)(I1.channels() * I1.total());
double psnr = 10.0*log10((255*255)/mse);
double mse = sse / (double)(I1.channels() * I1.total());
double psnr = 10.0 * log10((255 * 255) / mse);
return psnr;
}
}
@@ -155,10 +157,10 @@ Scalar getMSSIM( const Mat& i1, const Mat& i2)
{
const double C1 = 6.5025, C2 = 58.5225;
/***************************** INITS **********************************/
int d = CV_32F;
int d = CV_32F;
Mat I1, I2;
i1.convertTo(I1, d); // cannot calculate on one byte large values
i1.convertTo(I1, d); // cannot calculate on one byte large values
i2.convertTo(I2, d);
Mat I2_2 = I2.mul(I2); // I2^2
@@ -167,7 +169,7 @@ Scalar getMSSIM( const Mat& i1, const Mat& i2)
/*************************** END INITS **********************************/
Mat mu1, mu2; // PRELIMINARY COMPUTING
Mat mu1, mu2; // PRELIMINARY COMPUTING
GaussianBlur(I1, mu1, Size(11, 11), 1.5);
GaussianBlur(I2, mu2, Size(11, 11), 1.5);
@@ -191,15 +193,15 @@ Scalar getMSSIM( const Mat& i1, const Mat& i2)
t1 = 2 * mu1_mu2 + C1;
t2 = 2 * sigma12 + C2;
t3 = t1.mul(t2); // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))
t3 = t1.mul(t2); // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))
t1 = mu1_2 + mu2_2 + C1;
t2 = sigma1_2 + sigma2_2 + C2;
t1 = t1.mul(t2); // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))
t1 = t1.mul(t2); // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))
Mat ssim_map;
divide(t3, t1, ssim_map); // ssim_map = t3./t1;
divide(t3, t1, ssim_map); // ssim_map = t3./t1;
Scalar mssim = mean( ssim_map ); // mssim = average of ssim map
Scalar mssim = mean(ssim_map); // mssim = average of ssim map
return mssim;
}
}

View File

@@ -7,51 +7,53 @@
using namespace std;
using namespace cv;
void help()
static void help()
{
cout
<< "\n--------------------------------------------------------------------------" << endl
<< "This program shows how to write video files. You can extract the R or G or B color channel "
<< " of the input video.write " << endl
<< "Usage:" << endl
<< "./video-write inputvideoName [ R | G | B] [Y | N]" << endl
<< "--------------------------------------------------------------------------" << endl
<< "------------------------------------------------------------------------------" << endl
<< "This program shows how to write video files." << endl
<< "You can extract the R or G or B color channel of the input video." << endl
<< "Usage:" << endl
<< "./video-write inputvideoName [ R | G | B] [Y | N]" << endl
<< "------------------------------------------------------------------------------" << endl
<< endl;
}
int main(int argc, char *argv[], char *window_name)
int main(int argc, char *argv[])
{
help();
if (argc != 4)
{
cout << "Not enough parameters" << endl;
return -1;
}
const string source = argv[1]; // the source file name
const string source = argv[1]; // the source file name
const bool askOutputType = argv[3][0] =='Y'; // If false it will use the inputs codec type
VideoCapture inputVideo(source); // Open input
if ( !inputVideo.isOpened())
VideoCapture inputVideo(source); // Open input
if (!inputVideo.isOpened())
{
cout << "Could not open the input video." << source << endl;
cout << "Could not open the input video: " << source << endl;
return -1;
}
string::size_type pAt = source.find_last_of('.'); // Find extension point
string::size_type pAt = source.find_last_of('.'); // Find extension point
const string NAME = source.substr(0, pAt) + argv[2][0] + ".avi"; // Form the new name with container
int ex = static_cast<int>(inputVideo.get(CV_CAP_PROP_FOURCC)); // Get Codec Type- Int form
int ex = static_cast<int>(inputVideo.get(CAP_PROP_FOURCC)); // Get Codec Type- Int form
// Transform from int to char via Bitwise operators
char EXT[] = {ex & 0XFF , (ex & 0XFF00) >> 8,(ex & 0XFF0000) >> 16,(ex & 0XFF000000) >> 24, 0};
char EXT[] = {(char)(ex & 0XFF) , (char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24), 0};
Size S = Size((int) inputVideo.get(CV_CAP_PROP_FRAME_WIDTH), //Acquire input size
(int) inputVideo.get(CV_CAP_PROP_FRAME_HEIGHT));
Size S = Size((int) inputVideo.get(CAP_PROP_FRAME_WIDTH), // Acquire input size
(int) inputVideo.get(CAP_PROP_FRAME_HEIGHT));
VideoWriter outputVideo; // Open the output
if (askOutputType)
outputVideo.open(NAME , ex=-1, inputVideo.get(CV_CAP_PROP_FPS),S, true);
outputVideo.open(NAME, ex=-1, inputVideo.get(CAP_PROP_FPS), S, true);
else
outputVideo.open(NAME , ex, inputVideo.get(CV_CAP_PROP_FPS),S, true);
outputVideo.open(NAME, ex, inputVideo.get(CAP_PROP_FPS), S, true);
if (!outputVideo.isOpened())
{
@@ -59,33 +61,29 @@ int main(int argc, char *argv[], char *window_name)
return -1;
}
union { int v; char c[5];} uEx ;
uEx.v = ex; // From Int to char via union
uEx.c[4]='\0';
cout << "Input frame resolution: Width=" << S.width << " Height=" << S.height
<< " of nr#: " << inputVideo.get(CV_CAP_PROP_FRAME_COUNT) << endl;
<< " of nr#: " << inputVideo.get(CAP_PROP_FRAME_COUNT) << endl;
cout << "Input codec type: " << EXT << endl;
int channel = 2; // Select the channel to save
int channel = 2; // Select the channel to save
switch(argv[2][0])
{
case 'R' : {channel = 2; break;}
case 'G' : {channel = 1; break;}
case 'B' : {channel = 0; break;}
case 'R' : channel = 2; break;
case 'G' : channel = 1; break;
case 'B' : channel = 0; break;
}
Mat src,res;
Mat src, res;
vector<Mat> spl;
while( true) //Show the image captured in the window and repeat
for(;;) //Show the image captured in the window and repeat
{
inputVideo >> src; // read
if( src.empty()) break; // check if at end
if (src.empty()) break; // check if at end
split(src, spl); // process - extract only the correct channel
for( int i =0; i < 3; ++i)
if (i != channel)
spl[i] = Mat::zeros(S, spl[0].type());
split(src, spl); // process - extract only the correct channel
for (int i =0; i < 3; ++i)
if (i != channel)
spl[i] = Mat::zeros(S, spl[0].type());
merge(spl, res);
//outputVideo.write(res); //save or
@@ -94,4 +92,4 @@ int main(int argc, char *argv[], char *window_name)
cout << "Finished writing" << endl;
return 0;
}
}

View File

@@ -15,12 +15,12 @@ using namespace std;
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
Mat src, dst;
char* source_window = "Source image";
char* equalized_window = "Equalized Image";
const char* source_window = "Source image";
const char* equalized_window = "Equalized Image";
/// Load image
src = imread( argv[1], 1 );
@@ -31,14 +31,14 @@ int main( int argc, char** argv )
}
/// Convert to grayscale
cvtColor( src, src, CV_BGR2GRAY );
cvtColor( src, src, COLOR_BGR2GRAY );
/// Apply Histogram Equalization
equalizeHist( src, dst );
/// Display results
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
namedWindow( equalized_window, CV_WINDOW_AUTOSIZE );
namedWindow( source_window, WINDOW_AUTOSIZE );
namedWindow( equalized_window, WINDOW_AUTOSIZE );
imshow( source_window, src );
imshow( equalized_window, dst );

View File

@@ -14,8 +14,8 @@ using namespace cv;
/// Global Variables
Mat img; Mat templ; Mat result;
char* image_window = "Source Image";
char* result_window = "Result window";
const char* image_window = "Source Image";
const char* result_window = "Result window";
int match_method;
int max_Trackbar = 5;
@@ -26,18 +26,18 @@ void MatchingMethod( int, void* );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Load image and template
img = imread( argv[1], 1 );
templ = imread( argv[2], 1 );
/// Create windows
namedWindow( image_window, CV_WINDOW_AUTOSIZE );
namedWindow( result_window, CV_WINDOW_AUTOSIZE );
namedWindow( image_window, WINDOW_AUTOSIZE );
namedWindow( result_window, WINDOW_AUTOSIZE );
/// Create Trackbar
char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
const char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
createTrackbar( trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod );
MatchingMethod( 0, 0 );
@@ -74,7 +74,7 @@ void MatchingMethod( int, void* )
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
if( match_method == TM_SQDIFF || match_method == TM_SQDIFF_NORMED )
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; }

View File

@@ -23,12 +23,12 @@ void Hist_and_Backproj(int, void* );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Read the image
src = imread( argv[1], 1 );
/// Transform it to HSV
cvtColor( src, hsv, CV_BGR2HSV );
cvtColor( src, hsv, COLOR_BGR2HSV );
/// Use only the Hue value
hue.create( hsv.size(), hsv.depth() );
@@ -36,8 +36,8 @@ int main( int argc, char** argv )
mixChannels( &hsv, 1, &hue, 1, ch, 1 );
/// Create Trackbar to enter the number of bins
char* window_image = "Source image";
namedWindow( window_image, CV_WINDOW_AUTOSIZE );
const char* window_image = "Source image";
namedWindow( window_image, WINDOW_AUTOSIZE );
createTrackbar("* Hue bins: ", window_image, &bins, 180, Hist_and_Backproj );
Hist_and_Backproj(0, 0);

View File

@@ -17,7 +17,7 @@ Mat src; Mat hsv;
Mat mask;
int lo = 20; int up = 20;
char* window_image = "Source image";
const char* window_image = "Source image";
/// Function Headers
void Hist_and_Backproj( );
@@ -26,15 +26,15 @@ void pickPoint (int event, int x, int y, int, void* );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Read the image
src = imread( argv[1], 1 );
/// Transform it to HSV
cvtColor( src, hsv, CV_BGR2HSV );
cvtColor( src, hsv, COLOR_BGR2HSV );
/// Show the image
namedWindow( window_image, CV_WINDOW_AUTOSIZE );
namedWindow( window_image, WINDOW_AUTOSIZE );
imshow( window_image, src );
/// Set Trackbars for floodfill thresholds
@@ -52,7 +52,7 @@ int main( int argc, char** argv )
*/
void pickPoint (int event, int x, int y, int, void* )
{
if( event != CV_EVENT_LBUTTONDOWN )
if( event != EVENT_LBUTTONDOWN )
{ return; }
// Fill and get the mask

View File

@@ -15,7 +15,7 @@ using namespace cv;
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
Mat src, dst;
@@ -71,7 +71,7 @@ int main( int argc, char** argv )
}
/// Display
namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
namedWindow("calcHist Demo", WINDOW_AUTOSIZE );
imshow("calcHist Demo", histImage );
waitKey(0);

View File

@@ -33,9 +33,9 @@ int main( int argc, char** argv )
src_test2 = imread( argv[3], 1 );
/// Convert to HSV
cvtColor( src_base, hsv_base, CV_BGR2HSV );
cvtColor( src_test1, hsv_test1, CV_BGR2HSV );
cvtColor( src_test2, hsv_test2, CV_BGR2HSV );
cvtColor( src_base, hsv_base, COLOR_BGR2HSV );
cvtColor( src_test1, hsv_test1, COLOR_BGR2HSV );
cvtColor( src_test2, hsv_test2, COLOR_BGR2HSV );
hsv_half_down = hsv_base( Range( hsv_base.rows/2, hsv_base.rows - 1 ), Range( 0, hsv_base.cols - 1 ) );

View File

@@ -4,8 +4,7 @@
* @author OpenCV team
*/
#include <cv.h>
#include <highgui.h>
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
@@ -14,7 +13,7 @@ using namespace cv;
* @function main
* @brief Main function
*/
int main( int argc, char** argv )
int main( void )
{
double alpha = 0.5; double beta; double input;
@@ -35,8 +34,8 @@ int main( int argc, char** argv )
src1 = imread("../images/LinuxLogo.jpg");
src2 = imread("../images/WindowsLogo.jpg");
if( !src1.data ) { printf("Error loading src1 \n"); return -1; }
if( !src2.data ) { printf("Error loading src2 \n"); return -1; }
if( !src1.data ) { std::cout<< "Error loading src1"<<std::endl; return -1; }
if( !src2.data ) { std::cout<< "Error loading src2"<<std::endl; return -1; }
/// Create Windows
namedWindow("Linear Blend", 1);

View File

@@ -4,8 +4,7 @@
* @author OpenCV team
*/
#include <cv.h>
#include <highgui.h>
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
@@ -17,7 +16,7 @@ int beta; /**< Simple brightness control */
* @function main
* @brief Main function
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Read image given by user
Mat image = imread( argv[1] );

View File

@@ -6,7 +6,6 @@
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "highgui.h"
#include <stdlib.h>
#include <stdio.h>
@@ -29,7 +28,7 @@ void Dilation( int, void* );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Load an image
src = imread( argv[1] );
@@ -38,9 +37,9 @@ int main( int argc, char** argv )
{ return -1; }
/// Create windows
namedWindow( "Erosion Demo", CV_WINDOW_AUTOSIZE );
namedWindow( "Dilation Demo", CV_WINDOW_AUTOSIZE );
cvMoveWindow( "Dilation Demo", src.cols, 0 );
namedWindow( "Erosion Demo", WINDOW_AUTOSIZE );
namedWindow( "Dilation Demo", WINDOW_AUTOSIZE );
moveWindow( "Dilation Demo", src.cols, 0 );
/// Create Erosion Trackbar
createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Erosion Demo",
@@ -73,7 +72,7 @@ int main( int argc, char** argv )
*/
void Erosion( int, void* )
{
int erosion_type;
int erosion_type = 0;
if( erosion_elem == 0 ){ erosion_type = MORPH_RECT; }
else if( erosion_elem == 1 ){ erosion_type = MORPH_CROSS; }
else if( erosion_elem == 2) { erosion_type = MORPH_ELLIPSE; }
@@ -91,7 +90,7 @@ void Erosion( int, void* )
*/
void Dilation( int, void* )
{
int dilation_type;
int dilation_type = 0;
if( dilation_elem == 0 ){ dilation_type = MORPH_RECT; }
else if( dilation_elem == 1 ){ dilation_type = MORPH_CROSS; }
else if( dilation_elem == 2) { dilation_type = MORPH_ELLIPSE; }

View File

@@ -21,7 +21,7 @@ int const max_operator = 4;
int const max_elem = 2;
int const max_kernel_size = 21;
char* window_name = "Morphology Transformations Demo";
const char* window_name = "Morphology Transformations Demo";
/** Function Headers */
@@ -30,7 +30,7 @@ void Morphology_Operations( int, void* );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Load an image
src = imread( argv[1] );
@@ -39,7 +39,7 @@ int main( int argc, char** argv )
{ return -1; }
/// Create window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
namedWindow( window_name, WINDOW_AUTOSIZE );
/// Create Trackbar to select Morphology operation
createTrackbar("Operator:\n 0: Opening - 1: Closing \n 2: Gradient - 3: Top Hat \n 4: Black Hat", window_name, &morph_operator, max_operator, Morphology_Operations );

View File

@@ -15,13 +15,13 @@ using namespace cv;
/// Global variables
Mat src, dst, tmp;
char* window_name = "Pyramids Demo";
const char* window_name = "Pyramids Demo";
/**
* @function main
*/
int main( int argc, char** argv )
int main( void )
{
/// General instructions
printf( "\n Zoom In-Out demo \n " );
@@ -40,11 +40,11 @@ int main( int argc, char** argv )
dst = tmp;
/// Create window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
namedWindow( window_name, WINDOW_AUTOSIZE );
imshow( window_name, dst );
/// Loop
while( true )
for(;;)
{
int c;
c = waitKey(10);

View File

@@ -22,16 +22,16 @@ Mat src; Mat dst;
char window_name[] = "Smoothing Demo";
/// Function headers
int display_caption( char* caption );
int display_caption( const char* caption );
int display_dst( int delay );
/**
* function main
*/
int main( int argc, char** argv )
int main( void )
{
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
namedWindow( window_name, WINDOW_AUTOSIZE );
/// Load the source image
src = imread( "../images/lena.png", 1 );
@@ -84,12 +84,12 @@ int main( int argc, char** argv )
/**
* @function display_caption
*/
int display_caption( char* caption )
int display_caption( const char* caption )
{
dst = Mat::zeros( src.size(), src.type() );
putText( dst, caption,
Point( src.cols/4, src.rows/2),
CV_FONT_HERSHEY_COMPLEX, 1, Scalar(255, 255, 255) );
FONT_HERSHEY_COMPLEX, 1, Scalar(255, 255, 255) );
imshow( window_name, dst );
int c = waitKey( DELAY_CAPTION );

View File

@@ -20,10 +20,10 @@ int const max_type = 4;
int const max_BINARY_value = 255;
Mat src, src_gray, dst;
char* window_name = "Threshold Demo";
const char* window_name = "Threshold Demo";
char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
char* trackbar_value = "Value";
const char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
const char* trackbar_value = "Value";
/// Function headers
void Threshold_Demo( int, void* );
@@ -31,16 +31,16 @@ void Threshold_Demo( int, void* );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Load an image
src = imread( argv[1], 1 );
/// Convert the image to Gray
cvtColor( src, src_gray, CV_RGB2GRAY );
cvtColor( src, src_gray, COLOR_RGB2GRAY );
/// Create a window to display results
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
namedWindow( window_name, WINDOW_AUTOSIZE );
/// Create Trackbar to choose type of Threshold
createTrackbar( trackbar_type,
@@ -55,7 +55,7 @@ int main( int argc, char** argv )
Threshold_Demo( 0, 0 );
/// Wait until user finishes program
while(true)
for(;;)
{
int c;
c = waitKey( 20 );

View File

@@ -21,13 +21,13 @@ int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";
const char* window_name = "Edge Map";
/**
* @function CannyThreshold
* @brief Trackbar callback - Canny thresholds input with a ratio 1:3
*/
void CannyThreshold(int, void*)
static void CannyThreshold(int, void*)
{
/// Reduce noise with a kernel 3x3
blur( src_gray, detected_edges, Size(3,3) );
@@ -46,7 +46,7 @@ void CannyThreshold(int, void*)
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Load an image
src = imread( argv[1] );
@@ -58,10 +58,10 @@ int main( int argc, char** argv )
dst.create( src.size(), src.type() );
/// Convert the image to grayscale
cvtColor( src, src_gray, CV_BGR2GRAY );
cvtColor( src, src_gray, COLOR_BGR2GRAY );
/// Create a window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
namedWindow( window_name, WINDOW_AUTOSIZE );
/// Create a Trackbar for user to enter threshold
createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );

View File

@@ -13,14 +13,14 @@ using namespace cv;
using namespace std;
/// Global variables
char* source_window = "Source image";
char* warp_window = "Warp";
char* warp_rotate_window = "Warp + Rotate";
const char* source_window = "Source image";
const char* warp_window = "Warp";
const char* warp_rotate_window = "Warp + Rotate";
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
Point2f srcTri[3];
Point2f dstTri[3];
@@ -37,12 +37,12 @@ int main( int argc, char** argv )
/// Set your 3 points to calculate the Affine Transform
srcTri[0] = Point2f( 0,0 );
srcTri[1] = Point2f( src.cols - 1, 0 );
srcTri[2] = Point2f( 0, src.rows - 1 );
srcTri[1] = Point2f( src.cols - 1.f, 0 );
srcTri[2] = Point2f( 0, src.rows - 1.f );
dstTri[0] = Point2f( src.cols*0.0, src.rows*0.33 );
dstTri[1] = Point2f( src.cols*0.85, src.rows*0.25 );
dstTri[2] = Point2f( src.cols*0.15, src.rows*0.7 );
dstTri[0] = Point2f( src.cols*0.0f, src.rows*0.33f );
dstTri[1] = Point2f( src.cols*0.85f, src.rows*0.25f );
dstTri[2] = Point2f( src.cols*0.15f, src.rows*0.7f );
/// Get the Affine Transform
warp_mat = getAffineTransform( srcTri, dstTri );
@@ -65,13 +65,13 @@ int main( int argc, char** argv )
/// Show what you got
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
namedWindow( source_window, WINDOW_AUTOSIZE );
imshow( source_window, src );
namedWindow( warp_window, CV_WINDOW_AUTOSIZE );
namedWindow( warp_window, WINDOW_AUTOSIZE );
imshow( warp_window, warp_dst );
namedWindow( warp_rotate_window, CV_WINDOW_AUTOSIZE );
namedWindow( warp_rotate_window, WINDOW_AUTOSIZE );
imshow( warp_rotate_window, warp_rotate_dst );
/// Wait until user exits the program

View File

@@ -9,12 +9,13 @@
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/**
* @function main
*/
int main(int argc, char** argv)
int main(int, char** argv)
{
Mat src, src_gray;
@@ -25,7 +26,7 @@ int main(int argc, char** argv)
{ return -1; }
/// Convert it to gray
cvtColor( src, src_gray, CV_BGR2GRAY );
cvtColor( src, src_gray, COLOR_BGR2GRAY );
/// Reduce the noise so we avoid false circle detection
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
@@ -33,7 +34,7 @@ int main(int argc, char** argv)
vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, 200, 100, 0, 0 );
HoughCircles( src_gray, circles, HOUGH_GRADIENT, 1, src_gray.rows/8, 200, 100, 0, 0 );
/// Draw the circles detected
for( size_t i = 0; i < circles.size(); i++ )
@@ -47,7 +48,7 @@ int main(int argc, char** argv)
}
/// Show your results
namedWindow( "Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE );
namedWindow( "Hough Circle Transform Demo", WINDOW_AUTOSIZE );
imshow( "Hough Circle Transform Demo", src );
waitKey(0);

View File

@@ -21,8 +21,8 @@ Mat standard_hough, probabilistic_hough;
int min_threshold = 50;
int max_trackbar = 150;
char* standard_name = "Standard Hough Lines Demo";
char* probabilistic_name = "Probabilistic Hough Lines Demo";
const char* standard_name = "Standard Hough Lines Demo";
const char* probabilistic_name = "Probabilistic Hough Lines Demo";
int s_trackbar = max_trackbar;
int p_trackbar = max_trackbar;
@@ -35,7 +35,7 @@ void Probabilistic_Hough( int, void* );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Read the image
src = imread( argv[1], 1 );
@@ -46,7 +46,7 @@ int main( int argc, char** argv )
}
/// Pass the image to gray
cvtColor( src, src_gray, CV_RGB2GRAY );
cvtColor( src, src_gray, COLOR_RGB2GRAY );
/// Apply Canny edge detector
Canny( src_gray, edges, 50, 200, 3 );
@@ -55,10 +55,10 @@ int main( int argc, char** argv )
char thresh_label[50];
sprintf( thresh_label, "Thres: %d + input", min_threshold );
namedWindow( standard_name, CV_WINDOW_AUTOSIZE );
namedWindow( standard_name, WINDOW_AUTOSIZE );
createTrackbar( thresh_label, standard_name, &s_trackbar, max_trackbar, Standard_Hough);
namedWindow( probabilistic_name, CV_WINDOW_AUTOSIZE );
namedWindow( probabilistic_name, WINDOW_AUTOSIZE );
createTrackbar( thresh_label, probabilistic_name, &p_trackbar, max_trackbar, Probabilistic_Hough);
/// Initialize
@@ -85,13 +85,13 @@ void help()
void Standard_Hough( int, void* )
{
vector<Vec2f> s_lines;
cvtColor( edges, standard_hough, CV_GRAY2BGR );
cvtColor( edges, standard_hough, COLOR_GRAY2BGR );
/// 1. Use Standard Hough Transform
HoughLines( edges, s_lines, 1, CV_PI/180, min_threshold + s_trackbar, 0, 0 );
/// Show the result
for( int i = 0; i < s_lines.size(); i++ )
for( size_t i = 0; i < s_lines.size(); i++ )
{
float r = s_lines[i][0], t = s_lines[i][1];
double cos_t = cos(t), sin_t = sin(t);
@@ -100,7 +100,7 @@ void Standard_Hough( int, void* )
Point pt1( cvRound(x0 + alpha*(-sin_t)), cvRound(y0 + alpha*cos_t) );
Point pt2( cvRound(x0 - alpha*(-sin_t)), cvRound(y0 - alpha*cos_t) );
line( standard_hough, pt1, pt2, Scalar(255,0,0), 3, CV_AA);
line( standard_hough, pt1, pt2, Scalar(255,0,0), 3, LINE_AA);
}
imshow( standard_name, standard_hough );
@@ -112,7 +112,7 @@ void Standard_Hough( int, void* )
void Probabilistic_Hough( int, void* )
{
vector<Vec4i> p_lines;
cvtColor( edges, probabilistic_hough, CV_GRAY2BGR );
cvtColor( edges, probabilistic_hough, COLOR_GRAY2BGR );
/// 2. Use Probabilistic Hough Transform
HoughLinesP( edges, p_lines, 1, CV_PI/180, min_threshold + p_trackbar, 30, 10 );
@@ -121,7 +121,7 @@ void Probabilistic_Hough( int, void* )
for( size_t i = 0; i < p_lines.size(); i++ )
{
Vec4i l = p_lines[i];
line( probabilistic_hough, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255,0,0), 3, CV_AA);
line( probabilistic_hough, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255,0,0), 3, LINE_AA);
}
imshow( probabilistic_name, probabilistic_hough );

View File

@@ -14,7 +14,7 @@ using namespace cv;
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
Mat src, src_gray, dst;
@@ -22,9 +22,7 @@ int main( int argc, char** argv )
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
char* window_name = "Laplace Demo";
int c;
const char* window_name = "Laplace Demo";
/// Load an image
src = imread( argv[1] );
@@ -36,10 +34,10 @@ int main( int argc, char** argv )
GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT );
/// Convert the image to grayscale
cvtColor( src, src_gray, CV_RGB2GRAY );
cvtColor( src, src_gray, COLOR_RGB2GRAY );
/// Create window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
namedWindow( window_name, WINDOW_AUTOSIZE );
/// Apply Laplace function
Mat abs_dst;

View File

@@ -14,7 +14,7 @@ using namespace cv;
/// Global variables
Mat src, dst;
Mat map_x, map_y;
char* remap_window = "Remap demo";
const char* remap_window = "Remap demo";
int ind = 0;
/// Function Headers
@@ -23,7 +23,7 @@ void update_map( void );
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
/// Load the image
src = imread( argv[1], 1 );
@@ -34,10 +34,10 @@ int main( int argc, char** argv )
map_y.create( src.size(), CV_32FC1 );
/// Create window
namedWindow( remap_window, CV_WINDOW_AUTOSIZE );
namedWindow( remap_window, WINDOW_AUTOSIZE );
/// Loop
while( true )
for(;;)
{
/// Each 1 sec. Press ESC to exit the program
int c = waitKey( 1000 );
@@ -47,7 +47,7 @@ int main( int argc, char** argv )
/// Update map_x & map_y. Then apply remap
update_map();
remap( src, dst, map_x, map_y, CV_INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) );
remap( src, dst, map_x, map_y, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0) );
// Display results
imshow( remap_window, dst );
@@ -71,8 +71,8 @@ void update_map( void )
case 0:
if( i > src.cols*0.25 && i < src.cols*0.75 && j > src.rows*0.25 && j < src.rows*0.75 )
{
map_x.at<float>(j,i) = 2*( i - src.cols*0.25 ) + 0.5 ;
map_y.at<float>(j,i) = 2*( j - src.rows*0.25 ) + 0.5 ;
map_x.at<float>(j,i) = 2*( i - src.cols*0.25f ) + 0.5f ;
map_y.at<float>(j,i) = 2*( j - src.rows*0.25f ) + 0.5f ;
}
else
{ map_x.at<float>(j,i) = 0 ;
@@ -80,16 +80,16 @@ void update_map( void )
}
break;
case 1:
map_x.at<float>(j,i) = i ;
map_y.at<float>(j,i) = src.rows - j ;
map_x.at<float>(j,i) = (float)i ;
map_y.at<float>(j,i) = (float)(src.rows - j) ;
break;
case 2:
map_x.at<float>(j,i) = src.cols - i ;
map_y.at<float>(j,i) = j ;
map_x.at<float>(j,i) = (float)(src.cols - i) ;
map_y.at<float>(j,i) = (float)j ;
break;
case 3:
map_x.at<float>(j,i) = src.cols - i ;
map_y.at<float>(j,i) = src.rows - j ;
map_x.at<float>(j,i) = (float)(src.cols - i) ;
map_y.at<float>(j,i) = (float)(src.rows - j) ;
break;
} // end of switch
}

View File

@@ -14,18 +14,16 @@ using namespace cv;
/**
* @function main
*/
int main( int argc, char** argv )
int main( int, char** argv )
{
Mat src, src_gray;
Mat grad;
char* window_name = "Sobel Demo - Simple Edge Detector";
const char* window_name = "Sobel Demo - Simple Edge Detector";
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
int c;
/// Load an image
src = imread( argv[1] );
@@ -35,10 +33,10 @@ int main( int argc, char** argv )
GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT );
/// Convert it to gray
cvtColor( src, src_gray, CV_RGB2GRAY );
cvtColor( src, src_gray, COLOR_RGB2GRAY );
/// Create window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
namedWindow( window_name, WINDOW_AUTOSIZE );
/// Generate grad_x and grad_y
Mat grad_x, grad_y;

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