Set stricter warning rules for gcc

This commit is contained in:
Andrey Kamaev
2012-06-07 17:21:29 +00:00
parent 0395f7c63f
commit 49a1ba6038
241 changed files with 9054 additions and 8947 deletions

View File

@@ -15,7 +15,7 @@ using namespace std;
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
void help()
static void help()
{
printf( "\nThis is a camera calibration sample that calibrates 3 horizontally placed cameras together.\n"
"Usage: 3calibration\n"
@@ -34,7 +34,7 @@ void help()
static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners)
{
corners.resize(0);
for( int i = 0; i < boardSize.height; i++ )
for( int j = 0; j < boardSize.width; j++ )
corners.push_back(Point3f(float(j*squareSize),
@@ -43,7 +43,7 @@ static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point
static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
vector<vector<Point2f> > imagePoints2,
vector<vector<Point2f> > imagePoints3,
vector<vector<Point2f> > imagePoints3,
Size imageSize, Size boardSize,
float squareSize, float aspectRatio,
int flags,
@@ -53,13 +53,13 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
Mat& R12, Mat& T12, Mat& R13, Mat& T13)
{
int c, i;
// step 1: calibrate each camera individually
vector<vector<Point3f> > objpt(1);
vector<vector<Point2f> > imgpt;
calcChessboardCorners(boardSize, squareSize, objpt[0]);
vector<Mat> rvecs, tvecs;
for( c = 1; c <= 3; c++ )
{
const vector<vector<Point2f> >& imgpt0 = c == 1 ? imagePoints1 : c == 2 ? imagePoints2 : imagePoints3;
@@ -71,7 +71,7 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
imgpt.push_back(imgpt0[i]);
N += (int)imgpt0[i].size();
}
if( imgpt.size() < 3 )
{
printf("Error: not enough views for camera %d\n", c);
@@ -79,13 +79,13 @@ 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 )
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*/);
@@ -96,7 +96,7 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
return false;
}
printf("Camera %d calibration reprojection error = %g\n", c, sqrt(err/N));
if( c == 1 )
cameraMatrix1 = cameraMatrix, distCoeffs1 = distCoeffs;
else if( c == 2 )
@@ -104,18 +104,18 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
else
cameraMatrix3 = cameraMatrix, distCoeffs3 = distCoeffs;
}
vector<vector<Point2f> > imgpt_right;
// step 2: calibrate (1,2) and (3,2) pairs
for( c = 2; c <= 3; c++ )
{
const vector<vector<Point2f> >& imgpt0 = c == 2 ? imagePoints2 : imagePoints3;
imgpt.clear();
imgpt_right.clear();
int N = 0;
for( i = 0; i < (int)std::min(imagePoints1.size(), imgpt0.size()); i++ )
if( !imagePoints1.empty() && !imgpt0[i].empty() )
{
@@ -123,13 +123,13 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
imgpt_right.push_back(imgpt0[i]);
N += (int)imgpt0[i].size();
}
if( imgpt.size() < 3 )
{
printf("Error: not enough shared views for cameras 1 and %d\n", c);
return false;
}
objpt.resize(imgpt.size(),objpt[0]);
Mat cameraMatrix = c == 2 ? cameraMatrix2 : cameraMatrix3;
Mat distCoeffs = c == 2 ? distCoeffs2 : distCoeffs3;
@@ -151,7 +151,7 @@ static bool run3Calibration( vector<vector<Point2f> > imagePoints1,
R13 = R; T13 = T;
}
}
return true;
}
@@ -179,17 +179,17 @@ int main( int argc, char** argv )
float squareSize = 1.f, aspectRatio = 1.f;
const char* outputFilename = "out_camera_data.yml";
const char* inputFilename = 0;
vector<vector<Point2f> > imgpt[3];
vector<string> imageList;
if(argc < 2)
{
help();
return 1;
help();
return 1;
}
for( i = 1; i < argc; i++ )
{
const char* s = argv[i];
@@ -229,11 +229,11 @@ int main( int argc, char** argv )
else if( s[0] != '-' )
{
inputFilename = s;
}
}
else
return fprintf( stderr, "Unknown option %s", s ), -1;
}
if( !inputFilename ||
!readStringList(inputFilename, imageList) ||
imageList.size() == 0 || imageList.size() % 3 != 0 )
@@ -241,7 +241,7 @@ int main( int argc, char** argv )
printf("Error: the input image list is not specified, or can not be read, or the number of files is not divisible by 3\n");
return -1;
}
Mat view, viewGray;
Mat cameraMatrix[3], distCoeffs[3], R[3], P[3], R12, T12;
for( k = 0; k < 3; k++ )
@@ -252,13 +252,13 @@ int main( int argc, char** argv )
distCoeffs[k] = Mat_<double>::zeros(5,1);
}
Mat R13=Mat_<double>::eye(3,3), T13=Mat_<double>::zeros(3,1);
FileStorage fs;
namedWindow( "Image View", 0 );
for( k = 0; k < 3; k++ )
imgpt[k].resize(imageList.size()/3);
for( i = 0; i < (int)(imageList.size()/3); i++ )
{
for( k = 0; k < 3; k++ )
@@ -266,14 +266,14 @@ int main( int argc, char** argv )
int k1 = k == 0 ? 2 : k == 1 ? 0 : 1;
printf("%s\n", imageList[i*3+k].c_str());
view = imread(imageList[i*3+k], 1);
if(view.data)
{
vector<Point2f> ptvec;
imageSize = view.size();
cvtColor(view, viewGray, CV_BGR2GRAY);
bool found = findChessboardCorners( view, boardSize, ptvec, CV_CALIB_CB_ADAPTIVE_THRESH );
drawChessboardCorners( view, boardSize, Mat(ptvec), found );
if( found )
{
@@ -287,36 +287,36 @@ 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,
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
cameraMatrix[2], distCoeffs[2],
R12, T12, R13, T13);
fs.open(outputFilename, CV_STORAGE_WRITE);
fs << "cameraMatrix1" << cameraMatrix[0];
fs << "cameraMatrix2" << cameraMatrix[1];
fs << "cameraMatrix3" << cameraMatrix[2];
fs << "distCoeffs1" << distCoeffs[0];
fs << "distCoeffs2" << distCoeffs[1];
fs << "distCoeffs3" << distCoeffs[2];
fs << "R12" << R12;
fs << "T12" << T12;
fs << "R13" << R13;
fs << "T13" << T13;
fs << "imageWidth" << imageSize.width;
fs << "imageHeight" << imageSize.height;
Mat Q;
// step 3: find rectification transforms
double ratio = rectify3Collinear(cameraMatrix[0], distCoeffs[0], cameraMatrix[1],
distCoeffs[1], cameraMatrix[2], distCoeffs[2],
@@ -325,27 +325,27 @@ int main( int argc, char** argv )
R[0], R[1], R[2], P[0], P[1], P[2], Q, -1.,
imageSize, 0, 0, CV_CALIB_ZERO_DISPARITY);
Mat map1[3], map2[3];
fs << "R1" << R[0];
fs << "R2" << R[1];
fs << "R3" << R[2];
fs << "P1" << P[0];
fs << "P2" << P[1];
fs << "P3" << P[2];
fs << "disparityRatio" << ratio;
fs.release();
printf("Disparity ratio = %g\n", ratio);
for( k = 0; k < 3; k++ )
initUndistortRectifyMap(cameraMatrix[k], distCoeffs[k], R[k], P[k], imageSize, CV_16SC2, map1[k], map2[k]);
Mat canvas(imageSize.height, imageSize.width*3, CV_8UC3), small_canvas;
destroyWindow("view");
canvas = Scalar::all(0);
for( i = 0; i < (int)(imageList.size()/3); i++ )
{
canvas = Scalar::all(0);
@@ -354,10 +354,10 @@ int main( int argc, char** argv )
int k1 = k == 0 ? 2 : k == 1 ? 0 : 1;
int k2 = k == 0 ? 1 : k == 1 ? 0 : 2;
view = imread(imageList[i*3+k], 1);
if(!view.data)
continue;
Mat rview = canvas.colRange(k2*imageSize.width, (k2+1)*imageSize.width);
remap(view, rview, map1[k1], map2[k1], CV_INTER_LINEAR);
}
@@ -370,6 +370,6 @@ int main( int argc, char** argv )
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
return 0;
}

View File

@@ -12,266 +12,267 @@
#include "opencv2/opencv.hpp"
void help(std::string errorMessage)
static void help(std::string errorMessage)
{
std::cout<<"Program init error : "<<errorMessage<<std::endl;
std::cout<<"\nProgram call procedure : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping [OpenEXR image to process]"<<std::endl;
std::cout<<"\t[OpenEXR image to process] : the input HDR image to process, must be an OpenEXR format, see http://www.openexr.com/ to get some samples or create your own using camera bracketing and Photoshop or equivalent software for OpenEXR image synthesis"<<std::endl;
std::cout<<"\nExamples:"<<std::endl;
std::cout<<"\t-Image processing : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping memorial.exr"<<std::endl;
std::cout<<"Program init error : "<<errorMessage<<std::endl;
std::cout<<"\nProgram call procedure : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping [OpenEXR image to process]"<<std::endl;
std::cout<<"\t[OpenEXR image to process] : the input HDR image to process, must be an OpenEXR format, see http://www.openexr.com/ to get some samples or create your own using camera bracketing and Photoshop or equivalent software for OpenEXR image synthesis"<<std::endl;
std::cout<<"\nExamples:"<<std::endl;
std::cout<<"\t-Image processing : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping memorial.exr"<<std::endl;
}
// simple procedure for 1D curve tracing
void drawPlot(const cv::Mat curve, const std::string figureTitle, const int lowerLimit, const int upperLimit)
static void drawPlot(const cv::Mat curve, const std::string figureTitle, const int lowerLimit, const int upperLimit)
{
//std::cout<<"curve size(h,w) = "<<curve.size().height<<", "<<curve.size().width<<std::endl;
cv::Mat displayedCurveImage = cv::Mat::ones(200, curve.size().height, CV_8U);
//std::cout<<"curve size(h,w) = "<<curve.size().height<<", "<<curve.size().width<<std::endl;
cv::Mat displayedCurveImage = cv::Mat::ones(200, curve.size().height, CV_8U);
cv::Mat windowNormalizedCurve;
normalize(curve, windowNormalizedCurve, 0, 200, CV_MINMAX, CV_32F);
cv::Mat windowNormalizedCurve;
normalize(curve, windowNormalizedCurve, 0, 200, CV_MINMAX, CV_32F);
displayedCurveImage = cv::Scalar::all(255); // set a white background
int binW = cvRound((double)displayedCurveImage.cols/curve.size().height);
displayedCurveImage = cv::Scalar::all(255); // set a white background
int binW = cvRound((double)displayedCurveImage.cols/curve.size().height);
for( int i = 0; i < curve.size().height; i++ )
rectangle( displayedCurveImage, cv::Point(i*binW, displayedCurveImage.rows),
cv::Point((i+1)*binW, displayedCurveImage.rows - cvRound(windowNormalizedCurve.at<float>(i))),
cv::Scalar::all(0), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(0, 0),
cv::Point((lowerLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(displayedCurveImage.cols, 0),
cv::Point((upperLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
for( int i = 0; i < curve.size().height; i++ )
rectangle( displayedCurveImage, cv::Point(i*binW, displayedCurveImage.rows),
cv::Point((i+1)*binW, displayedCurveImage.rows - cvRound(windowNormalizedCurve.at<float>(i))),
cv::Scalar::all(0), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(0, 0),
cv::Point((lowerLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(displayedCurveImage.cols, 0),
cv::Point((upperLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
cv::imshow(figureTitle, displayedCurveImage);
cv::imshow(figureTitle, displayedCurveImage);
}
/*
* objective : get the gray level map of the input image and rescale it to the range [0-255]
*/void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, const float histogramClippingLimit)
*/
static void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, const float histogramClippingLimit)
{
// adjust output matrix wrt the input size but single channel
std::cout<<"Input image rescaling with histogram edges cutting (in order to eliminate bad pixels created during the HDR image creation) :"<<std::endl;
//std::cout<<"=> image size (h,w,channels) = "<<inputMat.size().height<<", "<<inputMat.size().width<<", "<<inputMat.channels()<<std::endl;
//std::cout<<"=> pixel coding (nbchannel, bytes per channel) = "<<inputMat.elemSize()/inputMat.elemSize1()<<", "<<inputMat.elemSize1()<<std::endl;
// adjust output matrix wrt the input size but single channel
std::cout<<"Input image rescaling with histogram edges cutting (in order to eliminate bad pixels created during the HDR image creation) :"<<std::endl;
//std::cout<<"=> image size (h,w,channels) = "<<inputMat.size().height<<", "<<inputMat.size().width<<", "<<inputMat.channels()<<std::endl;
//std::cout<<"=> pixel coding (nbchannel, bytes per channel) = "<<inputMat.elemSize()/inputMat.elemSize1()<<", "<<inputMat.elemSize1()<<std::endl;
// rescale between 0-255, keeping floating point values
cv::normalize(inputMat, outputMat, 0.0, 255.0, cv::NORM_MINMAX);
// rescale between 0-255, keeping floating point values
cv::normalize(inputMat, outputMat, 0.0, 255.0, cv::NORM_MINMAX);
// extract a 8bit image that will be used for histogram edge cut
cv::Mat intGrayImage;
if (inputMat.channels()==1)
{
outputMat.convertTo(intGrayImage, CV_8U);
}else
{
cv::Mat rgbIntImg;
outputMat.convertTo(rgbIntImg, CV_8UC3);
cvtColor(rgbIntImg, intGrayImage, CV_BGR2GRAY);
}
// extract a 8bit image that will be used for histogram edge cut
cv::Mat intGrayImage;
if (inputMat.channels()==1)
{
outputMat.convertTo(intGrayImage, CV_8U);
}else
{
cv::Mat rgbIntImg;
outputMat.convertTo(rgbIntImg, CV_8UC3);
cvtColor(rgbIntImg, intGrayImage, CV_BGR2GRAY);
}
// get histogram density probability in order to cut values under above edges limits (here 5-95%)... usefull for HDR pixel errors cancellation
cv::Mat dst, hist;
int histSize = 256;
calcHist(&intGrayImage, 1, 0, cv::Mat(), hist, 1, &histSize, 0);
cv::Mat normalizedHist;
normalize(hist, normalizedHist, 1, 0, cv::NORM_L1, CV_32F); // normalize histogram so that its sum equals 1
// get histogram density probability in order to cut values under above edges limits (here 5-95%)... usefull for HDR pixel errors cancellation
cv::Mat dst, hist;
int histSize = 256;
calcHist(&intGrayImage, 1, 0, cv::Mat(), hist, 1, &histSize, 0);
cv::Mat normalizedHist;
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);
//std::cout<<"Hist max,min = "<<max_val<<", "<<min_val<<std::endl;
double min_val, max_val;
CvMat histArr(normalizedHist);
cvMinMaxLoc(&histArr, &min_val, &max_val);
//std::cout<<"Hist max,min = "<<max_val<<", "<<min_val<<std::endl;
// compute density probability
cv::Mat denseProb=cv::Mat::zeros(normalizedHist.size(), CV_32F);
denseProb.at<float>(0)=normalizedHist.at<float>(0);
int histLowerLimit=0, histUpperLimit=0;
for (int i=1;i<normalizedHist.size().height;++i)
{
denseProb.at<float>(i)=denseProb.at<float>(i-1)+normalizedHist.at<float>(i);
//std::cout<<normalizedHist.at<float>(i)<<", "<<denseProb.at<float>(i)<<std::endl;
if ( denseProb.at<float>(i)<histogramClippingLimit)
histLowerLimit=i;
if ( denseProb.at<float>(i)<1-histogramClippingLimit)
histUpperLimit=i;
}
// deduce min and max admitted gray levels
float minInputValue = (float)histLowerLimit/histSize*255;
float maxInputValue = (float)histUpperLimit/histSize*255;
// compute density probability
cv::Mat denseProb=cv::Mat::zeros(normalizedHist.size(), CV_32F);
denseProb.at<float>(0)=normalizedHist.at<float>(0);
int histLowerLimit=0, histUpperLimit=0;
for (int i=1;i<normalizedHist.size().height;++i)
{
denseProb.at<float>(i)=denseProb.at<float>(i-1)+normalizedHist.at<float>(i);
//std::cout<<normalizedHist.at<float>(i)<<", "<<denseProb.at<float>(i)<<std::endl;
if ( denseProb.at<float>(i)<histogramClippingLimit)
histLowerLimit=i;
if ( denseProb.at<float>(i)<1-histogramClippingLimit)
histUpperLimit=i;
}
// deduce min and max admitted gray levels
float minInputValue = (float)histLowerLimit/histSize*255;
float maxInputValue = (float)histUpperLimit/histSize*255;
std::cout<<"=> Histogram limits "
<<"\n\t"<<histogramClippingLimit*100<<"% index = "<<histLowerLimit<<" => normalizedHist value = "<<denseProb.at<float>(histLowerLimit)<<" => input gray level = "<<minInputValue
<<"\n\t"<<(1-histogramClippingLimit)*100<<"% index = "<<histUpperLimit<<" => normalizedHist value = "<<denseProb.at<float>(histUpperLimit)<<" => input gray level = "<<maxInputValue
<<std::endl;
//drawPlot(denseProb, "input histogram density probability", histLowerLimit, histUpperLimit);
drawPlot(normalizedHist, "input histogram", histLowerLimit, histUpperLimit);
std::cout<<"=> Histogram limits "
<<"\n\t"<<histogramClippingLimit*100<<"% index = "<<histLowerLimit<<" => normalizedHist value = "<<denseProb.at<float>(histLowerLimit)<<" => input gray level = "<<minInputValue
<<"\n\t"<<(1-histogramClippingLimit)*100<<"% index = "<<histUpperLimit<<" => normalizedHist value = "<<denseProb.at<float>(histUpperLimit)<<" => input gray level = "<<maxInputValue
<<std::endl;
//drawPlot(denseProb, "input histogram density probability", histLowerLimit, histUpperLimit);
drawPlot(normalizedHist, "input histogram", histLowerLimit, histUpperLimit);
// rescale image range [minInputValue-maxInputValue] to [0-255]
outputMat-=minInputValue;
outputMat*=255.0/(maxInputValue-minInputValue);
// cut original histogram and back project to original image
cv::threshold( outputMat, outputMat, 255.0, 255.0, 2 ); //THRESH_TRUNC, clips values above 255
cv::threshold( outputMat, outputMat, 0.0, 0.0, 3 ); //THRESH_TOZERO, clips values under 0
// rescale image range [minInputValue-maxInputValue] to [0-255]
outputMat-=minInputValue;
outputMat*=255.0/(maxInputValue-minInputValue);
// cut original histogram and back project to original image
cv::threshold( outputMat, outputMat, 255.0, 255.0, 2 ); //THRESH_TRUNC, clips values above 255
cv::threshold( outputMat, outputMat, 0.0, 0.0, 3 ); //THRESH_TOZERO, clips values under 0
}
// basic callback method for interface management
cv::Mat inputImage;
cv::Mat imageInputRescaled;
int histogramClippingValue;
void callBack_rescaleGrayLevelMat(int, void*)
static void callBack_rescaleGrayLevelMat(int, void*)
{
std::cout<<"Histogram clipping value changed, current value = "<<histogramClippingValue<<std::endl;
rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)(histogramClippingValue/100.0));
normalize(imageInputRescaled, imageInputRescaled, 0.0, 255.0, cv::NORM_MINMAX);
std::cout<<"Histogram clipping value changed, current value = "<<histogramClippingValue<<std::endl;
rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)(histogramClippingValue/100.0));
normalize(imageInputRescaled, imageInputRescaled, 0.0, 255.0, cv::NORM_MINMAX);
}
cv::Ptr<cv::Retina> retina;
int retinaHcellsGain;
int localAdaptation_photoreceptors, localAdaptation_Gcells;
void callBack_updateRetinaParams(int, void*)
static void callBack_updateRetinaParams(int, void*)
{
retina->setupOPLandIPLParvoChannel(true, true, (float)(localAdaptation_photoreceptors/200.0), 0.5f, 0.43f, (float)retinaHcellsGain, 1.f, 7.f, (float)(localAdaptation_Gcells/200.0));
retina->setupOPLandIPLParvoChannel(true, true, (float)(localAdaptation_photoreceptors/200.0), 0.5f, 0.43f, (float)retinaHcellsGain, 1.f, 7.f, (float)(localAdaptation_Gcells/200.0));
}
int colorSaturationFactor;
void callback_saturateColors(int, void*)
static void callback_saturateColors(int, void*)
{
retina->setColorSaturation(true, (float)colorSaturationFactor);
retina->setColorSaturation(true, (float)colorSaturationFactor);
}
int main(int argc, char* argv[]) {
// welcome message
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"* Retina demonstration for High Dynamic Range compression (tone-mapping) : demonstrates the use of a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl;
std::cout<<"* This demo focuses demonstration of the dynamic compression capabilities of the model"<<std::endl;
std::cout<<"* => the main application is tone mapping of HDR images (i.e. see on a 8bit display a more than 8bits coded (up to 16bits) image with details in high and low luminance ranges"<<std::endl;
std::cout<<"* The retina model still have the following properties:"<<std::endl;
std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl;
std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl;
std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl;
std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl;
std::cout<<"* for more information, reer to the following papers :"<<std::endl;
std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl;
std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl;
std::cout<<"* => reports comments/remarks at benoit.alexandre.vision@gmail.com"<<std::endl;
std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"** WARNING : this sample requires OpenCV to be configured with OpenEXR support **"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"*** You can use free tools to generate OpenEXR images from images sets : ***"<<std::endl;
std::cout<<"*** => 1. take a set of photos from the same viewpoint using bracketing ***"<<std::endl;
std::cout<<"*** => 2. generate an OpenEXR image with tools like qtpfsgui.sourceforge.net ***"<<std::endl;
std::cout<<"*** => 3. apply tone mapping with this program ***"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
// welcome message
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"* Retina demonstration for High Dynamic Range compression (tone-mapping) : demonstrates the use of a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl;
std::cout<<"* This demo focuses demonstration of the dynamic compression capabilities of the model"<<std::endl;
std::cout<<"* => the main application is tone mapping of HDR images (i.e. see on a 8bit display a more than 8bits coded (up to 16bits) image with details in high and low luminance ranges"<<std::endl;
std::cout<<"* The retina model still have the following properties:"<<std::endl;
std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl;
std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl;
std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl;
std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl;
std::cout<<"* for more information, reer to the following papers :"<<std::endl;
std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl;
std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl;
std::cout<<"* => reports comments/remarks at benoit.alexandre.vision@gmail.com"<<std::endl;
std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"** WARNING : this sample requires OpenCV to be configured with OpenEXR support **"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"*** You can use free tools to generate OpenEXR images from images sets : ***"<<std::endl;
std::cout<<"*** => 1. take a set of photos from the same viewpoint using bracketing ***"<<std::endl;
std::cout<<"*** => 2. generate an OpenEXR image with tools like qtpfsgui.sourceforge.net ***"<<std::endl;
std::cout<<"*** => 3. apply tone mapping with this program ***"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
// basic input arguments checking
if (argc<2)
{
help("bad number of parameter");
return -1;
}
// basic input arguments checking
if (argc<2)
{
help("bad number of parameter");
return -1;
}
bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
std::string inputImageName=argv[1];
std::string inputImageName=argv[1];
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
std::cout<<"RetinaDemo: processing image "<<inputImageName<<std::endl;
// image processing case
// declare the retina input buffer... that will be fed differently in regard of the input media
inputImage = cv::imread(inputImageName, -1); // load image in RGB mode
std::cout<<"=> image size (h,w) = "<<inputImage.size().height<<", "<<inputImage.size().width<<std::endl;
if (!inputImage.total())
{
help("could not load image, program end");
return -1;
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
std::cout<<"RetinaDemo: processing image "<<inputImageName<<std::endl;
// image processing case
// declare the retina input buffer... that will be fed differently in regard of the input media
inputImage = cv::imread(inputImageName, -1); // load image in RGB mode
std::cout<<"=> image size (h,w) = "<<inputImage.size().height<<", "<<inputImage.size().width<<std::endl;
if (!inputImage.total())
{
help("could not load image, program end");
return -1;
}
// rescale between 0 and 1
normalize(inputImage, inputImage, 0.0, 1.0, cv::NORM_MINMAX);
cv::Mat gammaTransformedImage;
cv::pow(inputImage, 1./5, gammaTransformedImage); // apply gamma curve: img = img ** (1./5)
imshow("EXR image original image, 16bits=>8bits linear rescaling ", inputImage);
imshow("EXR image with basic processing : 16bits=>8bits with gamma correction", gammaTransformedImage);
if (inputImage.empty())
{
help("Input image could not be loaded, aborting");
return -1;
}
// rescale between 0 and 1
normalize(inputImage, inputImage, 0.0, 1.0, cv::NORM_MINMAX);
cv::Mat gammaTransformedImage;
cv::pow(inputImage, 1./5, gammaTransformedImage); // apply gamma curve: img = img ** (1./5)
imshow("EXR image original image, 16bits=>8bits linear rescaling ", inputImage);
imshow("EXR image with basic processing : 16bits=>8bits with gamma correction", gammaTransformedImage);
if (inputImage.empty())
{
help("Input image could not be loaded, aborting");
return -1;
}
//////////////////////////////////////////////////////////////////////////////
// Program start in a try/catch safety context (Retina may throw errors)
try
{
/* create a retina instance with default parameters setup, uncomment the initialisation you wanna test
* -> if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
*/
if (useLogSampling)
//////////////////////////////////////////////////////////////////////////////
// Program start in a try/catch safety context (Retina may throw errors)
try
{
/* create a retina instance with default parameters setup, uncomment the initialisation you wanna test
* -> if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
*/
if (useLogSampling)
{
retina = new cv::Retina(inputImage.size(),true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0);
}
else// -> else allocate "classical" retina :
retina = new cv::Retina(inputImage.size());
// save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
retina->write("RetinaDefaultParameters.xml");
else// -> else allocate "classical" retina :
retina = new cv::Retina(inputImage.size());
// save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
retina->write("RetinaDefaultParameters.xml");
// desactivate Magnocellular pathway processing (motion information extraction) since it is not usefull here
retina->activateMovingContoursProcessing(false);
// declare retina output buffers
cv::Mat retinaOutput_parvo;
// declare retina output buffers
cv::Mat retinaOutput_parvo;
/////////////////////////////////////////////
// prepare displays and interactions
histogramClippingValue=0; // default value... updated with interface slider
//inputRescaleMat = inputImage;
//outputRescaleMat = imageInputRescaled;
cv::namedWindow("Retina input image (with cut edges histogram for basic pixels error avoidance)",1);
cv::createTrackbar("histogram edges clipping limit", "Retina input image (with cut edges histogram for basic pixels error avoidance)",&histogramClippingValue,50,callBack_rescaleGrayLevelMat);
/////////////////////////////////////////////
// prepare displays and interactions
histogramClippingValue=0; // default value... updated with interface slider
//inputRescaleMat = inputImage;
//outputRescaleMat = imageInputRescaled;
cv::namedWindow("Retina input image (with cut edges histogram for basic pixels error avoidance)",1);
cv::createTrackbar("histogram edges clipping limit", "Retina input image (with cut edges histogram for basic pixels error avoidance)",&histogramClippingValue,50,callBack_rescaleGrayLevelMat);
cv::namedWindow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", 1);
colorSaturationFactor=3;
cv::createTrackbar("Color saturation", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &colorSaturationFactor,5,callback_saturateColors);
cv::namedWindow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", 1);
colorSaturationFactor=3;
cv::createTrackbar("Color saturation", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &colorSaturationFactor,5,callback_saturateColors);
retinaHcellsGain=40;
cv::createTrackbar("Hcells gain", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping",&retinaHcellsGain,100,callBack_updateRetinaParams);
retinaHcellsGain=40;
cv::createTrackbar("Hcells gain", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping",&retinaHcellsGain,100,callBack_updateRetinaParams);
localAdaptation_photoreceptors=197;
localAdaptation_Gcells=190;
cv::createTrackbar("Ph sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams);
cv::createTrackbar("Gcells sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_Gcells,199,callBack_updateRetinaParams);
localAdaptation_photoreceptors=197;
localAdaptation_Gcells=190;
cv::createTrackbar("Ph sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams);
cv::createTrackbar("Gcells sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_Gcells,199,callBack_updateRetinaParams);
/////////////////////////////////////////////
// apply default parameters of user interaction variables
rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)histogramClippingValue/100);
retina->setColorSaturation(true,(float)colorSaturationFactor);
callBack_updateRetinaParams(1,NULL); // first call for default parameters setup
/////////////////////////////////////////////
// apply default parameters of user interaction variables
rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)histogramClippingValue/100);
retina->setColorSaturation(true,(float)colorSaturationFactor);
callBack_updateRetinaParams(1,NULL); // first call for default parameters setup
// processing loop with stop condition
bool continueProcessing=true;
while(continueProcessing)
{
// run retina filter
retina->run(imageInputRescaled);
// Retrieve and display retina output
retina->getParvo(retinaOutput_parvo);
cv::imshow("Retina input image (with cut edges histogram for basic pixels error avoidance)", imageInputRescaled/255.0);
cv::imshow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", retinaOutput_parvo);
cv::waitKey(10);
}
}catch(cv::Exception e)
{
std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
}
// processing loop with stop condition
bool continueProcessing=true;
while(continueProcessing)
{
// run retina filter
retina->run(imageInputRescaled);
// Retrieve and display retina output
retina->getParvo(retinaOutput_parvo);
cv::imshow("Retina input image (with cut edges histogram for basic pixels error avoidance)", imageInputRescaled/255.0);
cv::imshow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", retinaOutput_parvo);
cv::waitKey(10);
}
}catch(cv::Exception e)
{
std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
}
// Program end message
std::cout<<"Retina demo end"<<std::endl;
// Program end message
std::cout<<"Retina demo end"<<std::endl;
return 0;
return 0;
}

View File

@@ -7,7 +7,7 @@
// Description : HighDynamicRange compression (tone mapping) for image sequences with the help of the Gipsa/Listic's retina in C++, Ansi-style
// Known issues: the input OpenEXR sequences can have bad computed pixels that should be removed
// => a simple method consists of cutting histogram edges (a slider for this on the UI is provided)
// => however, in image sequences, this histogramm cut must be done in an elegant way from frame to frame... still not done...
// => however, in image sequences, this histogramm cut must be done in an elegant way from frame to frame... still not done...
//============================================================================
#include <iostream>
@@ -16,130 +16,130 @@
#include "opencv2/opencv.hpp"
void help(std::string errorMessage)
static void help(std::string errorMessage)
{
std::cout<<"Program init error : "<<errorMessage<<std::endl;
std::cout<<"\nProgram call procedure : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping [OpenEXR image sequence to process] [OPTIONNAL start frame] [OPTIONNAL end frame]"<<std::endl;
std::cout<<"\t[OpenEXR image sequence to process] : std::sprintf style ready prototype filename of the input HDR images to process, must be an OpenEXR format, see http://www.openexr.com/ to get some samples or create your own using camera bracketing and Photoshop or equivalent software for OpenEXR image synthesis"<<std::endl;
std::cout<<"\t\t => WARNING : image index number of digits cannot exceed 10"<<std::endl;
std::cout<<"\t[start frame] : the starting frame tat should be considered"<<std::endl;
std::cout<<"\t[end frame] : the ending frame tat should be considered"<<std::endl;
std::cout<<"\nExamples:"<<std::endl;
std::cout<<"\t-Image processing : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping_video memorial%3d.exr 20 45"<<std::endl;
std::cout<<"\t-Image processing : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping_video memorial%3d.exr 20 45 log"<<std::endl;
std::cout<<"\t ==> to process images from memorial020d.exr to memorial045d.exr"<<std::endl;
std::cout<<"Program init error : "<<errorMessage<<std::endl;
std::cout<<"\nProgram call procedure : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping [OpenEXR image sequence to process] [OPTIONNAL start frame] [OPTIONNAL end frame]"<<std::endl;
std::cout<<"\t[OpenEXR image sequence to process] : std::sprintf style ready prototype filename of the input HDR images to process, must be an OpenEXR format, see http://www.openexr.com/ to get some samples or create your own using camera bracketing and Photoshop or equivalent software for OpenEXR image synthesis"<<std::endl;
std::cout<<"\t\t => WARNING : image index number of digits cannot exceed 10"<<std::endl;
std::cout<<"\t[start frame] : the starting frame tat should be considered"<<std::endl;
std::cout<<"\t[end frame] : the ending frame tat should be considered"<<std::endl;
std::cout<<"\nExamples:"<<std::endl;
std::cout<<"\t-Image processing : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping_video memorial%3d.exr 20 45"<<std::endl;
std::cout<<"\t-Image processing : ./OpenEXRimages_HighDynamicRange_Retina_toneMapping_video memorial%3d.exr 20 45 log"<<std::endl;
std::cout<<"\t ==> to process images from memorial020d.exr to memorial045d.exr"<<std::endl;
}
// simple procedure for 1D curve tracing
void drawPlot(const cv::Mat curve, const std::string figureTitle, const int lowerLimit, const int upperLimit)
static void drawPlot(const cv::Mat curve, const std::string figureTitle, const int lowerLimit, const int upperLimit)
{
//std::cout<<"curve size(h,w) = "<<curve.size().height<<", "<<curve.size().width<<std::endl;
cv::Mat displayedCurveImage = cv::Mat::ones(200, curve.size().height, CV_8U);
//std::cout<<"curve size(h,w) = "<<curve.size().height<<", "<<curve.size().width<<std::endl;
cv::Mat displayedCurveImage = cv::Mat::ones(200, curve.size().height, CV_8U);
cv::Mat windowNormalizedCurve;
normalize(curve, windowNormalizedCurve, 0, 200, CV_MINMAX, CV_32F);
cv::Mat windowNormalizedCurve;
normalize(curve, windowNormalizedCurve, 0, 200, CV_MINMAX, CV_32F);
displayedCurveImage = cv::Scalar::all(255); // set a white background
int binW = cvRound((double)displayedCurveImage.cols/curve.size().height);
displayedCurveImage = cv::Scalar::all(255); // set a white background
int binW = cvRound((double)displayedCurveImage.cols/curve.size().height);
for( int i = 0; i < curve.size().height; i++ )
rectangle( displayedCurveImage, cv::Point(i*binW, displayedCurveImage.rows),
cv::Point((i+1)*binW, displayedCurveImage.rows - cvRound(windowNormalizedCurve.at<float>(i))),
cv::Scalar::all(0), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(0, 0),
cv::Point((lowerLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(displayedCurveImage.cols, 0),
cv::Point((upperLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
for( int i = 0; i < curve.size().height; i++ )
rectangle( displayedCurveImage, cv::Point(i*binW, displayedCurveImage.rows),
cv::Point((i+1)*binW, displayedCurveImage.rows - cvRound(windowNormalizedCurve.at<float>(i))),
cv::Scalar::all(0), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(0, 0),
cv::Point((lowerLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
rectangle( displayedCurveImage, cv::Point(displayedCurveImage.cols, 0),
cv::Point((upperLimit)*binW, 200),
cv::Scalar::all(128), -1, 8, 0 );
cv::imshow(figureTitle, displayedCurveImage);
cv::imshow(figureTitle, displayedCurveImage);
}
/*
* objective : get the gray level map of the input image and rescale it to the range [0-255] if rescale0_255=TRUE, simply trunks else
*/
void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, const float histogramClippingLimit, const bool rescale0_255)
static void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, const float histogramClippingLimit, const bool rescale0_255)
{
// adjust output matrix wrt the input size but single channel
std::cout<<"Input image rescaling with histogram edges cutting (in order to eliminate bad pixels created during the HDR image creation) :"<<std::endl;
//std::cout<<"=> image size (h,w,channels) = "<<inputMat.size().height<<", "<<inputMat.size().width<<", "<<inputMat.channels()<<std::endl;
//std::cout<<"=> pixel coding (nbchannel, bytes per channel) = "<<inputMat.elemSize()/inputMat.elemSize1()<<", "<<inputMat.elemSize1()<<std::endl;
// adjust output matrix wrt the input size but single channel
std::cout<<"Input image rescaling with histogram edges cutting (in order to eliminate bad pixels created during the HDR image creation) :"<<std::endl;
//std::cout<<"=> image size (h,w,channels) = "<<inputMat.size().height<<", "<<inputMat.size().width<<", "<<inputMat.channels()<<std::endl;
//std::cout<<"=> pixel coding (nbchannel, bytes per channel) = "<<inputMat.elemSize()/inputMat.elemSize1()<<", "<<inputMat.elemSize1()<<std::endl;
// get min and max values to use afterwards if no 0-255 rescaling is used
double maxInput, minInput, histNormRescalefactor=1.f;
double histNormOffset=0.f;
minMaxLoc(inputMat, &minInput, &maxInput);
histNormRescalefactor=255.f/(maxInput-minInput);
histNormOffset=minInput;
std::cout<<"Hist max,min = "<<maxInput<<", "<<minInput<<" => scale, offset = "<<histNormRescalefactor<<", "<<histNormOffset<<std::endl;
// rescale between 0-255, keeping floating point values
cv::Mat normalisedImage;
cv::normalize(inputMat, normalisedImage, 0.f, 255.f, cv::NORM_MINMAX);
if (rescale0_255)
normalisedImage.copyTo(outputMat);
// extract a 8bit image that will be used for histogram edge cut
cv::Mat intGrayImage;
if (inputMat.channels()==1)
{
normalisedImage.convertTo(intGrayImage, CV_8U);
}else
{
cv::Mat rgbIntImg;
normalisedImage.convertTo(rgbIntImg, CV_8UC3);
cvtColor(rgbIntImg, intGrayImage, CV_BGR2GRAY);
}
// get min and max values to use afterwards if no 0-255 rescaling is used
double maxInput, minInput, histNormRescalefactor=1.f;
double histNormOffset=0.f;
minMaxLoc(inputMat, &minInput, &maxInput);
histNormRescalefactor=255.f/(maxInput-minInput);
histNormOffset=minInput;
std::cout<<"Hist max,min = "<<maxInput<<", "<<minInput<<" => scale, offset = "<<histNormRescalefactor<<", "<<histNormOffset<<std::endl;
// rescale between 0-255, keeping floating point values
cv::Mat normalisedImage;
cv::normalize(inputMat, normalisedImage, 0.f, 255.f, cv::NORM_MINMAX);
if (rescale0_255)
normalisedImage.copyTo(outputMat);
// extract a 8bit image that will be used for histogram edge cut
cv::Mat intGrayImage;
if (inputMat.channels()==1)
{
normalisedImage.convertTo(intGrayImage, CV_8U);
}else
{
cv::Mat rgbIntImg;
normalisedImage.convertTo(rgbIntImg, CV_8UC3);
cvtColor(rgbIntImg, intGrayImage, CV_BGR2GRAY);
}
// get histogram density probability in order to cut values under above edges limits (here 5-95%)... usefull for HDR pixel errors cancellation
cv::Mat dst, hist;
int histSize = 256;
calcHist(&intGrayImage, 1, 0, cv::Mat(), hist, 1, &histSize, 0);
cv::Mat normalizedHist;
normalize(hist, normalizedHist, 1.f, 0.f, cv::NORM_L1, CV_32F); // normalize histogram so that its sum equals 1
// get histogram density probability in order to cut values under above edges limits (here 5-95%)... usefull for HDR pixel errors cancellation
cv::Mat dst, hist;
int histSize = 256;
calcHist(&intGrayImage, 1, 0, cv::Mat(), hist, 1, &histSize, 0);
cv::Mat normalizedHist;
// compute density probability
cv::Mat denseProb=cv::Mat::zeros(normalizedHist.size(), CV_32F);
denseProb.at<float>(0)=normalizedHist.at<float>(0);
int histLowerLimit=0, histUpperLimit=0;
for (int i=1;i<normalizedHist.size().height;++i)
{
denseProb.at<float>(i)=denseProb.at<float>(i-1)+normalizedHist.at<float>(i);
//std::cout<<normalizedHist.at<float>(i)<<", "<<denseProb.at<float>(i)<<std::endl;
if ( denseProb.at<float>(i)<histogramClippingLimit)
histLowerLimit=i;
if ( denseProb.at<float>(i)<1.f-histogramClippingLimit)
histUpperLimit=i;
}
// deduce min and max admitted gray levels
float minInputValue = (float)histLowerLimit/histSize*255.f;
float maxInputValue = (float)histUpperLimit/histSize*255.f;
normalize(hist, normalizedHist, 1.f, 0.f, cv::NORM_L1, CV_32F); // normalize histogram so that its sum equals 1
std::cout<<"=> Histogram limits "
<<"\n\t"<<histogramClippingLimit*100.f<<"% index = "<<histLowerLimit<<" => normalizedHist value = "<<denseProb.at<float>(histLowerLimit)<<" => input gray level = "<<minInputValue
<<"\n\t"<<(1.f-histogramClippingLimit)*100.f<<"% index = "<<histUpperLimit<<" => normalizedHist value = "<<denseProb.at<float>(histUpperLimit)<<" => input gray level = "<<maxInputValue
<<std::endl;
//drawPlot(denseProb, "input histogram density probability", histLowerLimit, histUpperLimit);
drawPlot(normalizedHist, "input histogram", histLowerLimit, histUpperLimit);
// compute density probability
cv::Mat denseProb=cv::Mat::zeros(normalizedHist.size(), CV_32F);
denseProb.at<float>(0)=normalizedHist.at<float>(0);
int histLowerLimit=0, histUpperLimit=0;
for (int i=1;i<normalizedHist.size().height;++i)
{
denseProb.at<float>(i)=denseProb.at<float>(i-1)+normalizedHist.at<float>(i);
//std::cout<<normalizedHist.at<float>(i)<<", "<<denseProb.at<float>(i)<<std::endl;
if ( denseProb.at<float>(i)<histogramClippingLimit)
histLowerLimit=i;
if ( denseProb.at<float>(i)<1.f-histogramClippingLimit)
histUpperLimit=i;
}
// deduce min and max admitted gray levels
float minInputValue = (float)histLowerLimit/histSize*255.f;
float maxInputValue = (float)histUpperLimit/histSize*255.f;
if(rescale0_255) // rescale between 0-255 if asked to
{
cv::threshold( outputMat, outputMat, maxInputValue, maxInputValue, 2 ); //THRESH_TRUNC, clips values above maxInputValue
cv::threshold( outputMat, outputMat, minInputValue, minInputValue, 3 ); //THRESH_TOZERO, clips values under minInputValue
// rescale image range [minInputValue-maxInputValue] to [0-255]
outputMat-=minInputValue;
outputMat*=255.f/(maxInputValue-minInputValue);
}else
{
inputMat.copyTo(outputMat);
// update threshold in the initial input image range
maxInputValue=(float)((maxInputValue-255.f)/histNormRescalefactor+maxInput);
minInputValue=(float)(minInputValue/histNormRescalefactor+minInput);
std::cout<<"===> Input Hist clipping values (max,min) = "<<maxInputValue<<", "<<minInputValue<<std::endl;
cv::threshold( outputMat, outputMat, maxInputValue, maxInputValue, 2 ); //THRESH_TRUNC, clips values above maxInputValue
cv::threshold( outputMat, outputMat, minInputValue, minInputValue, 3 ); //
}
std::cout<<"=> Histogram limits "
<<"\n\t"<<histogramClippingLimit*100.f<<"% index = "<<histLowerLimit<<" => normalizedHist value = "<<denseProb.at<float>(histLowerLimit)<<" => input gray level = "<<minInputValue
<<"\n\t"<<(1.f-histogramClippingLimit)*100.f<<"% index = "<<histUpperLimit<<" => normalizedHist value = "<<denseProb.at<float>(histUpperLimit)<<" => input gray level = "<<maxInputValue
<<std::endl;
//drawPlot(denseProb, "input histogram density probability", histLowerLimit, histUpperLimit);
drawPlot(normalizedHist, "input histogram", histLowerLimit, histUpperLimit);
if(rescale0_255) // rescale between 0-255 if asked to
{
cv::threshold( outputMat, outputMat, maxInputValue, maxInputValue, 2 ); //THRESH_TRUNC, clips values above maxInputValue
cv::threshold( outputMat, outputMat, minInputValue, minInputValue, 3 ); //THRESH_TOZERO, clips values under minInputValue
// rescale image range [minInputValue-maxInputValue] to [0-255]
outputMat-=minInputValue;
outputMat*=255.f/(maxInputValue-minInputValue);
}else
{
inputMat.copyTo(outputMat);
// update threshold in the initial input image range
maxInputValue=(float)((maxInputValue-255.f)/histNormRescalefactor+maxInput);
minInputValue=(float)(minInputValue/histNormRescalefactor+minInput);
std::cout<<"===> Input Hist clipping values (max,min) = "<<maxInputValue<<", "<<minInputValue<<std::endl;
cv::threshold( outputMat, outputMat, maxInputValue, maxInputValue, 2 ); //THRESH_TRUNC, clips values above maxInputValue
cv::threshold( outputMat, outputMat, minInputValue, minInputValue, 3 ); //
}
}
// basic callback method for interface management
@@ -148,213 +148,213 @@ void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, const floa
float globalRescalefactor=1;
cv::Scalar globalOffset=0;
int histogramClippingValue;
void callBack_rescaleGrayLevelMat(int, void*)
static void callBack_rescaleGrayLevelMat(int, void*)
{
std::cout<<"Histogram clipping value changed, current value = "<<histogramClippingValue<<std::endl;
// rescale and process
inputImage+=globalOffset;
inputImage*=globalRescalefactor;
inputImage+=cv::Scalar(50, 50, 50, 50); // WARNING value linked to the hardcoded value (200.0) used in the globalRescalefactor in order to center on the 128 mean value... experimental but... basic compromise
rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)histogramClippingValue/100.f, true);
std::cout<<"Histogram clipping value changed, current value = "<<histogramClippingValue<<std::endl;
// rescale and process
inputImage+=globalOffset;
inputImage*=globalRescalefactor;
inputImage+=cv::Scalar(50, 50, 50, 50); // WARNING value linked to the hardcoded value (200.0) used in the globalRescalefactor in order to center on the 128 mean value... experimental but... basic compromise
rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)histogramClippingValue/100.f, true);
}
cv::Ptr<cv::Retina> retina;
int retinaHcellsGain;
int localAdaptation_photoreceptors, localAdaptation_Gcells;
void callBack_updateRetinaParams(int, void*)
static void callBack_updateRetinaParams(int, void*)
{
retina->setupOPLandIPLParvoChannel(true, true, (float)(localAdaptation_photoreceptors/200.0), 0.5f, 0.43f, (float)retinaHcellsGain, 1.f, 7.f, (float)(localAdaptation_Gcells/200.0));
retina->setupOPLandIPLParvoChannel(true, true, (float)(localAdaptation_photoreceptors/200.0), 0.5f, 0.43f, (float)retinaHcellsGain, 1.f, 7.f, (float)(localAdaptation_Gcells/200.0));
}
int colorSaturationFactor;
void callback_saturateColors(int, void*)
static void callback_saturateColors(int, void*)
{
retina->setColorSaturation(true, (float)colorSaturationFactor);
retina->setColorSaturation(true, (float)colorSaturationFactor);
}
// loadNewFrame : loads a n image wrt filename parameters. it also manages image rescaling/histogram edges cutting (acts differently at first image i.e. if firstTimeread=true)
void loadNewFrame(const std::string filenamePrototype, const int currentFileIndex, const bool firstTimeread)
static void loadNewFrame(const std::string filenamePrototype, const int currentFileIndex, const bool firstTimeread)
{
char *currentImageName=NULL;
currentImageName = (char*)malloc(sizeof(char)*filenamePrototype.size()+10);
char *currentImageName=NULL;
currentImageName = (char*)malloc(sizeof(char)*filenamePrototype.size()+10);
// grab the first frame
sprintf(currentImageName, filenamePrototype.c_str(), currentFileIndex);
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
std::cout<<"RetinaDemo: reading image : "<<currentImageName<<std::endl;
// image processing case
// declare the retina input buffer... that will be fed differently in regard of the input media
inputImage = cv::imread(currentImageName, -1); // load image in RGB mode
std::cout<<"=> image size (h,w) = "<<inputImage.size().height<<", "<<inputImage.size().width<<std::endl;
if (inputImage.empty())
{
help("could not load image, program end");
return;;
// grab the first frame
sprintf(currentImageName, filenamePrototype.c_str(), currentFileIndex);
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
std::cout<<"RetinaDemo: reading image : "<<currentImageName<<std::endl;
// image processing case
// declare the retina input buffer... that will be fed differently in regard of the input media
inputImage = cv::imread(currentImageName, -1); // load image in RGB mode
std::cout<<"=> image size (h,w) = "<<inputImage.size().height<<", "<<inputImage.size().width<<std::endl;
if (inputImage.empty())
{
help("could not load image, program end");
return;;
}
// rescaling/histogram clipping stage
// rescale between 0 and 1
// TODO : take care of this step !!! maybe disable of do this in a nicer way ... each successive image should get the same transformation... but it depends on the initial image format
double maxInput, minInput;
minMaxLoc(inputImage, &minInput, &maxInput);
std::cout<<"ORIGINAL IMAGE pixels values range (max,min) : "<<maxInput<<", "<<minInput<<std::endl
// rescaling/histogram clipping stage
// rescale between 0 and 1
// TODO : take care of this step !!! maybe disable of do this in a nicer way ... each successive image should get the same transformation... but it depends on the initial image format
double maxInput, minInput;
minMaxLoc(inputImage, &minInput, &maxInput);
std::cout<<"ORIGINAL IMAGE pixels values range (max,min) : "<<maxInput<<", "<<minInput<<std::endl
;if (firstTimeread)
{
/* the first time, get the pixel values range and rougthly update scaling value
in order to center values around 128 and getting a range close to [0-255],
=> actually using a little less in order to let some more flexibility in range evolves...
*/
double maxInput, minInput;
minMaxLoc(inputImage, &minInput, &maxInput);
std::cout<<"FIRST IMAGE pixels values range (max,min) : "<<maxInput<<", "<<minInput<<std::endl;
globalRescalefactor=(float)(50.0/(maxInput-minInput)); // less than 255 for flexibility... experimental value to be carefull about
double channelOffset = -1.5*minInput;
globalOffset= cv::Scalar(channelOffset, channelOffset, channelOffset, channelOffset);
}
// call the generic input image rescaling callback
callBack_rescaleGrayLevelMat(1,NULL);
{
/* the first time, get the pixel values range and rougthly update scaling value
in order to center values around 128 and getting a range close to [0-255],
=> actually using a little less in order to let some more flexibility in range evolves...
*/
double maxInput, minInput;
minMaxLoc(inputImage, &minInput, &maxInput);
std::cout<<"FIRST IMAGE pixels values range (max,min) : "<<maxInput<<", "<<minInput<<std::endl;
globalRescalefactor=(float)(50.0/(maxInput-minInput)); // less than 255 for flexibility... experimental value to be carefull about
double channelOffset = -1.5*minInput;
globalOffset= cv::Scalar(channelOffset, channelOffset, channelOffset, channelOffset);
}
// call the generic input image rescaling callback
callBack_rescaleGrayLevelMat(1,NULL);
}
int main(int argc, char* argv[]) {
// welcome message
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"* Retina demonstration for High Dynamic Range compression (tone-mapping) : demonstrates the use of a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl;
std::cout<<"* This demo focuses demonstration of the dynamic compression capabilities of the model"<<std::endl;
std::cout<<"* => the main application is tone mapping of HDR images (i.e. see on a 8bit display a more than 8bits coded (up to 16bits) image with details in high and low luminance ranges"<<std::endl;
std::cout<<"* The retina model still have the following properties:"<<std::endl;
std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl;
std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl;
std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl;
std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl;
std::cout<<"* for more information, reer to the following papers :"<<std::endl;
std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl;
std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl;
std::cout<<"* => reports comments/remarks at benoit.alexandre.vision@gmail.com"<<std::endl;
std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"** WARNING : this sample requires OpenCV to be configured with OpenEXR support **"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"*** You can use free tools to generate OpenEXR images from images sets : ***"<<std::endl;
std::cout<<"*** => 1. take a set of photos from the same viewpoint using bracketing ***"<<std::endl;
std::cout<<"*** => 2. generate an OpenEXR image with tools like qtpfsgui.sourceforge.net ***"<<std::endl;
std::cout<<"*** => 3. apply tone mapping with this program ***"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
// welcome message
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"* Retina demonstration for High Dynamic Range compression (tone-mapping) : demonstrates the use of a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl;
std::cout<<"* This demo focuses demonstration of the dynamic compression capabilities of the model"<<std::endl;
std::cout<<"* => the main application is tone mapping of HDR images (i.e. see on a 8bit display a more than 8bits coded (up to 16bits) image with details in high and low luminance ranges"<<std::endl;
std::cout<<"* The retina model still have the following properties:"<<std::endl;
std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl;
std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl;
std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl;
std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl;
std::cout<<"* for more information, reer to the following papers :"<<std::endl;
std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl;
std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl;
std::cout<<"* => reports comments/remarks at benoit.alexandre.vision@gmail.com"<<std::endl;
std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"** WARNING : this sample requires OpenCV to be configured with OpenEXR support **"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
std::cout<<"*** You can use free tools to generate OpenEXR images from images sets : ***"<<std::endl;
std::cout<<"*** => 1. take a set of photos from the same viewpoint using bracketing ***"<<std::endl;
std::cout<<"*** => 2. generate an OpenEXR image with tools like qtpfsgui.sourceforge.net ***"<<std::endl;
std::cout<<"*** => 3. apply tone mapping with this program ***"<<std::endl;
std::cout<<"*********************************************************************************"<<std::endl;
// basic input arguments checking
if (argc<4)
{
help("bad number of parameter");
return -1;
}
// basic input arguments checking
if (argc<4)
{
help("bad number of parameter");
return -1;
}
bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
int startFrameIndex=0, endFrameIndex=0, currentFrameIndex=0;
sscanf(argv[2], "%d", &startFrameIndex);
sscanf(argv[3], "%d", &endFrameIndex);
std::string inputImageNamePrototype(argv[1]);
int startFrameIndex=0, endFrameIndex=0, currentFrameIndex=0;
sscanf(argv[2], "%d", &startFrameIndex);
sscanf(argv[3], "%d", &endFrameIndex);
std::string inputImageNamePrototype(argv[1]);
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
std::cout<<"RetinaDemo: setting up system with first image..."<<std::endl;
loadNewFrame(inputImageNamePrototype, startFrameIndex, true);
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
std::cout<<"RetinaDemo: setting up system with first image..."<<std::endl;
loadNewFrame(inputImageNamePrototype, startFrameIndex, true);
if (inputImage.empty())
{
help("could not load image, program end");
return -1;
if (inputImage.empty())
{
help("could not load image, program end");
return -1;
}
//////////////////////////////////////////////////////////////////////////////
// Program start in a try/catch safety context (Retina may throw errors)
try
{
/* create a retina instance with default parameters setup, uncomment the initialisation you wanna test
* -> if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
*/
if (useLogSampling)
//////////////////////////////////////////////////////////////////////////////
// Program start in a try/catch safety context (Retina may throw errors)
try
{
/* create a retina instance with default parameters setup, uncomment the initialisation you wanna test
* -> if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
*/
if (useLogSampling)
{
retina = new cv::Retina(inputImage.size(),true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0);
}
else// -> else allocate "classical" retina :
retina = new cv::Retina(inputImage.size());
// save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
retina->write("RetinaDefaultParameters.xml");
else// -> else allocate "classical" retina :
retina = new cv::Retina(inputImage.size());
// save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
retina->write("RetinaDefaultParameters.xml");
// desactivate Magnocellular pathway processing (motion information extraction) since it is not usefull here
retina->activateMovingContoursProcessing(false);
// declare retina output buffers
cv::Mat retinaOutput_parvo;
// declare retina output buffers
cv::Mat retinaOutput_parvo;
/////////////////////////////////////////////
// prepare displays and interactions
histogramClippingValue=0; // default value... updated with interface slider
/////////////////////////////////////////////
// prepare displays and interactions
histogramClippingValue=0; // default value... updated with interface slider
std::string retinaInputCorrected("Retina input image (with cut edges histogram for basic pixels error avoidance)");
cv::namedWindow(retinaInputCorrected,1);
cv::createTrackbar("histogram edges clipping limit", "Retina input image (with cut edges histogram for basic pixels error avoidance)",&histogramClippingValue,50,callBack_rescaleGrayLevelMat);
std::string retinaInputCorrected("Retina input image (with cut edges histogram for basic pixels error avoidance)");
cv::namedWindow(retinaInputCorrected,1);
cv::createTrackbar("histogram edges clipping limit", "Retina input image (with cut edges histogram for basic pixels error avoidance)",&histogramClippingValue,50,callBack_rescaleGrayLevelMat);
std::string RetinaParvoWindow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping");
cv::namedWindow(RetinaParvoWindow, 1);
colorSaturationFactor=3;
cv::createTrackbar("Color saturation", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &colorSaturationFactor,5,callback_saturateColors);
std::string RetinaParvoWindow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping");
cv::namedWindow(RetinaParvoWindow, 1);
colorSaturationFactor=3;
cv::createTrackbar("Color saturation", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &colorSaturationFactor,5,callback_saturateColors);
retinaHcellsGain=40;
cv::createTrackbar("Hcells gain", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping",&retinaHcellsGain,100,callBack_updateRetinaParams);
retinaHcellsGain=40;
cv::createTrackbar("Hcells gain", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping",&retinaHcellsGain,100,callBack_updateRetinaParams);
localAdaptation_photoreceptors=197;
localAdaptation_Gcells=190;
cv::createTrackbar("Ph sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams);
cv::createTrackbar("Gcells sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_Gcells,199,callBack_updateRetinaParams);
localAdaptation_photoreceptors=197;
localAdaptation_Gcells=190;
cv::createTrackbar("Ph sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams);
cv::createTrackbar("Gcells sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_Gcells,199,callBack_updateRetinaParams);
std::string powerTransformedInput("EXR image with basic processing : 16bits=>8bits with gamma correction");
std::string powerTransformedInput("EXR image with basic processing : 16bits=>8bits with gamma correction");
/////////////////////////////////////////////
// apply default parameters of user interaction variables
callBack_updateRetinaParams(1,NULL); // first call for default parameters setup
callback_saturateColors(1, NULL);
/////////////////////////////////////////////
// apply default parameters of user interaction variables
callBack_updateRetinaParams(1,NULL); // first call for default parameters setup
callback_saturateColors(1, NULL);
// processing loop with stop condition
currentFrameIndex=startFrameIndex;
while(currentFrameIndex <= endFrameIndex)
{
loadNewFrame(inputImageNamePrototype, currentFrameIndex, false);
// processing loop with stop condition
currentFrameIndex=startFrameIndex;
while(currentFrameIndex <= endFrameIndex)
{
loadNewFrame(inputImageNamePrototype, currentFrameIndex, false);
if (inputImage.empty())
{
std::cout<<"Could not load new image (index = "<<currentFrameIndex<<"), program end"<<std::endl;
return -1;
}
// display input & process standard power transformation
imshow("EXR image original image, 16bits=>8bits linear rescaling ", imageInputRescaled);
cv::Mat gammaTransformedImage;
cv::pow(imageInputRescaled, 1./5, gammaTransformedImage); // apply gamma curve: img = img ** (1./5)
imshow(powerTransformedInput, gammaTransformedImage);
// run retina filter
retina->run(imageInputRescaled);
// Retrieve and display retina output
retina->getParvo(retinaOutput_parvo);
cv::imshow(retinaInputCorrected, imageInputRescaled/255.f);
cv::imshow(RetinaParvoWindow, retinaOutput_parvo);
cv::waitKey(4);
// jump to next frame
++currentFrameIndex;
}
}catch(cv::Exception e)
{
std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
}
if (inputImage.empty())
{
std::cout<<"Could not load new image (index = "<<currentFrameIndex<<"), program end"<<std::endl;
return -1;
}
// display input & process standard power transformation
imshow("EXR image original image, 16bits=>8bits linear rescaling ", imageInputRescaled);
cv::Mat gammaTransformedImage;
cv::pow(imageInputRescaled, 1./5, gammaTransformedImage); // apply gamma curve: img = img ** (1./5)
imshow(powerTransformedInput, gammaTransformedImage);
// run retina filter
retina->run(imageInputRescaled);
// Retrieve and display retina output
retina->getParvo(retinaOutput_parvo);
cv::imshow(retinaInputCorrected, imageInputRescaled/255.f);
cv::imshow(RetinaParvoWindow, retinaOutput_parvo);
cv::waitKey(4);
// jump to next frame
++currentFrameIndex;
}
}catch(cv::Exception e)
{
std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
}
// Program end message
std::cout<<"Retina demo end"<<std::endl;
// Program end message
std::cout<<"Retina demo end"<<std::endl;
return 0;
return 0;
}

View File

@@ -28,7 +28,7 @@ const string bowImageDescriptorsDir = "/bowImageDescriptors";
const string svmsDir = "/svms";
const string plotsDir = "/plots";
void help(char** argv)
static void help(char** argv)
{
cout << "\nThis program shows how to read in, train on and produce test results for the PASCAL VOC (Visual Object Challenge) data. \n"
<< "It shows how to use detectors, descriptors and recognition methods \n"
@@ -57,7 +57,7 @@ void help(char** argv)
void makeDir( const string& dir )
static void makeDir( const string& dir )
{
#if defined WIN32 || defined _WIN32
CreateDirectory( dir.c_str(), 0 );
@@ -66,7 +66,7 @@ void makeDir( const string& dir )
#endif
}
void makeUsedDirs( const string& rootPath )
static void makeUsedDirs( const string& rootPath )
{
makeDir(rootPath + bowImageDescriptorsDir);
makeDir(rootPath + svmsDir);
@@ -1356,7 +1356,7 @@ const vector<string>& VocData::getObjectClasses()
// Protected Functions ------------------------------------
//---------------------------------------------------------
string getVocName( const string& vocPath )
static string getVocName( const string& vocPath )
{
size_t found = vocPath.rfind( '/' );
if( found == string::npos )
@@ -2047,7 +2047,7 @@ struct SVMTrainParamsExt
bool balanceClasses; // Balance class weights by number of samples in each (if true cSvmTrainTargetRatio is ignored).
};
void readUsedParams( const FileNode& fn, string& vocName, DDMParams& ddmParams, VocabTrainParams& vocabTrainParams, SVMTrainParamsExt& svmTrainParamsExt )
static void readUsedParams( const FileNode& fn, string& vocName, DDMParams& ddmParams, VocabTrainParams& vocabTrainParams, SVMTrainParamsExt& svmTrainParamsExt )
{
fn["vocName"] >> vocName;
@@ -2063,7 +2063,7 @@ void readUsedParams( const FileNode& fn, string& vocName, DDMParams& ddmParams,
svmTrainParamsExt.read( currFn );
}
void writeUsedParams( FileStorage& fs, const string& vocName, const DDMParams& ddmParams, const VocabTrainParams& vocabTrainParams, const SVMTrainParamsExt& svmTrainParamsExt )
static void writeUsedParams( FileStorage& fs, const string& vocName, const DDMParams& ddmParams, const VocabTrainParams& vocabTrainParams, const SVMTrainParamsExt& svmTrainParamsExt )
{
fs << "vocName" << vocName;
@@ -2080,7 +2080,7 @@ void writeUsedParams( FileStorage& fs, const string& vocName, const DDMParams& d
fs << "}";
}
void printUsedParams( const string& vocPath, const string& resDir,
static void printUsedParams( const string& vocPath, const string& resDir,
const DDMParams& ddmParams, const VocabTrainParams& vocabTrainParams,
const SVMTrainParamsExt& svmTrainParamsExt )
{
@@ -2094,7 +2094,7 @@ void printUsedParams( const string& vocPath, const string& resDir,
cout << "----------------------------------------------------------------" << endl << endl;
}
bool readVocabulary( const string& filename, Mat& vocabulary )
static bool readVocabulary( const string& filename, Mat& vocabulary )
{
cout << "Reading vocabulary...";
FileStorage fs( filename, FileStorage::READ );
@@ -2107,7 +2107,7 @@ bool readVocabulary( const string& filename, Mat& vocabulary )
return false;
}
bool writeVocabulary( const string& filename, const Mat& vocabulary )
static bool writeVocabulary( const string& filename, const Mat& vocabulary )
{
cout << "Saving vocabulary..." << endl;
FileStorage fs( filename, FileStorage::WRITE );
@@ -2119,7 +2119,7 @@ bool writeVocabulary( const string& filename, const Mat& vocabulary )
return false;
}
Mat trainVocabulary( const string& filename, VocData& vocData, const VocabTrainParams& trainParams,
static Mat trainVocabulary( const string& filename, VocData& vocData, const VocabTrainParams& trainParams,
const Ptr<FeatureDetector>& fdetector, const Ptr<DescriptorExtractor>& dextractor )
{
Mat vocabulary;
@@ -2209,7 +2209,7 @@ Mat trainVocabulary( const string& filename, VocData& vocData, const VocabTrainP
return vocabulary;
}
bool readBowImageDescriptor( const string& file, Mat& bowImageDescriptor )
static bool readBowImageDescriptor( const string& file, Mat& bowImageDescriptor )
{
FileStorage fs( file, FileStorage::READ );
if( fs.isOpened() )
@@ -2220,7 +2220,7 @@ bool readBowImageDescriptor( const string& file, Mat& bowImageDescriptor )
return false;
}
bool writeBowImageDescriptor( const string& file, const Mat& bowImageDescriptor )
static bool writeBowImageDescriptor( const string& file, const Mat& bowImageDescriptor )
{
FileStorage fs( file, FileStorage::WRITE );
if( fs.isOpened() )
@@ -2232,7 +2232,7 @@ bool writeBowImageDescriptor( const string& file, const Mat& bowImageDescriptor
}
// Load in the bag of words vectors for a set of images, from file if possible
void calculateImageDescriptors( const vector<ObdImage>& images, vector<Mat>& imageDescriptors,
static void calculateImageDescriptors( const vector<ObdImage>& images, vector<Mat>& imageDescriptors,
Ptr<BOWImgDescriptorExtractor>& bowExtractor, const Ptr<FeatureDetector>& fdetector,
const string& resPath )
{
@@ -2276,7 +2276,7 @@ void calculateImageDescriptors( const vector<ObdImage>& images, vector<Mat>& ima
}
}
void removeEmptyBowImageDescriptors( vector<ObdImage>& images, vector<Mat>& bowImageDescriptors,
static void removeEmptyBowImageDescriptors( vector<ObdImage>& images, vector<Mat>& bowImageDescriptors,
vector<char>& objectPresent )
{
CV_Assert( !images.empty() );
@@ -2293,7 +2293,7 @@ void removeEmptyBowImageDescriptors( vector<ObdImage>& images, vector<Mat>& bowI
}
}
void removeBowImageDescriptorsByCount( vector<ObdImage>& images, vector<Mat> bowImageDescriptors, vector<char> objectPresent,
static void removeBowImageDescriptorsByCount( vector<ObdImage>& images, vector<Mat> bowImageDescriptors, vector<char> objectPresent,
const SVMTrainParamsExt& svmParamsExt, int descsToDelete )
{
RNG& rng = theRNG();
@@ -2325,7 +2325,7 @@ void removeBowImageDescriptorsByCount( vector<ObdImage>& images, vector<Mat> bow
CV_Assert( bowImageDescriptors.size() == objectPresent.size() );
}
void setSVMParams( CvSVMParams& svmParams, CvMat& class_wts_cv, const Mat& responses, bool balanceClasses )
static void setSVMParams( CvSVMParams& svmParams, CvMat& class_wts_cv, const Mat& responses, bool balanceClasses )
{
int pos_ex = countNonZero(responses == 1);
int neg_ex = countNonZero(responses == -1);
@@ -2354,7 +2354,7 @@ void setSVMParams( CvSVMParams& svmParams, CvMat& class_wts_cv, const Mat& respo
}
}
void setSVMTrainAutoParams( CvParamGrid& c_grid, CvParamGrid& gamma_grid,
static void setSVMTrainAutoParams( CvParamGrid& c_grid, CvParamGrid& gamma_grid,
CvParamGrid& p_grid, CvParamGrid& nu_grid,
CvParamGrid& coef_grid, CvParamGrid& degree_grid )
{
@@ -2375,7 +2375,7 @@ void setSVMTrainAutoParams( CvParamGrid& c_grid, CvParamGrid& gamma_grid,
degree_grid.step = 0;
}
void trainSVMClassifier( CvSVM& svm, const SVMTrainParamsExt& svmParamsExt, const string& objClassName, VocData& vocData,
static void trainSVMClassifier( CvSVM& svm, const SVMTrainParamsExt& svmParamsExt, const string& objClassName, VocData& vocData,
Ptr<BOWImgDescriptorExtractor>& bowExtractor, const Ptr<FeatureDetector>& fdetector,
const string& resPath )
{
@@ -2450,7 +2450,7 @@ void trainSVMClassifier( CvSVM& svm, const SVMTrainParamsExt& svmParamsExt, cons
}
}
void computeConfidences( CvSVM& svm, const string& objClassName, VocData& vocData,
static void computeConfidences( CvSVM& svm, const string& objClassName, VocData& vocData,
Ptr<BOWImgDescriptorExtractor>& bowExtractor, const Ptr<FeatureDetector>& fdetector,
const string& resPath )
{
@@ -2491,7 +2491,7 @@ void computeConfidences( CvSVM& svm, const string& objClassName, VocData& vocDat
cout << "---------------------------------------------------------------" << endl;
}
void computeGnuPlotOutput( const string& resPath, const string& objClassName, VocData& vocData )
static void computeGnuPlotOutput( const string& resPath, const string& objClassName, VocData& vocData )
{
vector<float> precision, recall;
float ap;

View File

@@ -7,7 +7,7 @@
using namespace std;
using namespace cv;
void help()
static void help()
{
printf("\nDo background segmentation, especially demonstrating the use of cvUpdateBGStatModel().\n"
"Learns the background at the start and then segments.\n"

View File

@@ -16,7 +16,7 @@ using namespace cv;
using namespace std;
//Copy (x,y) location of descriptor matches found from KeyPoint data structures into Point2f vectors
void matches2points(const vector<DMatch>& matches, const vector<KeyPoint>& kpts_train,
static void matches2points(const vector<DMatch>& matches, const vector<KeyPoint>& kpts_train,
const vector<KeyPoint>& kpts_query, vector<Point2f>& pts_train, vector<Point2f>& pts_query)
{
pts_train.clear();
@@ -32,7 +32,7 @@ void matches2points(const vector<DMatch>& matches, const vector<KeyPoint>& kpts_
}
double match(const vector<KeyPoint>& /*kpts_train*/, const vector<KeyPoint>& /*kpts_query*/, DescriptorMatcher& matcher,
static double match(const vector<KeyPoint>& /*kpts_train*/, const vector<KeyPoint>& /*kpts_query*/, DescriptorMatcher& matcher,
const Mat& train, const Mat& query, vector<DMatch>& matches)
{
@@ -41,7 +41,7 @@ double match(const vector<KeyPoint>& /*kpts_train*/, const vector<KeyPoint>& /*k
return ((double)getTickCount() - t) / getTickFrequency();
}
void help()
static void help()
{
cout << "This program shows how to use BRIEF descriptor to match points in features2d" << endl <<
"It takes in two images, finds keypoints and matches them displaying matches and final homography warped results" << endl <<

View File

@@ -13,7 +13,7 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
printf("\nSigh: This program is not complete/will be replaced. \n"
"So: Use this just to see hints of how to use things like Rodrigues\n"
@@ -51,17 +51,17 @@ static bool readModelViews( const string& filename, vector<Point3f>& box,
roiList.resize(0);
poseList.resize(0);
box.resize(0);
FileStorage fs(filename, FileStorage::READ);
if( !fs.isOpened() )
return false;
fs["box"] >> box;
FileNode all = fs["views"];
if( all.type() != FileNode::SEQ )
return false;
FileNodeIterator it = all.begin(), it_end = all.end();
for(; it != it_end; ++it)
{
FileNode n = *it;
@@ -72,7 +72,7 @@ static bool readModelViews( const string& filename, vector<Point3f>& box,
poseList.push_back(Vec6f((float)np[0], (float)np[1], (float)np[2],
(float)np[3], (float)np[4], (float)np[5]));
}
return true;
}
@@ -90,11 +90,11 @@ static void writeModel(const string& modelFileName, const string& modelname,
const PointModel& model)
{
FileStorage fs(modelFileName, FileStorage::WRITE);
fs << modelname << "{" <<
"points" << "[:" << model.points << "]" <<
"idx" << "[:";
for( size_t i = 0; i < model.didx.size(); i++ )
fs << "[:" << model.didx[i] << "]";
fs << "]" << "descriptors" << model.descriptors;
@@ -259,7 +259,7 @@ static void findConstrainedCorrespondences(const Mat& _F,
static Point3f findRayIntersection(Point3f k1, Point3f b1, Point3f k2, Point3f b2)
{
{
float a[4], b[2], x[2];
a[0] = k1.dot(k1);
a[1] = a[2] = -k1.dot(k2);
@@ -268,7 +268,7 @@ static Point3f findRayIntersection(Point3f k1, Point3f b1, Point3f k2, Point3f b
b[1] = k2.dot(b1 - b2);
Mat_<float> A(2, 2, a), B(2, 1, b), X(2, 1, x);
solve(A, B, X);
float s1 = X.at<float>(0, 0);
float s2 = X.at<float>(1, 0);
return (k1*s1 + b1 + k2*s2 + b2)*0.5f;
@@ -281,19 +281,19 @@ static Point3f triangulatePoint(const vector<Point2f>& ps,
const Mat& cameraMatrix)
{
Mat_<double> K(cameraMatrix);
/*if( ps.size() > 2 )
{
Mat_<double> L(ps.size()*3, 4), U, evalues;
Mat_<double> P(3,4), Rt(3,4), Rt_part1=Rt.colRange(0,3), Rt_part2=Rt.colRange(3,4);
for( size_t i = 0; i < ps.size(); i++ )
{
double x = ps[i].x, y = ps[i].y;
Rs[i].convertTo(Rt_part1, Rt_part1.type());
ts[i].convertTo(Rt_part2, Rt_part2.type());
P = K*Rt;
for( int k = 0; k < 4; k++ )
{
L(i*3, k) = x*P(2,k) - P(0,k);
@@ -301,10 +301,10 @@ static Point3f triangulatePoint(const vector<Point2f>& ps,
L(i*3+2, k) = x*P(1,k) - y*P(0,k);
}
}
eigen(L.t()*L, evalues, U);
CV_Assert(evalues(0,0) >= evalues(3,0));
double W = fabs(U(3,3)) > FLT_EPSILON ? 1./U(3,3) : 0;
return Point3f((float)(U(3,0)*W), (float)(U(3,1)*W), (float)(U(3,2)*W));
}
@@ -324,7 +324,7 @@ static Point3f triangulatePoint(const vector<Point2f>& ps,
}
void triangulatePoint_test(void)
static void triangulatePoint_test(void)
{
int i, n = 100;
vector<Point3f> objpt(n), delta1(n), delta2(n);
@@ -370,13 +370,13 @@ struct EqKeypoints
{
EqKeypoints(const vector<int>* _dstart, const Set2i* _pairs)
: dstart(_dstart), pairs(_pairs) {}
bool operator()(const Pair2i& a, const Pair2i& b) const
{
return pairs->find(Pair2i(dstart->at(a.first) + a.second,
dstart->at(b.first) + b.second)) != pairs->end();
}
const vector<int>* dstart;
const Set2i* pairs;
};
@@ -423,7 +423,7 @@ static void build3dmodel( const Ptr<FeatureDetector>& detector,
vector<KeyPoint> keypoints;
detector->detect(gray, keypoints);
descriptorExtractor->compute(gray, keypoints, descriptorbuf);
Point2f roiofs = roiList[i].tl();
Point2f roiofs = roiList[i].tl();
for( size_t k = 0; k < keypoints.size(); k++ )
keypoints[k].pt += roiofs;
allkeypoints.push_back(keypoints);
@@ -438,7 +438,7 @@ static void build3dmodel( const Ptr<FeatureDetector>& detector,
size_t prev = alldescriptorsVec.size();
size_t delta = buf.rows*buf.cols;
alldescriptorsVec.resize(prev + delta);
alldescriptorsVec.resize(prev + delta);
std::copy(buf.ptr<float>(), buf.ptr<float>() + delta,
alldescriptorsVec.begin() + prev);
dstart.push_back(dstart.back() + (int)keypoints.size());
@@ -514,7 +514,7 @@ static void build3dmodel( const Ptr<FeatureDetector>& detector,
pairsFound++;
//model.points.push_back(objpt);
//model.points.push_back(objpt);
pairs[Pair2i(i1+dstart[i], i2+dstart[j])] = 1;
pairs[Pair2i(i2+dstart[j], i1+dstart[i])] = 1;
keypointsIdxMap[Pair2i((int)i,i1)] = 1;
@@ -618,7 +618,7 @@ int main(int argc, char** argv)
const char* intrinsicsFilename = 0;
const char* modelName = 0;
const char* detectorName = "SURF";
const char* descriptorExtractorName = "SURF";
const char* descriptorExtractorName = "SURF";
vector<Point3f> modelBox;
vector<string> imageList;

View File

@@ -41,7 +41,7 @@ const char* liveCaptureHelp =
" 'g' - start capturing images\n"
" 'u' - switch undistortion on/off\n";
void help()
static void help()
{
printf( "This is a camera calibration sample.\n"
"Usage: calibration\n"
@@ -88,7 +88,7 @@ static double computeReprojectionErrors(
int i, totalPoints = 0;
double totalErr = 0, err;
perViewErrors.resize(objectPoints.size());
for( i = 0; i < (int)objectPoints.size(); i++ )
{
projectPoints(Mat(objectPoints[i]), rvecs[i], tvecs[i],
@@ -99,14 +99,14 @@ static double computeReprojectionErrors(
totalErr += err*err;
totalPoints += n;
}
return std::sqrt(totalErr/totalPoints);
}
static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners, Pattern patternType = CHESSBOARD)
{
corners.resize(0);
switch(patternType)
{
case CHESSBOARD:
@@ -140,21 +140,21 @@ static bool runCalibration( vector<vector<Point2f> > imagePoints,
cameraMatrix = Mat::eye(3, 3, CV_64F);
if( flags & CV_CALIB_FIX_ASPECT_RATIO )
cameraMatrix.at<double>(0,0) = aspectRatio;
distCoeffs = Mat::zeros(8, 1, CV_64F);
vector<vector<Point3f> > objectPoints(1);
calcChessboardCorners(boardSize, squareSize, objectPoints[0], patternType);
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);
printf("RMS error reported by calibrateCamera: %g\n", rms);
bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);
@@ -162,7 +162,7 @@ static bool runCalibration( vector<vector<Point2f> > imagePoints,
}
void saveCameraParams( const string& filename,
static void saveCameraParams( const string& filename,
Size imageSize, Size boardSize,
float squareSize, float aspectRatio, int flags,
const Mat& cameraMatrix, const Mat& distCoeffs,
@@ -172,7 +172,7 @@ void saveCameraParams( const string& filename,
double totalAvgErr )
{
FileStorage fs( filename, FileStorage::WRITE );
time_t t;
time( &t );
struct tm *t2 = localtime( &t );
@@ -180,7 +180,7 @@ void saveCameraParams( const string& filename,
strftime( buf, sizeof(buf)-1, "%c", t2 );
fs << "calibration_time" << buf;
if( !rvecs.empty() || !reprojErrs.empty() )
fs << "nframes" << (int)std::max(rvecs.size(), reprojErrs.size());
fs << "image_width" << imageSize.width;
@@ -188,7 +188,7 @@ void saveCameraParams( const string& filename,
fs << "board_width" << boardSize.width;
fs << "board_height" << boardSize.height;
fs << "square_size" << squareSize;
if( flags & CV_CALIB_FIX_ASPECT_RATIO )
fs << "aspectRatio" << aspectRatio;
@@ -201,7 +201,7 @@ void saveCameraParams( const string& filename,
flags & CV_CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
cvWriteComment( *fs, buf, 0 );
}
fs << "flags" << flags;
fs << "camera_matrix" << cameraMatrix;
@@ -210,7 +210,7 @@ void saveCameraParams( const string& filename,
fs << "avg_reprojection_error" << totalAvgErr;
if( !reprojErrs.empty() )
fs << "per_view_reprojection_errors" << Mat(reprojErrs);
if( !rvecs.empty() && !tvecs.empty() )
{
CV_Assert(rvecs[0].type() == tvecs[0].type());
@@ -229,7 +229,7 @@ void saveCameraParams( const string& filename,
cvWriteComment( *fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
fs << "extrinsic_parameters" << bigmat;
}
if( !imagePoints.empty() )
{
Mat imagePtMat((int)imagePoints.size(), (int)imagePoints[0].size(), CV_32FC2);
@@ -259,7 +259,7 @@ static bool readStringList( const string& filename, vector<string>& l )
}
bool runAndSave(const string& outputFilename,
static bool runAndSave(const string& outputFilename,
const vector<vector<Point2f> >& imagePoints,
Size imageSize, Size boardSize, Pattern patternType, float squareSize,
float aspectRatio, int flags, Mat& cameraMatrix,
@@ -268,14 +268,14 @@ bool runAndSave(const string& outputFilename,
vector<Mat> rvecs, tvecs;
vector<float> reprojErrs;
double totalAvgErr = 0;
bool ok = runCalibration(imagePoints, imageSize, boardSize, patternType, squareSize,
aspectRatio, flags, cameraMatrix, distCoeffs,
rvecs, tvecs, reprojErrs, totalAvgErr);
printf("%s. avg reprojection error = %.2f\n",
ok ? "Calibration succeeded" : "Calibration failed",
totalAvgErr);
if( ok )
saveCameraParams( outputFilename, imageSize,
boardSize, squareSize, aspectRatio,
@@ -296,7 +296,7 @@ int main( int argc, char** argv )
Mat cameraMatrix, distCoeffs;
const char* outputFilename = "out_camera_data.yml";
const char* inputFilename = 0;
int i, nframes = 10;
bool writeExtrinsics = false, writePoints = false;
bool undistortImage = false;
@@ -412,7 +412,7 @@ int main( int argc, char** argv )
{
if( !videofile && readStringList(inputFilename, imageList) )
mode = CAPTURING;
else
else
capture.open(inputFilename);
}
else
@@ -420,7 +420,7 @@ int main( int argc, char** argv )
if( !capture.isOpened() && imageList.empty() )
return fprintf( stderr, "Could not initialize video (%d) capture\n",cameraId ), -2;
if( !imageList.empty() )
nframes = (int)imageList.size();
@@ -433,7 +433,7 @@ int main( int argc, char** argv )
{
Mat view, viewGray;
bool blink = false;
if( capture.isOpened() )
{
Mat view0;
@@ -442,7 +442,7 @@ int main( int argc, char** argv )
}
else if( i < (int)imageList.size() )
view = imread(imageList[i], 1);
if(!view.data)
{
if( imagePoints.size() > 0 )
@@ -452,14 +452,14 @@ int main( int argc, char** argv )
writeExtrinsics, writePoints);
break;
}
imageSize = view.size();
if( flipVertical )
flip( view, view, 0 );
vector<Point2f> pointbuf;
cvtColor(view, viewGray, CV_BGR2GRAY);
cvtColor(view, viewGray, CV_BGR2GRAY);
bool found;
switch( pattern )
@@ -489,14 +489,14 @@ int main( int argc, char** argv )
prevTimestamp = clock();
blink = capture.isOpened();
}
if(found)
drawChessboardCorners( view, boardSize, Mat(pointbuf), found );
string msg = mode == CAPTURING ? "100/100" :
mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
int baseLine = 0;
Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
Size textSize = getTextSize(msg, 1, 1, 1, &baseLine);
Point textOrigin(view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10);
if( mode == CAPTURING )
@@ -524,7 +524,7 @@ int main( int argc, char** argv )
if( (key & 255) == 27 )
break;
if( key == 'u' && mode == CALIBRATED )
undistortImage = !undistortImage;
@@ -547,14 +547,14 @@ int main( int argc, char** argv )
break;
}
}
if( !capture.isOpened() && showUndistorted )
{
Mat view, rview, map1, map2;
initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(),
getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
imageSize, CV_16SC2, map1, map2);
for( i = 0; i < (int)imageList.size(); i++ )
{
view = imread(imageList[i], 1);
@@ -568,6 +568,6 @@ int main( int argc, char** argv )
break;
}
}
return 0;
}

View File

@@ -11,7 +11,7 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
printf( "\nThis code generates an artificial camera and artificial chessboard images,\n"
"and then calibrates. It is basically test code for calibration that shows\n"
@@ -26,8 +26,8 @@ namespace cv
class ChessBoardGenerator
{
public:
double sensorWidth;
double sensorHeight;
double sensorWidth;
double sensorHeight;
size_t squareEdgePointsNum;
double min_cos;
mutable double cov;
@@ -35,14 +35,14 @@ public:
int rendererResolutionMultiplier;
ChessBoardGenerator(const Size& patternSize = Size(8, 6));
Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector<Point2f>& corners) const;
Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector<Point2f>& corners) const;
Size cornersSize() const;
private:
void generateEdge(const Point3f& p1, const Point3f& p2, vector<Point3f>& out) const;
Mat generageChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Point3f& zero, const Point3f& pb1, const Point3f& pb2,
Mat generageChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Point3f& zero, const Point3f& pb1, const Point3f& pb2,
float sqWidth, float sqHeight, const vector<Point3f>& whole, vector<Point2f>& corners) const;
void generateBasis(Point3f& pb1, Point3f& pb2) const;
void generateBasis(Point3f& pb1, Point3f& pb2) const;
Point3f generateChessBoardCenter(const Mat& camMat, const Size& imgSize) const;
Mat rvec, tvec;
};
@@ -55,25 +55,25 @@ const Size brdSize(8, 7);
const size_t brds_num = 20;
template<class T> ostream& operator<<(ostream& out, const Mat_<T>& mat)
{
{
for(int j = 0; j < mat.rows; ++j)
for(int i = 0; i < mat.cols; ++i)
out << mat(j, i) << " ";
out << mat(j, i) << " ";
return out;
}
int main()
{
help();
cout << "Initializing background...";
Mat background(imgSize, CV_8UC3);
randu(background, Scalar::all(32), Scalar::all(255));
{
help();
cout << "Initializing background...";
Mat background(imgSize, CV_8UC3);
randu(background, Scalar::all(32), Scalar::all(255));
GaussianBlur(background, background, Size(5, 5), 2);
cout << "Done" << endl;
cout << "Initializing chess board generator...";
cout << "Initializing chess board generator...";
ChessBoardGenerator cbg(brdSize);
cbg.rendererResolutionMultiplier = 4;
cout << "Done" << endl;
@@ -81,24 +81,24 @@ int main()
/* camera params */
Mat_<double> camMat(3, 3);
camMat << 300., 0., background.cols/2., 0, 300., background.rows/2., 0., 0., 1.;
Mat_<double> distCoeffs(1, 5);
distCoeffs << 1.2, 0.2, 0., 0., 0.;
cout << "Generating chessboards...";
cout << "Generating chessboards...";
vector<Mat> boards(brds_num);
vector<Point2f> tmp;
for(size_t i = 0; i < brds_num; ++i)
cout << (boards[i] = cbg(background, camMat, distCoeffs, tmp), i) << " ";
cout << "Done" << endl;
cout << "Done" << endl;
vector<Point3f> chessboard3D;
for(int j = 0; j < cbg.cornersSize().height; ++j)
for(int i = 0; i < cbg.cornersSize().width; ++i)
chessboard3D.push_back(Point3i(i, j, 0));
/* init points */
vector< vector<Point3f> > objectPoints;
vector< vector<Point3f> > objectPoints;
vector< vector<Point2f> > imagePoints;
cout << endl << "Finding chessboards' corners...";
@@ -110,22 +110,22 @@ int main()
if (found)
{
imagePoints.push_back(tmp);
objectPoints.push_back(chessboard3D);
cout<< "-found ";
objectPoints.push_back(chessboard3D);
cout<< "-found ";
}
else
cout<< "-not-found ";
cout<< "-not-found ";
drawChessboardCorners(boards[i], cbg.cornersSize(), Mat(tmp), found);
imshow("Current chessboard", boards[i]); waitKey(1000);
}
cout << "Done" << endl;
cvDestroyAllWindows();
Mat camMat_est;
Mat distCoeffs_est;
vector<Mat> rvecs, tvecs;
cout << "Calibrating...";
double rep_err = calibrateCamera(objectPoints, imagePoints, imgSize, camMat_est, distCoeffs_est, rvecs, tvecs);
cout << "Done" << endl;
@@ -137,7 +137,7 @@ int main()
cout << "==================================" << endl;
cout << "Estimated camera matrix:\n" << (Mat_<double>&)camMat_est << endl;
cout << "Estimated distCoeffs:\n" << (Mat_<double>&)distCoeffs_est << endl;
return 0;
}
@@ -150,18 +150,18 @@ 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(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);
}
void cv::ChessBoardGenerator::generateEdge(const Point3f& p1, const Point3f& p2, vector<Point3f>& out) const
{
Point3f step = (p2 - p1) * (1.f/squareEdgePointsNum);
{
Point3f step = (p2 - p1) * (1.f/squareEdgePointsNum);
for(size_t n = 0; n < squareEdgePointsNum; ++n)
out.push_back( p1 + step * (float)n);
}
}
Size cv::ChessBoardGenerator::cornersSize() const
{
@@ -172,7 +172,7 @@ struct Mult
{
float m;
Mult(int mult) : m((float)mult) {}
Point2f operator()(const Point2f& p)const { return p * m; }
Point2f operator()(const Point2f& p)const { return p * m; }
};
void cv::ChessBoardGenerator::generateBasis(Point3f& pb1, Point3f& pb2) const
@@ -181,39 +181,39 @@ void cv::ChessBoardGenerator::generateBasis(Point3f& pb1, Point3f& pb2) const
Vec3f n;
for(;;)
{
{
n[0] = rng.uniform(-1.f, 1.f);
n[1] = rng.uniform(-1.f, 1.f);
n[2] = rng.uniform(-1.f, 1.f);
float len = (float)norm(n);
n[0]/=len;
n[1]/=len;
n[2] = rng.uniform(-1.f, 1.f);
float len = (float)norm(n);
n[0]/=len;
n[1]/=len;
n[2]/=len;
if (fabs(n[2]) > min_cos)
break;
}
Vec3f n_temp = n; n_temp[0] += 100;
Vec3f b1 = n.cross(n_temp);
Vec3f b1 = n.cross(n_temp);
Vec3f b2 = n.cross(b1);
float len_b1 = (float)norm(b1);
float len_b2 = (float)norm(b2);
float len_b2 = (float)norm(b2);
pb1 = Point3f(b1[0]/len_b1, b1[1]/len_b1, b1[2]/len_b1);
pb2 = Point3f(b2[0]/len_b1, b2[1]/len_b2, b2[2]/len_b2);
}
Mat cv::ChessBoardGenerator::generageChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Point3f& zero, const Point3f& pb1, const Point3f& pb2,
Mat cv::ChessBoardGenerator::generageChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Point3f& zero, const Point3f& pb1, const Point3f& pb2,
float sqWidth, float sqHeight, const vector<Point3f>& whole,
vector<Point2f>& corners) const
{
vector< vector<Point> > squares_black;
vector< vector<Point> > squares_black;
for(int i = 0; i < patternSize.width; ++i)
for(int j = 0; j < patternSize.height; ++j)
if ( (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0) )
{
if ( (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0) )
{
vector<Point3f> pts_square3d;
vector<Point2f> pts_square2d;
@@ -224,17 +224,17 @@ Mat cv::ChessBoardGenerator::generageChessBoard(const Mat& bg, const Mat& camMat
generateEdge(p1, p2, pts_square3d);
generateEdge(p2, p3, pts_square3d);
generateEdge(p3, p4, pts_square3d);
generateEdge(p4, p1, pts_square3d);
generateEdge(p4, p1, pts_square3d);
projectPoints( Mat(pts_square3d), rvec, tvec, camMat, distCoeffs, pts_square2d);
squares_black.resize(squares_black.size() + 1);
vector<Point2f> temp;
approxPolyDP(Mat(pts_square2d), temp, 1.0, true);
transform(temp.begin(), temp.end(), back_inserter(squares_black.back()), Mult(rendererResolutionMultiplier));
}
squares_black.resize(squares_black.size() + 1);
vector<Point2f> temp;
approxPolyDP(Mat(pts_square2d), temp, 1.0, true);
transform(temp.begin(), temp.end(), back_inserter(squares_black.back()), Mult(rendererResolutionMultiplier));
}
/* calculate corners */
vector<Point3f> corners3d;
vector<Point3f> corners3d;
for(int j = 0; j < patternSize.height - 1; ++j)
for(int i = 0; i < patternSize.width - 1; ++i)
corners3d.push_back(zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2);
@@ -248,66 +248,66 @@ Mat cv::ChessBoardGenerator::generageChessBoard(const Mat& bg, const Mat& camMat
generateEdge(whole[2], whole[3], whole3d);
generateEdge(whole[3], whole[0], whole3d);
projectPoints( Mat(whole3d), rvec, tvec, camMat, distCoeffs, whole2d);
vector<Point2f> temp_whole2d;
approxPolyDP(Mat(whole2d), temp_whole2d, 1.0, true);
vector<Point2f> temp_whole2d;
approxPolyDP(Mat(whole2d), temp_whole2d, 1.0, true);
vector< vector<Point > > whole_contour(1);
transform(temp_whole2d.begin(), temp_whole2d.end(),
back_inserter(whole_contour.front()), Mult(rendererResolutionMultiplier));
transform(temp_whole2d.begin(), temp_whole2d.end(),
back_inserter(whole_contour.front()), Mult(rendererResolutionMultiplier));
Mat result;
if (rendererResolutionMultiplier == 1)
{
{
result = bg.clone();
drawContours(result, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA);
drawContours(result, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA);
drawContours(result, squares_black, -1, Scalar::all(0), CV_FILLED, CV_AA);
}
else
{
Mat tmp;
Mat tmp;
resize(bg, tmp, bg.size() * rendererResolutionMultiplier);
drawContours(tmp, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA);
drawContours(tmp, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA);
drawContours(tmp, squares_black, -1, Scalar::all(0), CV_FILLED, CV_AA);
resize(tmp, result, bg.size(), 0, 0, INTER_AREA);
}
}
return result;
}
Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector<Point2f>& corners) const
{
{
cov = min(cov, 0.8);
double fovx, fovy, focalLen;
Point2d principalPoint;
double aspect;
calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight,
calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight,
fovx, fovy, focalLen, principalPoint, aspect);
RNG& rng = theRNG();
float d1 = static_cast<float>(rng.uniform(0.1, 10.0));
float d1 = static_cast<float>(rng.uniform(0.1, 10.0));
float ah = static_cast<float>(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180);
float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180);
float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180);
Point3f p;
p.z = cos(ah) * d1;
p.x = sin(ah) * d1;
p.y = p.z * tan(av);
p.y = p.z * tan(av);
Point3f pb1, pb2;
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = static_cast<float>(norm(p) * sin( min(fovx, fovy) * 0.5 * CV_PI / 180));
float cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
vector<Point3f> pts3d(4);
vector<Point2f> pts2d(4);
for(;;)
{
{
pts3d[0] = p + pb1 * cbHalfWidth + cbHalfHeight * pb2;
pts3d[1] = p + pb1 * cbHalfWidth - cbHalfHeight * pb2;
pts3d[2] = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
pts3d[3] = p - pb1 * cbHalfWidth + cbHalfHeight * pb2;
/* can remake with better perf */
projectPoints( Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d);
@@ -315,12 +315,12 @@ Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const
bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0;
bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0;
bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0;
if ( inrect1 && inrect2 && inrect3 && inrect4)
break;
cbHalfWidth*=0.8f;
cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
}
cbHalfWidth *= static_cast<float>(patternSize.width)/(patternSize.width + 1);
@@ -329,7 +329,7 @@ Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const
Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
float sqWidth = 2 * cbHalfWidth/patternSize.width;
float sqHeight = 2 * cbHalfHeight/patternSize.height;
return generageChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, sqWidth, sqHeight, pts3d, corners);
return generageChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, sqWidth, sqHeight, pts3d, corners);
}

View File

@@ -18,7 +18,7 @@ Point origin;
Rect selection;
int vmin = 10, vmax = 256, smin = 30;
void onMouse( int event, int x, int y, int, void* )
static void onMouse( int event, int x, int y, int, void* )
{
if( selectObject )
{
@@ -45,7 +45,7 @@ void onMouse( int event, int x, int y, int, void* )
}
}
void help()
static void help()
{
cout << "\nThis is a demo that shows mean-shift based tracking\n"
"You select a color objects such as your face and it tracks it.\n"

View File

@@ -7,9 +7,9 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nThis program demonstrates Chamfer matching -- computing a distance between an \n"
"edge template and a query edge image.\n"
"Usage: \n"
@@ -17,24 +17,24 @@ void help()
" By default the inputs are logo_in_clutter.png logo.png\n";
}
const char* keys =
const char* keys =
{
"{1| |logo_in_clutter.png|image edge map }"
"{2| |logo.png |template edge map}"
"{1| |logo_in_clutter.png|image edge map }"
"{2| |logo.png |template edge map}"
};
int main( int argc, const char** argv )
{
help();
CommandLineParser parser(argc, argv, keys);
help();
CommandLineParser parser(argc, argv, keys);
string image = parser.get<string>("1");
string templ = parser.get<string>("2");
Mat img = imread(image.c_str(), 0);
Mat tpl = imread(templ.c_str(), 0);
string image = parser.get<string>("1");
string templ = parser.get<string>("2");
Mat img = imread(image.c_str(), 0);
Mat tpl = imread(templ.c_str(), 0);
if (img.empty() || tpl.empty())
if (img.empty() || tpl.empty())
{
cout << "Could not read image file " << image << " or " << templ << "." << endl;
return -1;

View File

@@ -8,16 +8,16 @@ using namespace std;
Mat img;
int threshval = 100;
void on_trackbar(int, void*)
static void on_trackbar(int, void*)
{
Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
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);
Mat dst = Mat::zeros(img.size(), CV_8UC3);
if( !contours.empty() && !hierarchy.empty() )
{
@@ -31,42 +31,42 @@ void on_trackbar(int, void*)
}
}
imshow( "Connected Components", dst );
imshow( "Connected Components", dst );
}
void help()
static void help()
{
cout << "\n This program demonstrates connected components and use of the trackbar\n"
"Usage: \n"
" ./connected_components <image(stuff.jpg as default)>\n"
"The image is converted to grayscale and displayed, another image has a trackbar\n"
"Usage: \n"
" ./connected_components <image(stuff.jpg as default)>\n"
"The image is converted to grayscale and displayed, another image has a trackbar\n"
"that controls thresholding and thereby the extracted contours which are drawn in color\n";
}
const char* keys =
const char* keys =
{
"{1| |stuff.jpg|image for converting to a grayscale}"
"{1| |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");
img = imread(inputImage.c_str(), 0);
help();
CommandLineParser parser(argc, argv, keys);
string inputImage = parser.get<string>("1");
img = imread(inputImage.c_str(), 0);
if(img.empty())
{
if(img.empty())
{
cout << "Could not read input image file: " << inputImage << endl;
return -1;
}
return -1;
}
namedWindow( "Image", 1 );
namedWindow( "Image", 1 );
imshow( "Image", img );
namedWindow( "Connected Components", 1 );
createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
on_trackbar(threshval, 0);
namedWindow( "Connected Components", 1 );
createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
on_trackbar(threshval, 0);
waitKey(0);
return 0;

View File

@@ -6,7 +6,7 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout
<< "\nThis program illustrates the use of findContours and drawContours\n"
@@ -23,7 +23,7 @@ int levels = 3;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
void on_trackbar(int, void*)
static void on_trackbar(int, void*)
{
Mat cnt_img = Mat::zeros(w, w, CV_8UC3);
int _levels = levels - 3;

View File

@@ -6,11 +6,11 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nThis sample program demonstrates the use of the convexHull() function\n"
<< "Call:\n"
<< "./convexhull\n" << endl;
cout << "\nThis sample program demonstrates the use of the convexHull() function\n"
<< "Call:\n"
<< "./convexhull\n" << endl;
}
int main( int /*argc*/, char** /*argv*/ )
@@ -24,7 +24,7 @@ int main( int /*argc*/, char** /*argv*/ )
{
char key;
int i, count = (unsigned)rng%100 + 1;
vector<Point> points;
for( i = 0; i < count; i++ )
@@ -32,20 +32,20 @@ int main( int /*argc*/, char** /*argv*/ )
Point pt;
pt.x = rng.uniform(img.cols/4, img.cols*3/4);
pt.y = rng.uniform(img.rows/4, img.rows*3/4);
points.push_back(pt);
}
vector<int> hull;
convexHull(Mat(points), hull, true);
img = Scalar::all(0);
for( i = 0; i < count; i++ )
circle(img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA);
int hullcount = (int)hull.size();
Point pt0 = points[hull[hullcount-1]];
for( i = 0; i < hullcount; i++ )
{
Point pt = points[hull[i]];

View File

@@ -11,23 +11,23 @@
using namespace std;
using namespace cv;
void help()
static void help()
{
cout
<< "\n------------------------------------------------------------------\n"
<< " This program shows the serial out capabilities of cv::Mat\n"
<< "That is, cv::Mat M(...); cout << M; Now works.\n"
<< "Output can be formated to OpenCV, python, numpy, csv and C styles"
<< "Usage:\n"
<< "./cvout_sample\n"
<< "------------------------------------------------------------------\n\n"
<< endl;
cout
<< "\n------------------------------------------------------------------\n"
<< " This program shows the serial out capabilities of cv::Mat\n"
<< "That is, cv::Mat M(...); cout << M; Now works.\n"
<< "Output can be formated to OpenCV, python, numpy, csv and C styles"
<< "Usage:\n"
<< "./cvout_sample\n"
<< "------------------------------------------------------------------\n\n"
<< endl;
}
int main(int,char**)
{
help();
help();
Mat i = Mat::eye(4, 4, CV_64F);
i.at<double>(1,1) = CV_PI;
cout << "i = " << i << ";" << endl;
@@ -38,7 +38,7 @@ int main(int,char**)
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 (csv) = " << format(r,"csv") << ";" << endl << endl;
cout << "r (c) = " << format(r,"C") << ";" << endl << endl;
Point2f p(5, 1);
@@ -51,9 +51,9 @@ int main(int,char**)
v.push_back(1);
v.push_back(2);
v.push_back(3);
cout << "shortvec = " << Mat(v) << endl;
vector<Point2f> points(20);
for (size_t i = 0; i < points.size(); ++i)
points[i] = Point2f((float)(i * 5), (float)(i % 7));

View File

@@ -7,7 +7,7 @@ using namespace std;
static void help()
{
cout << "\nThis program demostrates iterative construction of\n"
cout << "\nThis program demostrates iterative construction of\n"
"delaunay triangulation and voronoi tesselation.\n"
"It draws a random set of points in an image and then delaunay triangulates them.\n"
"Usage: \n"
@@ -27,7 +27,7 @@ static void draw_subdiv( Mat& img, Subdiv2D& subdiv, Scalar delaunay_color )
vector<Vec6f> triangleList;
subdiv.getTriangleList(triangleList);
vector<Point> pt(3);
for( size_t i = 0; i < triangleList.size(); i++ )
{
Vec6f t = triangleList[i];
@@ -54,9 +54,9 @@ static void draw_subdiv( Mat& img, Subdiv2D& subdiv, Scalar delaunay_color )
static void locate_point( Mat& img, Subdiv2D& subdiv, Point2f fp, Scalar active_color )
{
int e0=0, vertex=0;
subdiv.locate(fp, e0, vertex);
if( e0 > 0 )
{
int e = e0;
@@ -65,37 +65,37 @@ 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 );
e = subdiv.getEdge(e, Subdiv2D::NEXT_AROUND_LEFT);
}
while( e != e0 );
}
draw_subdiv_point( img, fp, active_color );
}
void paint_voronoi( Mat& img, Subdiv2D& subdiv )
static void paint_voronoi( Mat& img, Subdiv2D& subdiv )
{
vector<vector<Point2f> > facets;
vector<Point2f> centers;
subdiv.getVoronoiFacetList(vector<int>(), facets, centers);
vector<Point> ifacet;
vector<vector<Point> > ifacets(1);
for( size_t i = 0; i < facets.size(); i++ )
{
ifacet.resize(facets[i].size());
for( size_t j = 0; j < facets[i].size(); j++ )
ifacet[j] = facets[i][j];
Scalar color;
color[0] = rand() & 255;
color[1] = rand() & 255;
color[2] = rand() & 255;
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);
@@ -106,43 +106,43 @@ void paint_voronoi( Mat& img, Subdiv2D& subdiv )
int main( int, char** )
{
help();
Scalar active_facet_color(0, 0, 255), delaunay_color(255,255,255);
Rect rect(0, 0, 600, 600);
Subdiv2D subdiv(rect);
Mat img(rect.size(), CV_8UC3);
img = Scalar::all(0);
string win = "Delaunay Demo";
imshow(win, img);
for( int i = 0; i < 200; i++ )
{
Point2f fp( (float)(rand()%(rect.width-10)+5),
(float)(rand()%(rect.height-10)+5));
locate_point( img, subdiv, fp, active_facet_color );
imshow( win, img );
if( waitKey( 100 ) >= 0 )
break;
subdiv.insert(fp);
img = Scalar::all(0);
draw_subdiv( img, subdiv, delaunay_color );
imshow( win, img );
if( waitKey( 100 ) >= 0 )
break;
}
img = Scalar::all(0);
paint_voronoi( img, subdiv );
imshow( win, img );
waitKey(0);
return 0;
}

View File

@@ -12,7 +12,7 @@ int _contrast = 100;
Mat image;
/* brightness/contrast callback function */
void updateBrightnessContrast( int /*arg*/, void* )
static void updateBrightnessContrast( int /*arg*/, void* )
{
int histSize = 64;
int brightness = _brightness - 100;
@@ -42,7 +42,7 @@ 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);
histImage = Scalar::all(255);
@@ -54,31 +54,31 @@ void updateBrightnessContrast( int /*arg*/, void* )
Scalar::all(0), -1, 8, 0 );
imshow("histogram", histImage);
}
void help()
static void help()
{
std::cout << "\nThis program demonstrates the use of calcHist() -- histogram creation.\n"
<< "Usage: \n" << "demhist [image_name -- Defaults to baboon.jpg]" << std::endl;
std::cout << "\nThis program demonstrates the use of calcHist() -- histogram creation.\n"
<< "Usage: \n" << "demhist [image_name -- Defaults to baboon.jpg]" << std::endl;
}
const char* keys =
const char* keys =
{
"{1| |baboon.jpg|input image file}"
"{1| |baboon.jpg|input image file}"
};
int main( int argc, const char** argv )
{
help();
help();
CommandLineParser parser(argc, argv, keys);
string inputImage = parser.get<string>("1");
CommandLineParser parser(argc, argv, keys);
string inputImage = parser.get<string>("1");
// Load the source image. HighGUI use.
image = imread( inputImage, 0 );
if(image.empty())
{
std::cerr << "Cannot read image file: " << inputImage << std::endl;
return -1;
}
// Load the source image. HighGUI use.
image = imread( inputImage, 0 );
if(image.empty())
{
std::cerr << "Cannot read image file: " << inputImage << std::endl;
return -1;
}
namedWindow("image", 0);
namedWindow("histogram", 0);

View File

@@ -9,7 +9,7 @@
using namespace cv;
using namespace std;
void help(char** argv)
static void help(char** argv)
{
cout << "\nThis program demonstrats keypoint finding and matching between 2 images using features2d framework.\n"
<< " In one case, the 2nd image is synthesized by homography from the first, in the second case, there are 2 images\n"
@@ -39,7 +39,7 @@ const string winName = "correspondences";
enum { NONE_FILTER = 0, CROSS_CHECK_FILTER = 1 };
int getMatcherFilterType( const string& str )
static int getMatcherFilterType( const string& str )
{
if( str == "NoneFilter" )
return NONE_FILTER;
@@ -49,7 +49,7 @@ int getMatcherFilterType( const string& str )
return -1;
}
void simpleMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
static void simpleMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
vector<DMatch>& matches12 )
{
@@ -57,7 +57,7 @@ void simpleMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
descriptorMatcher->match( descriptors1, descriptors2, matches12 );
}
void crossCheckMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
static void crossCheckMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
vector<DMatch>& filteredMatches12, int knn=1 )
{
@@ -87,7 +87,7 @@ void crossCheckMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
}
}
void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
static void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
{
H.create(3, 3, CV_32FC1);
H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);
@@ -103,7 +103,7 @@ void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
warpPerspective( src, dst, H, src.size() );
}
void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
static void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
vector<KeyPoint>& keypoints1, const Mat& descriptors1,
Ptr<FeatureDetector>& detector, Ptr<DescriptorExtractor>& descriptorExtractor,
Ptr<DescriptorMatcher>& descriptorMatcher, int matcherFilter, bool eval,

View File

@@ -14,7 +14,7 @@
#define DEBUGLOGS 1
#if ANDROID
#ifdef ANDROID
#include <android/log.h>
#define LOG_TAG "DETECTIONBASEDTRACKER__TEST_APPLICAT"
#define LOGD0(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
@@ -36,7 +36,7 @@
#define LOGI(_str, ...) LOGI0(_str , ## __VA_ARGS__)
#define LOGW(_str, ...) LOGW0(_str , ## __VA_ARGS__)
#define LOGE(_str, ...) LOGE0(_str , ## __VA_ARGS__)
#else
#else
#define LOGD(...) do{} while(0)
#define LOGI(...) do{} while(0)
#define LOGW(...) do{} while(0)
@@ -51,7 +51,7 @@ using namespace std;
#define ORIGINAL 0
#define SHOULD_USE_EXTERNAL_BUFFERS 1
void usage()
static void usage()
{
LOGE0("usage: filepattern outfilepattern cascadefile");
LOGE0("\t where ");
@@ -63,7 +63,7 @@ void usage()
LOGE0("\t (e.g.\"opencv/data/lbpcascades/lbpcascade_frontalface.xml\" ");
}
int test_FaceDetector(int argc, char *argv[])
static int test_FaceDetector(int argc, char *argv[])
{
if (argc < 4) {
usage();
@@ -102,7 +102,7 @@ int test_FaceDetector(int argc, char *argv[])
fd.run();
Mat gray;
Mat m;
Mat m;
int64 tprev=getTickCount();
double freq=getTickFrequency();

View File

@@ -175,6 +175,8 @@ public:
void run();
virtual ~BaseQualityEvaluator(){}
protected:
virtual string getRunParamsFilename() const = 0;
virtual string getResultsFilename() const = 0;
@@ -540,7 +542,7 @@ void DetectorQualityEvaluator::readAlgorithm ()
}
}
int update_progress( const string& /*name*/, int progress, int test_case_idx, int count, double dt )
static int update_progress( const string& /*name*/, int progress, int test_case_idx, int count, double dt )
{
int width = 60 /*- (int)name.length()*/;
if( count > 0 )
@@ -588,13 +590,13 @@ void DetectorQualityEvaluator::runDatasetTest (const vector<Mat> &imgs, const ve
}
}
void testLog( bool isBadAccuracy )
{
if( isBadAccuracy )
printf(" bad accuracy\n");
else
printf("\n");
}
// static void testLog( bool isBadAccuracy )
// {
// if( isBadAccuracy )
// printf(" bad accuracy\n");
// else
// printf("\n");
// }
/****************************************************************************************\
* Descriptors evaluation *

View File

@@ -7,56 +7,56 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
printf("\nThis program demonstrated the use of the discrete Fourier transform (dft)\n"
"The dft of an image is taken and it's power spectrum is displayed.\n"
"Usage:\n"
"./dft [image_name -- default lena.jpg]\n");
printf("\nThis program demonstrated the use of the discrete Fourier transform (dft)\n"
"The dft of an image is taken and it's power spectrum is displayed.\n"
"Usage:\n"
"./dft [image_name -- default lena.jpg]\n");
}
const char* keys =
const char* keys =
{
"{1| |lena.jpg|input image file}"
"{1| |lena.jpg|input image file}"
};
int main(int argc, const char ** argv)
{
help();
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>("1");
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>("1");
Mat img = imread(filename.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
Mat img = imread(filename.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
if( img.empty() )
{
help();
printf("Cannot read image file: %s\n", filename.c_str());
printf("Cannot read image file: %s\n", filename.c_str());
return -1;
}
int M = getOptimalDFTSize( img.rows );
int N = getOptimalDFTSize( img.cols );
Mat padded;
copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));
Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
Mat complexImg;
merge(planes, 2, complexImg);
dft(complexImg, complexImg);
// compute log(1 + sqrt(Re(DFT(img))**2 + Im(DFT(img))**2))
split(complexImg, planes);
magnitude(planes[0], planes[1], planes[0]);
Mat mag = planes[0];
mag += Scalar::all(1);
log(mag, mag);
// crop the spectrum, if it has an odd number of rows or columns
mag = mag(Rect(0, 0, mag.cols & -2, mag.rows & -2));
int cx = mag.cols/2;
int cy = mag.rows/2;
// rearrange the quadrants of Fourier image
// so that the origin is at the image center
Mat tmp;
@@ -64,17 +64,17 @@ int main(int argc, const char ** argv)
Mat q1(mag, Rect(cx, 0, cx, cy));
Mat q2(mag, Rect(0, cy, cx, cy));
Mat q3(mag, Rect(cx, cy, cx, cy));
q0.copyTo(tmp);
q3.copyTo(q0);
tmp.copyTo(q3);
q1.copyTo(tmp);
q2.copyTo(q1);
tmp.copyTo(q2);
normalize(mag, mag, 0, 1, CV_MINMAX);
imshow("spectrum magnitude", mag);
waitKey();
return 0;

View File

@@ -14,7 +14,7 @@ int distType0 = CV_DIST_L1;
Mat gray;
// threshold trackbar callback
void onTrackbar( int, void* )
static void onTrackbar( int, void* )
{
static const Scalar colors[] =
{
@@ -44,20 +44,20 @@ void onTrackbar( int, void* )
// begin "painting" the distance transform result
dist *= 5000;
pow(dist, 0.5, dist);
Mat dist32s, dist8u1, dist8u2;
dist.convertTo(dist32s, CV_32S, 1, 0.5);
dist32s &= Scalar::all(255);
dist32s.convertTo(dist8u1, CV_8U, 1, 0);
dist32s *= -1;
dist32s += Scalar::all(255);
dist32s.convertTo(dist8u2, CV_8U);
Mat planes[] = {dist8u1, dist8u2, dist8u2};
merge(planes, 3, dist8u);
merge(planes, 3, dist8u);
}
else
{
@@ -84,40 +84,40 @@ void onTrackbar( int, void* )
imshow("Distance Map", dist8u );
}
void help()
static void help()
{
printf("\nProgram to demonstrate the use of the distance transform function between edge images.\n"
"Usage:\n"
"./distrans [image_name -- default image is stuff.jpg]\n"
"\nHot keys: \n"
"\tESC - quit the program\n"
"\tC - use C/Inf metric\n"
"\tL1 - use L1 metric\n"
"\tL2 - use L2 metric\n"
"\t3 - use 3x3 mask\n"
"\t5 - use 5x5 mask\n"
"\t0 - use precise distance transform\n"
"\tv - switch to Voronoi diagram mode\n"
printf("\nProgram to demonstrate the use of the distance transform function between edge images.\n"
"Usage:\n"
"./distrans [image_name -- default image is stuff.jpg]\n"
"\nHot keys: \n"
"\tESC - quit the program\n"
"\tC - use C/Inf metric\n"
"\tL1 - use L1 metric\n"
"\tL2 - use L2 metric\n"
"\t3 - use 3x3 mask\n"
"\t5 - use 5x5 mask\n"
"\t0 - use precise distance transform\n"
"\tv - switch to Voronoi diagram mode\n"
"\tp - switch to pixel-based Voronoi diagram mode\n"
"\tSPACE - loop through all the modes\n\n");
"\tSPACE - loop through all the modes\n\n");
}
const char* keys =
const char* keys =
{
"{1| |stuff.jpg|input image file}"
"{1| |stuff.jpg|input image file}"
};
int main( int argc, const char** argv )
{
help();
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>("1");
gray = imread(filename.c_str(), 0);
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>("1");
gray = imread(filename.c_str(), 0);
if(gray.empty())
{
printf("Cannot read image file: %s\n", filename.c_str());
help();
return -1;
printf("Cannot read image file: %s\n", filename.c_str());
help();
return -1;
}
namedWindow("Distance Map", 1);
@@ -136,7 +136,7 @@ int main( int argc, const char** argv )
if( c == 'c' || c == 'C' || c == '1' || c == '2' ||
c == '3' || c == '5' || c == '0' )
voronoiType = -1;
if( c == 'c' || c == 'C' )
distType0 = CV_DIST_C;
else if( c == '1' )

View File

@@ -3,11 +3,11 @@
#include <stdio.h>
using namespace cv;
void help()
static void help()
{
printf("\nThis program demonstrates OpenCV drawing and text output functions.\n"
"Usage:\n"
" ./drawing\n");
printf("\nThis program demonstrates OpenCV drawing and text output functions.\n"
"Usage:\n"
" ./drawing\n");
}
static Scalar randomColor(RNG& rng)
{
@@ -18,7 +18,7 @@ static Scalar randomColor(RNG& rng)
int main()
{
help();
char wndname[] = "Drawing Demo";
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
@@ -39,7 +39,7 @@ int main()
pt2.y = rng.uniform(y1, y2);
line( image, pt1, pt2, randomColor(rng), rng.uniform(1,10), lineType );
imshow(wndname, image);
if(waitKey(DELAY) >= 0)
return 0;
@@ -53,14 +53,14 @@ int main()
pt2.x = rng.uniform(x1, x2);
pt2.y = rng.uniform(y1, y2);
int thickness = rng.uniform(-3, 10);
rectangle( image, pt1, pt2, randomColor(rng), MAX(thickness, -1), lineType );
imshow(wndname, image);
if(waitKey(DELAY) >= 0)
return 0;
}
for (i = 0; i < NUMBER; i++)
{
Point center;
@@ -73,7 +73,7 @@ int main()
ellipse( image, center, axes, angle, angle - 100, angle + 200,
randomColor(rng), rng.uniform(-1,9), lineType );
imshow(wndname, image);
if(waitKey(DELAY) >= 0)
return 0;
@@ -84,46 +84,46 @@ int main()
Point pt[2][3];
pt[0][0].x = rng.uniform(x1, x2);
pt[0][0].y = rng.uniform(y1, y2);
pt[0][1].x = rng.uniform(x1, x2);
pt[0][1].y = rng.uniform(y1, y2);
pt[0][1].x = rng.uniform(x1, x2);
pt[0][1].y = rng.uniform(y1, y2);
pt[0][2].x = rng.uniform(x1, x2);
pt[0][2].y = rng.uniform(y1, y2);
pt[1][0].x = rng.uniform(x1, x2);
pt[1][0].x = rng.uniform(x1, x2);
pt[1][0].y = rng.uniform(y1, y2);
pt[1][1].x = rng.uniform(x1, x2);
pt[1][1].x = rng.uniform(x1, x2);
pt[1][1].y = rng.uniform(y1, y2);
pt[1][2].x = rng.uniform(x1, x2);
pt[1][2].x = rng.uniform(x1, x2);
pt[1][2].y = rng.uniform(y1, y2);
const Point* ppt[2] = {pt[0], pt[1]};
int npt[] = {3, 3};
polylines(image, ppt, npt, 2, true, randomColor(rng), rng.uniform(1,10), lineType);
imshow(wndname, image);
if(waitKey(DELAY) >= 0)
return 0;
}
for (i = 0; i< NUMBER; i++)
{
Point pt[2][3];
pt[0][0].x = rng.uniform(x1, x2);
pt[0][0].y = rng.uniform(y1, y2);
pt[0][1].x = rng.uniform(x1, x2);
pt[0][1].y = rng.uniform(y1, y2);
pt[0][1].x = rng.uniform(x1, x2);
pt[0][1].y = rng.uniform(y1, y2);
pt[0][2].x = rng.uniform(x1, x2);
pt[0][2].y = rng.uniform(y1, y2);
pt[1][0].x = rng.uniform(x1, x2);
pt[1][0].x = rng.uniform(x1, x2);
pt[1][0].y = rng.uniform(y1, y2);
pt[1][1].x = rng.uniform(x1, x2);
pt[1][1].x = rng.uniform(x1, x2);
pt[1][1].y = rng.uniform(y1, y2);
pt[1][2].x = rng.uniform(x1, x2);
pt[1][2].x = rng.uniform(x1, x2);
pt[1][2].y = rng.uniform(y1, y2);
const Point* ppt[2] = {pt[0], pt[1]};
int npt[] = {3, 3};
fillPoly(image, ppt, npt, 2, randomColor(rng), lineType);
imshow(wndname, image);
if(waitKey(DELAY) >= 0)
return 0;
@@ -134,10 +134,10 @@ int main()
Point center;
center.x = rng.uniform(x1, x2);
center.y = rng.uniform(y1, y2);
circle(image, center, rng.uniform(0, 300), randomColor(rng),
rng.uniform(-1, 9), lineType);
imshow(wndname, image);
if(waitKey(DELAY) >= 0)
return 0;
@@ -151,7 +151,7 @@ int main()
putText(image, "Testing text rendering", org, rng.uniform(0,8),
rng.uniform(0,100)*0.05+0.1, randomColor(rng), rng.uniform(1, 10), lineType);
imshow(wndname, image);
if(waitKey(DELAY) >= 0)
return 0;
@@ -159,14 +159,14 @@ int main()
Size textsize = getTextSize("OpenCV forever!", CV_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,
Scalar(i, i, 255), 5, lineType);
imshow(wndname, image2);
if(waitKey(DELAY) >= 0)
return 0;

View File

@@ -10,42 +10,42 @@ int edgeThresh = 1;
Mat image, gray, edge, cedge;
// define a trackbar callback
void onTrackbar(int, void*)
static void onTrackbar(int, void*)
{
blur(gray, edge, Size(3,3));
// Run the edge detector on grayscale
Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
cedge = Scalar::all(0);
image.copyTo(cedge, edge);
imshow("Edge map", cedge);
}
void help()
static void help()
{
printf("\nThis sample demonstrates Canny edge detection\n"
"Call:\n"
" /.edge [image_name -- Default is fruits.jpg]\n\n");
printf("\nThis sample demonstrates Canny edge detection\n"
"Call:\n"
" /.edge [image_name -- Default is fruits.jpg]\n\n");
}
const char* keys =
const char* keys =
{
"{1| |fruits.jpg|input image name}"
"{1| |fruits.jpg|input image name}"
};
int main( int argc, const char** argv )
{
help();
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>("1");
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>("1");
image = imread(filename, 1);
if(image.empty())
{
printf("Cannot read image file: %s\n", filename.c_str());
help();
printf("Cannot read image file: %s\n", filename.c_str());
help();
return -1;
}
cedge.create(image.size(), image.type());

View File

@@ -25,7 +25,7 @@
using namespace cv;
using namespace std;
Mat toGrayscale(InputArray _src) {
static Mat toGrayscale(InputArray _src) {
Mat src = _src.getMat();
// only allow one channel
if(src.channels() != 1)
@@ -36,7 +36,7 @@ Mat toGrayscale(InputArray _src) {
return dst;
}
void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file)
throw std::exception();

View File

@@ -7,16 +7,16 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout <<
"\nThis program demonstrates dense optical flow algorithm by Gunnar Farneback\n"
"Mainly the function: calcOpticalFlowFarneback()\n"
"Call:\n"
"./fback\n"
"This reads from video camera 0\n" << endl;
cout <<
"\nThis program demonstrates dense optical flow algorithm by Gunnar Farneback\n"
"Mainly the function: calcOpticalFlowFarneback()\n"
"Call:\n"
"./fback\n"
"This reads from video camera 0\n" << endl;
}
void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step,
static void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step,
double, const Scalar& color)
{
for(int y = 0; y < cflowmap.rows; y += step)
@@ -35,15 +35,15 @@ int main(int, char**)
help();
if( !cap.isOpened() )
return -1;
Mat prevgray, gray, flow, cflow, frame;
namedWindow("flow", 1);
for(;;)
{
cap >> frame;
cvtColor(frame, gray, CV_BGR2GRAY);
if( prevgray.data )
{
calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, 3, 15, 3, 5, 1.2, 0);

View File

@@ -6,22 +6,22 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nThis program demonstrated the floodFill() function\n"
"Call:\n"
"./ffilldemo [image_name -- Default: fruits.jpg]\n" << endl;
"Call:\n"
"./ffilldemo [image_name -- Default: fruits.jpg]\n" << endl;
cout << "Hot keys: \n"
"\tESC - quit the program\n"
"\tc - switch color/grayscale mode\n"
"\tm - switch mask mode\n"
"\tr - restore the original image\n"
"\ts - use null-range floodfill\n"
"\tf - use gradient floodfill with fixed(absolute) range\n"
"\tg - use gradient floodfill with floating(relative) range\n"
"\t4 - use 4-connectivity mode\n"
"\t8 - use 8-connectivity mode\n" << endl;
cout << "Hot keys: \n"
"\tESC - quit the program\n"
"\tc - switch color/grayscale mode\n"
"\tm - switch mask mode\n"
"\tr - restore the original image\n"
"\ts - use null-range floodfill\n"
"\tf - use gradient floodfill with fixed(absolute) range\n"
"\tg - use gradient floodfill with floating(relative) range\n"
"\t4 - use 4-connectivity mode\n"
"\t8 - use 8-connectivity mode\n" << endl;
}
Mat image0, image, gray, mask;
@@ -32,7 +32,7 @@ int isColor = true;
bool useMask = false;
int newMaskVal = 255;
void onMouse( int event, int x, int y, int, void* )
static void onMouse( int event, int x, int y, int, void* )
{
if( event != CV_EVENT_LBUTTONDOWN )
return;
@@ -50,7 +50,7 @@ void onMouse( int event, int x, int y, int, void* )
Scalar newVal = isColor ? Scalar(b, g, r) : Scalar(r*0.299 + g*0.587 + b*0.114);
Mat dst = isColor ? image : gray;
int area;
if( useMask )
{
threshold(mask, mask, 1, 128, CV_THRESH_BINARY);
@@ -63,7 +63,7 @@ void onMouse( int event, int x, int y, int, void* )
area = floodFill(dst, seed, newVal, &ccomp, Scalar(lo, lo, lo),
Scalar(up, up, up), flags);
}
imshow("image", dst);
cout << area << " pixels were repainted\n";
}
@@ -73,7 +73,7 @@ int main( int argc, char** argv )
{
char* filename = argc >= 2 ? argv[1] : (char*)"fruits.jpg";
image0 = imread(filename, 1);
if( image0.empty() )
{
cout << "Image empty. Usage: ffilldemo <image_name>\n";

View File

@@ -13,15 +13,15 @@ using std::cerr;
using std::ostream;
using namespace cv;
void help(char** av)
static void help(char** av)
{
cout << "\nfilestorage_sample demonstrate the usage of the opencv serialization functionality.\n"
<< "usage:\n"
<< av[0] << " outputfile.yml.gz\n"
<< "\n outputfile above can have many different extenstions, see below."
<< "\nThis program demonstrates the use of FileStorage for serialization, that is use << and >> in OpenCV\n"
<< "For example, how to create a class and have it serialize, but also how to use it to read and write matrices.\n"
<< "FileStorage allows you to serialize to various formats specified by the file end type."
<< "usage:\n"
<< av[0] << " outputfile.yml.gz\n"
<< "\n outputfile above can have many different extenstions, see below."
<< "\nThis program demonstrates the use of FileStorage for serialization, that is use << and >> in OpenCV\n"
<< "For example, how to create a class and have it serialize, but also how to use it to read and write matrices.\n"
<< "FileStorage allows you to serialize to various formats specified by the file end type."
<< "\nYou should try using different file extensions.(e.g. yaml yml xml xml.gz yaml.gz etc...)\n" << endl;
}
@@ -52,17 +52,17 @@ struct MyData
};
//These write and read functions must exist as per the inline functions in operations.hpp
void write(FileStorage& fs, const std::string&, const MyData& x){
static void write(FileStorage& fs, const std::string&, const MyData& x){
x.write(fs);
}
void read(const FileNode& node, MyData& x, const MyData& default_value = MyData()){
static void read(const FileNode& node, MyData& x, const MyData& default_value = MyData()){
if(node.empty())
x = default_value;
else
x.read(node);
}
ostream& operator<<(ostream& out, const MyData& m){
static ostream& operator<<(ostream& out, const MyData& m){
out << "{ id = " << m.id << ", ";
out << "X = " << m.X << ", ";
out << "A = " << m.A << "}";

View File

@@ -20,14 +20,14 @@
using namespace cv;
using namespace std;
void help()
{
cout <<
"\nThis program is demonstration for ellipse fitting. The program finds\n"
"contours and approximate it by ellipses.\n"
"Call:\n"
"./fitellipse [image_name -- Default stuff.jpg]\n" << endl;
}
// static void help()
// {
// cout <<
// "\nThis program is demonstration for ellipse fitting. The program finds\n"
// "contours and approximate it by ellipses.\n"
// "Call:\n"
// "./fitellipse [image_name -- Default stuff.jpg]\n" << endl;
// }
int sliderPos = 70;
@@ -47,7 +47,7 @@ int main( int argc, char** argv )
imshow("source", image);
namedWindow("result", 1);
// Create toolbars. HighGUI use.
createTrackbar( "threshold", "result", &sliderPos, 255, processImage );
processImage(0, 0);
@@ -63,7 +63,7 @@ void processImage(int /*h*/, void*)
{
vector<vector<Point> > contours;
Mat bimage = image >= sliderPos;
findContours(bimage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
Mat cimage = Mat::zeros(bimage.size(), CV_8UC3);
@@ -73,11 +73,11 @@ void processImage(int /*h*/, void*)
size_t count = contours[i].size();
if( count < 6 )
continue;
Mat pointsf;
Mat(contours[i]).convertTo(pointsf, CV_32F);
RotatedRect box = fitEllipse(pointsf);
if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 )
continue;
drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8);

View File

@@ -8,7 +8,7 @@
using namespace cv;
void help()
static void help()
{
printf("Use the SURF descriptor for matching keypoints between 2 images\n");
printf("Format: \n./generic_descriptor_match <image1> <image2> <algorithm> <XML params>\n");
@@ -22,7 +22,7 @@ int main(int argc, char** argv)
{
if (argc != 5)
{
help();
help();
return 0;
}
@@ -41,14 +41,14 @@ int main(int argc, char** argv)
//printf("Reading the images...\n");
Mat img1 = imread(img1_name, CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(img2_name, CV_LOAD_IMAGE_GRAYSCALE);
// extract keypoints from the first image
SURF surf_extractor(5.0e3);
vector<KeyPoint> keypoints1;
// printf("Extracting keypoints\n");
surf_extractor(img1, Mat(), keypoints1);
printf("Extracted %d keypoints from the first image\n", (int)keypoints1.size());
vector<KeyPoint> keypoints2;

View File

@@ -6,7 +6,7 @@
using namespace std;
using namespace cv;
void help()
static void help()
{
cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n"
"and then grabcut will attempt to segment it out.\n"
@@ -36,7 +36,7 @@ const Scalar GREEN = Scalar(0,255,0);
const int BGD_KEY = CV_EVENT_FLAG_CTRLKEY;
const int FGD_KEY = CV_EVENT_FLAG_SHIFTKEY;
void getBinMask( const Mat& comMask, Mat& binMask )
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)" );
@@ -268,7 +268,7 @@ int GCApplication::nextIter()
GCApplication gcapp;
void on_mouse( int event, int x, int y, int flags, void* param )
static void on_mouse( int event, int x, int y, int flags, void* param )
{
gcapp.mouseClick( event, x, y, flags, param );
}

View File

@@ -6,7 +6,7 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
"Usage:\n"
@@ -28,10 +28,10 @@ int main(int argc, char** argv)
Mat cimg;
medianBlur(img, img, 5);
cvtColor(img, cimg, CV_GRAY2BGR);
vector<Vec3f> circles;
HoughCircles(img, circles, CV_HOUGH_GRADIENT, 1, 10,
100, 30, 1, 30 // change the last two parameters
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++ )

View File

@@ -6,7 +6,7 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nThis program demonstrates line finding with the Hough transform.\n"
"Usage:\n"

View File

@@ -32,151 +32,151 @@ bool selectObject = false;
int trackObject = 0;
int live = 1;
void drawRectangle(Mat* image, Rect win) {
rectangle(*image, Point(win.x, win.y), Point(win.x + win.width, win.y
+ win.height), Scalar(0, 255, 0), 2, CV_AA);
static void drawRectangle(Mat* image, Rect win) {
rectangle(*image, Point(win.x, win.y), Point(win.x + win.width, win.y
+ win.height), Scalar(0, 255, 0), 2, CV_AA);
}
void onMouse(int event, int x, int y, int, void*) {
if (selectObject) {
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = std::abs(x - origin.x);
selection.height = std::abs(y - origin.y);
selection &= Rect(0, 0, image.cols, image.rows);
}
static void onMouse(int event, int x, int y, int, void*) {
if (selectObject) {
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = std::abs(x - origin.x);
selection.height = std::abs(y - origin.y);
selection &= Rect(0, 0, image.cols, image.rows);
}
switch (event) {
case CV_EVENT_LBUTTONDOWN:
origin = Point(x, y);
selection = Rect(x, y, 0, 0);
selectObject = true;
break;
case CV_EVENT_LBUTTONUP:
selectObject = false;
trackObject = -1;
break;
}
switch (event) {
case CV_EVENT_LBUTTONDOWN:
origin = Point(x, y);
selection = Rect(x, y, 0, 0);
selectObject = true;
break;
case CV_EVENT_LBUTTONUP:
selectObject = false;
trackObject = -1;
break;
}
}
void help()
static void help()
{
printf("Usage: ./hytrack live or ./hytrack <test_file> \n\
printf("Usage: ./hytrack live or ./hytrack <test_file> \n\
For Live View or Benchmarking. Read documentation is source code.\n\n");
}
int main(int argc, char** argv)
{
if(argc != 2) {
help();
return 1;
}
if(argc != 2) {
help();
return 1;
}
FILE* f = 0;
VideoCapture cap;
char test_file[20] = "";
FILE* f = 0;
VideoCapture cap;
char test_file[20] = "";
if (strcmp(argv[1], "live") != 0)
{
sprintf(test_file, "%s", argv[1]);
f = fopen(test_file, "r");
char vid[20];
int values_read = fscanf(f, "%s\n", vid);
CV_Assert(values_read == 1);
cout << "Benchmarking against " << vid << endl;
live = 0;
}
else
{
cap.open(0);
if (!cap.isOpened())
{
cout << "Failed to open camera" << endl;
return 0;
}
cout << "Opened camera" << endl;
if (strcmp(argv[1], "live") != 0)
{
sprintf(test_file, "%s", argv[1]);
f = fopen(test_file, "r");
char vid[20];
int values_read = fscanf(f, "%s\n", vid);
CV_Assert(values_read == 1);
cout << "Benchmarking against " << vid << endl;
live = 0;
}
else
{
cap.open(0);
if (!cap.isOpened())
{
cout << "Failed to open camera" << endl;
return 0;
}
cout << "Opened camera" << endl;
cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
cap >> frame;
}
HybridTrackerParams params;
// motion model params
params.motion_model = CvMotionModel::LOW_PASS_FILTER;
params.low_pass_gain = 0.1f;
// mean shift params
params.ms_tracker_weight = 0.8f;
params.ms_params.tracking_type = CvMeanShiftTrackerParams::HS;
// feature tracking params
params.ft_tracker_weight = 0.2f;
params.ft_params.feature_type = CvFeatureTrackerParams::OPTICAL_FLOW;
params.ft_params.window_size = 0;
cap >> frame;
}
HybridTracker tracker(params);
char img_file[20] = "seqG/0001.png";
char img_file_num[10];
namedWindow("Win", 1);
HybridTrackerParams params;
// motion model params
params.motion_model = CvMotionModel::LOW_PASS_FILTER;
params.low_pass_gain = 0.1f;
// mean shift params
params.ms_tracker_weight = 0.8f;
params.ms_params.tracking_type = CvMeanShiftTrackerParams::HS;
// feature tracking params
params.ft_tracker_weight = 0.2f;
params.ft_params.feature_type = CvFeatureTrackerParams::OPTICAL_FLOW;
params.ft_params.window_size = 0;
setMouseCallback("Win", onMouse, 0);
HybridTracker tracker(params);
char img_file[20] = "seqG/0001.png";
char img_file_num[10];
namedWindow("Win", 1);
int i = 0;
float w[4];
for(;;)
{
i++;
if (live)
{
cap >> frame;
setMouseCallback("Win", onMouse, 0);
int i = 0;
float w[4];
for(;;)
{
i++;
if (live)
{
cap >> frame;
if( frame.empty() )
break;
frame.copyTo(image);
}
else
{
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);
frame.copyTo(image);
}
else
{
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);
if (image.empty())
break;
selection = Rect(cvRound(w[0]*image.cols), cvRound(w[1]*image.rows),
break;
selection = Rect(cvRound(w[0]*image.cols), cvRound(w[1]*image.rows),
cvRound(w[2]*image.cols), cvRound(w[3]*image.rows));
}
}
sprintf(img_file_num, "Frame: %d", i);
putText(image, img_file_num, Point(10, image.rows-20), FONT_HERSHEY_PLAIN, 0.75, Scalar(255, 255, 255));
if (!image.empty())
{
sprintf(img_file_num, "Frame: %d", i);
putText(image, img_file_num, Point(10, image.rows-20), FONT_HERSHEY_PLAIN, 0.75, Scalar(255, 255, 255));
if (!image.empty())
{
if (trackObject < 0)
{
tracker.newTracker(image, selection);
trackObject = 1;
}
if (trackObject < 0)
{
tracker.newTracker(image, selection);
trackObject = 1;
}
if (trackObject)
{
tracker.updateTracker(image);
drawRectangle(&image, tracker.getTrackingWindow());
}
if (trackObject)
{
tracker.updateTracker(image);
drawRectangle(&image, tracker.getTrackingWindow());
}
if (selectObject && selection.width > 0 && selection.height > 0)
{
Mat roi(image, selection);
bitwise_not(roi, roi);
}
if (selectObject && selection.width > 0 && selection.height > 0)
{
Mat roi(image, selection);
bitwise_not(roi, roi);
}
drawRectangle(&image, Rect(cvRound(w[0]*image.cols), cvRound(w[1]*image.rows),
drawRectangle(&image, Rect(cvRound(w[0]*image.cols), cvRound(w[1]*image.rows),
cvRound(w[2]*image.cols), cvRound(w[3]*image.rows)));
imshow("Win", image);
imshow("Win", image);
waitKey(100);
}
else
i = 0;
}
waitKey(100);
}
else
i = 0;
}
fclose(f);
return 0;
fclose(f);
return 0;
}

View File

@@ -8,14 +8,14 @@ using namespace cv; // all the new API is put into "cv" namespace. Export its co
using namespace std;
using namespace cv::flann;
void help()
static void help()
{
cout <<
"\nThis program shows how to use cv::Mat and IplImages converting back and forth.\n"
"It shows reading of images, converting to planes and merging back, color conversion\n"
"and also iterating through pixels.\n"
"Call:\n"
"./image [image-name Default: lena.jpg]\n" << endl;
cout <<
"\nThis program shows how to use cv::Mat and IplImages converting back and forth.\n"
"It shows reading of images, converting to planes and merging back, color conversion\n"
"and also iterating through pixels.\n"
"Call:\n"
"./image [image-name Default: lena.jpg]\n" << endl;
}
// enable/disable use of mixed API in the code below.
@@ -23,7 +23,7 @@ void help()
int main( int argc, char** argv )
{
help();
help();
const char* imagename = argc > 1 ? argv[1] : "lena.jpg";
#if DEMO_MIXED_API_USE
Ptr<IplImage> iplimg = cvLoadImage(imagename); // Ptr<T> is safe ref-conting pointer class
@@ -43,16 +43,16 @@ int main( int argc, char** argv )
return -1;
}
#endif
if( !img.data ) // check if the image has been loaded properly
return -1;
Mat img_yuv;
cvtColor(img, img_yuv, CV_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
#if 1
// method 1. process Y plane using an iterator
MatIterator_<uchar> it = planes[0].begin<uchar>(), it_end = planes[0].end<uchar>();
@@ -61,7 +61,7 @@ int main( int argc, char** argv )
double v = *it*1.7 + rand()%21-10;
*it = saturate_cast<uchar>(v*v/255.);
}
// method 2. process the first chroma plane using pre-stored row pointer.
// method 3. process the second chroma plane using individual element access
for( int y = 0; y < img_yuv.rows; y++ )
@@ -74,13 +74,13 @@ int main( int argc, char** argv )
Vxy = saturate_cast<uchar>((Vxy-128)/2 + 128);
}
}
#else
Mat noise(img.size(), CV_8U); // another Mat constructor; allocates a matrix of the specified size and type
randn(noise, Scalar::all(128), Scalar::all(20)); // fills the matrix with normally distributed random values;
// there is also randu() for uniformly distributed random number generation
GaussianBlur(noise, noise, Size(3, 3), 0.5, 0.5); // blur the noise a bit, kernel size is 3x3 and both sigma's are set to 0.5
const double brightness_gain = 0;
const double contrast_gain = 1.7;
#if DEMO_MIXED_API_USE
@@ -98,16 +98,16 @@ int main( int argc, char** argv )
// alternative form of cv::convertScale if we know the datatype at compile time ("uchar" here).
// This expression will not create any temporary arrays and should be almost as fast as the above variant
planes[2] = Mat_<uchar>(planes[2]*color_scale + 128*(1-color_scale));
// Mat::mul replaces cvMul(). Again, no temporary arrays are created in case of simple expressions.
planes[0] = planes[0].mul(planes[0], 1./255);
#endif
// now merge the results back
merge(planes, img_yuv);
// and produce the output RGB image
cvtColor(img_yuv, img, CV_YCrCb2BGR);
// this is counterpart for cvNamedWindow
namedWindow("image with grain", CV_WINDOW_AUTOSIZE);
#if DEMO_MIXED_API_USE
@@ -118,7 +118,7 @@ int main( int argc, char** argv )
imshow("image with grain", img);
#endif
waitKey();
return 0;
// all the memory will automatically be released by Vector<>, Mat and Ptr<> destructors.
}

View File

@@ -12,10 +12,10 @@ using std::endl;
using namespace cv;
void help(char** av)
static void help(char** av)
{
cout << "\nThis creates a yaml or xml list of files from the command line args\n"
"usage:\n./" << av[0] << " imagelist.yaml *.png\n"
"usage:\n./" << av[0] << " imagelist.yaml *.png\n"
<< "Try using different extensions.(e.g. yaml yml xml xml.gz etc...)\n"
<< "This will serialize this list of images or whatever with opencv's FileStorage framework" << endl;
}

View File

@@ -7,13 +7,13 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nCool inpainging demo. Inpainting repairs damage to images by floodfilling the damage \n"
<< "with surrounding image areas.\n"
"Using OpenCV version %s\n" << CV_VERSION << "\n"
"Usage:\n"
"./inpaint [image_name -- Default fruits.jpg]\n" << endl;
<< "with surrounding image areas.\n"
"Using OpenCV version %s\n" << CV_VERSION << "\n"
"Usage:\n"
"./inpaint [image_name -- Default fruits.jpg]\n" << endl;
cout << "Hot keys: \n"
"\tESC - quit the program\n"
@@ -25,7 +25,7 @@ void help()
Mat img, inpaintMask;
Point prevPt(-1,-1);
void onMouse( int event, int x, int y, int flags, void* )
static void onMouse( int event, int x, int y, int flags, void* )
{
if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) )
prevPt = Point(-1,-1);
@@ -55,7 +55,7 @@ int main( int argc, char** argv )
}
help();
namedWindow( "image", 1 );
img = img0.clone();

View File

@@ -10,9 +10,9 @@ static inline Point calcPoint(Point2f center, double R, double angle)
return center + Point2f((float)cos(angle), (float)-sin(angle))*(float)R;
}
void help()
static void help()
{
printf( "\nExamle of c calls to OpenCV's Kalman filter.\n"
printf( "\nExamle of c calls to OpenCV's Kalman filter.\n"
" Tracking of rotating point.\n"
" Rotation speed is constant.\n"
" Both state and measurements vectors are 1D (a point angle),\n"
@@ -21,10 +21,10 @@ void help()
" the real and the measured points are connected with red line segment.\n"
" (if Kalman filter works correctly,\n"
" the yellow segment should be shorter than the red one).\n"
"\n"
"\n"
" Pressing any key (except ESC) will reset the tracking with a different speed.\n"
" Pressing ESC will stop the program.\n"
);
);
}
int main(int, char**)

View File

@@ -5,14 +5,14 @@
using namespace cv;
using namespace std;
void help()
{
cout << "\nThis program demonstrates kmeans clustering.\n"
"It generates an image with random points, then assigns a random number of cluster\n"
"centers and uses kmeans to move those cluster centers to their representitive location\n"
"Call\n"
"./kmeans\n" << endl;
}
// static void help()
// {
// cout << "\nThis program demonstrates kmeans clustering.\n"
// "It generates an image with random points, then assigns a random number of cluster\n"
// "centers and uses kmeans to move those cluster centers to their representitive location\n"
// "Call\n"
// "./kmeans\n" << endl;
// }
int main( int /*argc*/, char** /*argv*/ )
{
@@ -25,7 +25,7 @@ int main( int /*argc*/, char** /*argv*/ )
Scalar(255,0,255),
Scalar(0,255,255)
};
Mat img(500, 500, CV_8UC3);
RNG rng(12345);
@@ -34,7 +34,7 @@ int main( int /*argc*/, char** /*argv*/ )
int k, clusterCount = rng.uniform(2, MAX_CLUSTERS+1);
int i, sampleCount = rng.uniform(1, 1001);
Mat points(sampleCount, 1, CV_32FC2), labels;
clusterCount = MIN(clusterCount, sampleCount);
Mat centers(clusterCount, 1, points.type());
@@ -52,7 +52,7 @@ int main( int /*argc*/, char** /*argv*/ )
randShuffle(points, 1, &rng);
kmeans(points, clusterCount, labels,
kmeans(points, clusterCount, labels,
TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0),
3, KMEANS_PP_CENTERS, centers);

View File

@@ -8,13 +8,13 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout <<
"\nThis program demonstrates Laplace point/edge detection using OpenCV function Laplacian()\n"
"It captures from the camera of your choice: 0, 1, ... default 0\n"
"Call:\n"
"./laplace [camera #, default 0]\n" << endl;
cout <<
"\nThis program demonstrates Laplace point/edge detection using OpenCV function Laplacian()\n"
"It captures from the camera of your choice: 0, 1, ... default 0\n"
"Call:\n"
"./laplace [camera #, default 0]\n" << endl;
}
int sigma = 3;
@@ -54,7 +54,7 @@ int main( int argc, char** argv )
createTrackbar( "Sigma", "Laplacian", &sigma, 15, 0 );
Mat smoothed, laplace, result;
for(;;)
{
Mat frame;
@@ -69,7 +69,7 @@ int main( int argc, char** argv )
blur(frame, smoothed, Size(ksize, ksize));
else
medianBlur(frame, smoothed, ksize);
Laplacian(smoothed, laplace, CV_16S, 5);
convertScaleAbs(laplace, result, (sigma+1)*0.25);
imshow("Laplacian", result);

View File

@@ -9,8 +9,8 @@
#include <dirent.h>
#endif
#ifdef HAVE_CVCONFIG_H
#include <cvconfig.h>
#ifdef HAVE_CVCONFIG_H
#include <cvconfig.h>
#endif
#ifdef HAVE_TBB
@@ -20,7 +20,7 @@
using namespace std;
using namespace cv;
void help()
static void help()
{
cout << "This program demonstrated the use of the latentSVM detector." << endl <<
"It reads in a trained object models and then uses them to detect the objects in an images." << endl <<
@@ -36,7 +36,7 @@ void help()
endl;
}
void detectAndDrawObjects( Mat& image, LatentSvmDetector& detector, const vector<Scalar>& colors, float overlapThreshold, int numThreads )
static void detectAndDrawObjects( Mat& image, LatentSvmDetector& detector, const vector<Scalar>& colors, float overlapThreshold, int numThreads )
{
vector<LatentSvmDetector::ObjectDetection> detections;
@@ -63,7 +63,7 @@ void detectAndDrawObjects( Mat& image, LatentSvmDetector& detector, const vector
}
}
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();
@@ -71,8 +71,8 @@ void readDirectory( const string& directoryName, vector<string>& filenames, bool
struct _finddata_t s_file;
string str = directoryName + "\\*.*";
intptr_t h_file = _findfirst( str.c_str(), &s_file );
if( h_file != static_cast<intptr_t>(-1.0) )
intptr_t h_file = _findfirst( str.c_str(), &s_file );
if( h_file != static_cast<intptr_t>(-1.0) )
{
do
{
@@ -104,13 +104,13 @@ void readDirectory( const string& directoryName, vector<string>& filenames, bool
int main(int argc, char* argv[])
{
help();
help();
string images_folder, models_folder;
float overlapThreshold = 0.2f;
int numThreads = -1;
if( argc > 2 )
{
{
images_folder = argv[1];
models_folder = argv[2];
if( argc > 3 ) overlapThreshold = (float)atof(argv[3]);
@@ -121,7 +121,7 @@ int main(int argc, char* argv[])
}
if( argc > 4 ) numThreads = atoi(argv[4]);
}
}
vector<string> images_filenames, models_filenames;
readDirectory( images_folder, images_filenames );
@@ -166,6 +166,6 @@ int main(int argc, char* argv[])
exit(0);
}
}
return 0;
return 0;
}

View File

@@ -7,24 +7,24 @@
*/
void help()
static void help()
{
printf("\nThe sample demonstrates how to train Random Trees classifier\n"
"(or Boosting classifier, or MLP, or Knearest, or Nbayes, or Support Vector Machines - see main()) using the provided dataset.\n"
"\n"
"We use the sample database letter-recognition.data\n"
"from UCI Repository, here is the link:\n"
"\n"
"Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).\n"
"UCI Repository of machine learning databases\n"
"[http://www.ics.uci.edu/~mlearn/MLRepository.html].\n"
"Irvine, CA: University of California, Department of Information and Computer Science.\n"
"\n"
"The dataset consists of 20000 feature vectors along with the\n"
"responses - capital latin letters A..Z.\n"
"The first 16000 (10000 for boosting)) samples are used for training\n"
"and the remaining 4000 (10000 for boosting) - to test the classifier.\n"
"======================================================\n");
printf("\nThe sample demonstrates how to train Random Trees classifier\n"
"(or Boosting classifier, or MLP, or Knearest, or Nbayes, or Support Vector Machines - see main()) using the provided dataset.\n"
"\n"
"We use the sample database letter-recognition.data\n"
"from UCI Repository, here is the link:\n"
"\n"
"Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).\n"
"UCI Repository of machine learning databases\n"
"[http://www.ics.uci.edu/~mlearn/MLRepository.html].\n"
"Irvine, CA: University of California, Department of Information and Computer Science.\n"
"\n"
"The dataset consists of 20000 feature vectors along with the\n"
"responses - capital latin letters A..Z.\n"
"The first 16000 (10000 for boosting)) samples are used for training\n"
"and the remaining 4000 (10000 for boosting) - to test the classifier.\n"
"======================================================\n");
printf("\nThis is letter recognition sample.\n"
"The usage: letter_recog [-data <path to letter-recognition.data>] \\\n"
" [-save <output XML file for the classifier>] \\\n"
@@ -312,7 +312,7 @@ int build_boost_classifier( char* data_filename,
}
temp_sample = cvCreateMat( 1, var_count + 1, CV_32F );
weak_responses = cvCreateMat( 1, boost.get_weak_predictors()->total, CV_32F );
weak_responses = cvCreateMat( 1, boost.get_weak_predictors()->total, CV_32F );
// compute prediction error on train and test data
for( i = 0; i < nsamples_all; i++ )
@@ -548,7 +548,7 @@ int build_knearest_classifier( char* data_filename, int K )
}
}
printf("true_resp = %f%%\tavg accuracy = %f%%\n", (float)true_resp / (nsamples_all - ntrain_samples) * 100,
printf("true_resp = %f%%\tavg accuracy = %f%%\n", (float)true_resp / (nsamples_all - ntrain_samples) * 100,
(float)accuracy / (nsamples_all - ntrain_samples) / K * 100);
delete[] true_results;
@@ -674,15 +674,15 @@ int build_svm_classifier( char* data_filename )
for (int j = ntrain_samples; j < nsamples_all; j++)
{
float *s = data->data.fl + j * var_count;
for (int i = 0; i < var_count; i++)
{
{
sample.data.fl[(j - ntrain_samples) * var_count + i] = s[i];
}
true_results[j - ntrain_samples] = responses->data.fl[j];
}
CvMat *result = cvCreateMat(1, nsamples_all - ntrain_samples, CV_32FC1);
printf("Classification (may take a few minutes)...\n");
svm.predict(&sample, result);
@@ -692,9 +692,9 @@ int build_svm_classifier( char* data_filename )
if (result->data.fl[i] == true_results[i])
true_resp++;
}
printf("true_resp = %f%%\n", (float)true_resp / (nsamples_all - ntrain_samples) * 100);
cvReleaseMat( &train_resp );
cvReleaseMat( &result );
cvReleaseMat( &data );
@@ -738,17 +738,17 @@ int main( int argc, char *argv[] )
method = 2;
}
else if ( strcmp(argv[i], "-knearest") == 0)
{
method = 3;
}
else if ( strcmp(argv[i], "-nbayes") == 0)
{
method = 4;
}
else if ( strcmp(argv[i], "-svm") == 0)
{
method = 5;
}
{
method = 3;
}
else if ( strcmp(argv[i], "-nbayes") == 0)
{
method = 4;
}
else if ( strcmp(argv[i], "-svm") == 0)
{
method = 5;
}
else
break;
}
@@ -768,7 +768,7 @@ int main( int argc, char *argv[] )
build_svm_classifier( data_filename ):
-1) < 0)
{
help();
help();
}
return 0;
}

View File

@@ -11,15 +11,15 @@
// Function prototypes
void subtractPlane(const cv::Mat& depth, cv::Mat& mask, std::vector<CvPoint>& chain, double f);
std::vector<CvPoint> maskFromTemplate(const std::vector<cv::linemod::Template>& templates,
std::vector<CvPoint> maskFromTemplate(const std::vector<cv::linemod::Template>& templates,
int num_modalities, cv::Point offset, cv::Size size,
cv::Mat& mask, cv::Mat& dst);
void templateConvexHull(const std::vector<cv::linemod::Template>& templates,
void templateConvexHull(const std::vector<cv::linemod::Template>& templates,
int num_modalities, cv::Point offset, cv::Size size,
cv::Mat& dst);
void drawResponse(const std::vector<cv::linemod::Template>& templates,
void drawResponse(const std::vector<cv::linemod::Template>& templates,
int num_modalities, cv::Mat& dst, cv::Point offset, int T);
cv::Mat displayQuantized(const cv::Mat& quantized);
@@ -54,7 +54,7 @@ private:
m_x = a_x;
m_y = a_y;
}
static int m_event;
static int m_x;
static int m_y;
@@ -63,7 +63,7 @@ int Mouse::m_event;
int Mouse::m_x;
int Mouse::m_y;
void help()
static void help()
{
printf("Usage: openni_demo [templates.yml]\n\n"
"Place your object on a planar, featureless surface. With the mouse,\n"
@@ -111,7 +111,7 @@ private:
};
// Functions to store detector and templates in single XML/YAML file
cv::Ptr<cv::linemod::Detector> readLinemod(const std::string& filename)
static cv::Ptr<cv::linemod::Detector> readLinemod(const std::string& filename)
{
cv::Ptr<cv::linemod::Detector> detector = new cv::linemod::Detector;
cv::FileStorage fs(filename, cv::FileStorage::READ);
@@ -124,7 +124,7 @@ cv::Ptr<cv::linemod::Detector> readLinemod(const std::string& filename)
return detector;
}
void writeLinemod(const cv::Ptr<cv::linemod::Detector>& detector, const std::string& filename)
static void writeLinemod(const cv::Ptr<cv::linemod::Detector>& detector, const std::string& filename)
{
cv::FileStorage fs(filename, cv::FileStorage::WRITE);
detector->write(fs);
@@ -207,7 +207,7 @@ int main(int argc, char * argv[])
capture.grab();
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);
sources.push_back(depth);
@@ -235,7 +235,7 @@ int main(int argc, char * argv[])
subtractPlane(depth, mask, chain, focal_length);
cv::imshow("mask", mask);
// Extract template
std::string class_id = cv::format("class%d", num_classes);
cv::Rect bb;
@@ -267,7 +267,7 @@ int main(int argc, char * argv[])
int classes_visited = 0;
std::set<std::string> visited;
for (int i = 0; (i < (int)matches.size()) && (classes_visited < num_classes); ++i)
{
cv::linemod::Match m = matches[i];
@@ -281,7 +281,7 @@ int main(int argc, char * argv[])
printf("Similarity: %5.1f%%; x: %3d; y: %3d; class: %s; template: %3d\n",
m.similarity, m.x, m.y, m.class_id.c_str(), m.template_id);
}
// Draw matching template
const std::vector<cv::linemod::Template>& templates = detector->getTemplates(m.class_id, m.template_id);
drawResponse(templates, num_modalities, display, cv::Point(m.x, m.y), detector->getT(0));
@@ -290,7 +290,7 @@ int main(int argc, char * argv[])
{
/// @todo Online learning possibly broken by new gradient feature extraction,
/// which assumes an accurate object outline.
// Compute masks based on convex hull of matched template
cv::Mat color_mask, depth_mask;
std::vector<CvPoint> chain = maskFromTemplate(templates, num_modalities,
@@ -376,11 +376,11 @@ int main(int argc, char * argv[])
return 0;
}
void reprojectPoints(const std::vector<cv::Point3d>& proj, std::vector<cv::Point3d>& real, double f)
static void reprojectPoints(const std::vector<cv::Point3d>& proj, std::vector<cv::Point3d>& real, double f)
{
real.resize(proj.size());
double f_inv = 1.0 / f;
for (int i = 0; i < (int)proj.size(); ++i)
{
double Z = proj[i].z;
@@ -390,7 +390,7 @@ void reprojectPoints(const std::vector<cv::Point3d>& proj, std::vector<cv::Point
}
}
void filterPlane(IplImage * ap_depth, std::vector<IplImage *> & a_masks, std::vector<CvPoint> & a_chain, double f)
static void filterPlane(IplImage * ap_depth, std::vector<IplImage *> & a_masks, std::vector<CvPoint> & a_chain, double f)
{
const int l_num_cost_pts = 200;
@@ -576,7 +576,7 @@ void subtractPlane(const cv::Mat& depth, cv::Mat& mask, std::vector<CvPoint>& ch
filterPlane(&depth_ipl, tmp, chain, f);
}
std::vector<CvPoint> maskFromTemplate(const std::vector<cv::linemod::Template>& templates,
std::vector<CvPoint> maskFromTemplate(const std::vector<cv::linemod::Template>& templates,
int num_modalities, cv::Point offset, cv::Size size,
cv::Mat& mask, cv::Mat& dst)
{
@@ -629,7 +629,7 @@ cv::Mat displayQuantized(const cv::Mat& quantized)
{
const uchar* quant_r = quantized.ptr(r);
cv::Vec3b* color_r = color.ptr<cv::Vec3b>(r);
for (int c = 0; c < quantized.cols; ++c)
{
cv::Vec3b& bgr = color_r[c];
@@ -649,12 +649,12 @@ cv::Mat displayQuantized(const cv::Mat& quantized)
}
}
}
return color;
}
// Adapted from cv_line_template::convex_hull
void templateConvexHull(const std::vector<cv::linemod::Template>& templates,
void templateConvexHull(const std::vector<cv::linemod::Template>& templates,
int num_modalities, cv::Point offset, cv::Size size,
cv::Mat& dst)
{
@@ -667,7 +667,7 @@ void templateConvexHull(const std::vector<cv::linemod::Template>& templates,
points.push_back(cv::Point(f.x, f.y) + offset);
}
}
std::vector<cv::Point> hull;
cv::convexHull(points, hull);
@@ -677,7 +677,7 @@ void templateConvexHull(const std::vector<cv::linemod::Template>& templates,
cv::fillPoly(dst, &hull_pts, &hull_count, 1, cv::Scalar(255));
}
void drawResponse(const std::vector<cv::linemod::Template>& templates,
void drawResponse(const std::vector<cv::linemod::Template>& templates,
int num_modalities, cv::Mat& dst, cv::Point offset, int T)
{
static const cv::Scalar COLORS[5] = { CV_RGB(0, 0, 255),
@@ -692,7 +692,7 @@ void drawResponse(const std::vector<cv::linemod::Template>& templates,
// box around it and chose the display color based on that response. Here
// the display color just depends on the modality.
cv::Scalar color = COLORS[m];
for (int i = 0; i < (int)templates[m].features.size(); ++i)
{
cv::linemod::Feature f = templates[m].features[i];

View File

@@ -8,12 +8,12 @@
using namespace cv;
using namespace std;
void help()
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 %s\n" << CV_VERSION << "\n"
<< endl;
cout << "\nHot keys: \n"
"\tESC - quit the program\n"
@@ -26,7 +26,7 @@ void help()
Point2f pt;
bool addRemovePt = false;
void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
static void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
{
if( event == CV_EVENT_LBUTTONDOWN )
{
@@ -40,11 +40,11 @@ int main( int argc, char** argv )
VideoCapture cap;
TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
Size subPixWinSize(10,10), winSize(31,31);
const int MAX_COUNT = 500;
bool needToInit = false;
bool nightMode = false;
if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
cap.open(argc == 2 ? argv[1][0] - '0' : 0);
else if( argc == 2 )
@@ -63,7 +63,7 @@ int main( int argc, char** argv )
Mat gray, prevGray, image;
vector<Point2f> points[2];
for(;;)
{
Mat frame;
@@ -72,7 +72,7 @@ int main( int argc, char** argv )
break;
frame.copyTo(image);
cvtColor(image, gray, CV_BGR2GRAY);
cvtColor(image, gray, CV_BGR2GRAY);
if( nightMode )
image = Scalar::all(0);
@@ -142,7 +142,7 @@ int main( int argc, char** argv )
default:
;
}
std::swap(points[1], points[0]);
swap(prevGray, gray);
}

View File

@@ -13,7 +13,7 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "LogPolar Blind Spot Model sample.\nShortcuts:"
"\n\tn for nearest pixel technique"
@@ -22,7 +22,7 @@ void help()
"\n\ta for adjacent receptive fields"
"\n\tq or ESC quit\n";
}
int main(int argc, char** argv)
{
Mat img = imread(argc > 1 ? argv[1] : "lena.jpg",1); // open the image
@@ -32,12 +32,12 @@ int main(int argc, char** argv)
return 0;
}
help();
Size s=img.size();
int w=s.width, h=s.height;
int ro0=3; //radius of the blind spot
int R=120; //number of rings
int R=120; //number of rings
//Creation of the four different objects that implement the four log-polar transformations
//Off-line computation
Point2i center(w/2,h/2);
@@ -60,13 +60,13 @@ int main(int argc, char** argv)
Retinal=nearest.to_cartesian(Cortical);
}else if (wk=='b'){
Cortical=bilin.to_cortical(img);
Retinal=bilin.to_cartesian(Cortical);
Retinal=bilin.to_cartesian(Cortical);
}else if (wk=='o'){
Cortical=overlap.to_cortical(img);
Retinal=overlap.to_cartesian(Cortical);
Retinal=overlap.to_cartesian(Cortical);
}else if (wk=='a'){
Cortical=adj.to_cortical(img);
Retinal=adj.to_cartesian(Cortical);
Retinal=adj.to_cartesian(Cortical);
}
imshow("Cartesian", img);

View File

@@ -6,53 +6,53 @@
using namespace cv;
void help()
static void help()
{
printf("\nThis program demonstrates using features2d detector, descriptor extractor and simple matcher\n"
"Using the SURF desriptor:\n"
"\n"
"Usage:\n matcher_simple <image1> <image2>\n");
printf("\nThis program demonstrates using features2d detector, descriptor extractor and simple matcher\n"
"Using the SURF desriptor:\n"
"\n"
"Usage:\n matcher_simple <image1> <image2>\n");
}
int main(int argc, char** argv)
{
if(argc != 3)
{
help();
return -1;
}
if(argc != 3)
{
help();
return -1;
}
Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
if(img1.empty() || img2.empty())
{
printf("Can't read one of the images\n");
return -1;
}
Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
if(img1.empty() || img2.empty())
{
printf("Can't read one of the images\n");
return -1;
}
// detecting keypoints
SurfFeatureDetector detector(400);
vector<KeyPoint> keypoints1, keypoints2;
detector.detect(img1, keypoints1);
detector.detect(img2, keypoints2);
// detecting keypoints
SurfFeatureDetector detector(400);
vector<KeyPoint> keypoints1, keypoints2;
detector.detect(img1, keypoints1);
detector.detect(img2, keypoints2);
// computing descriptors
SurfDescriptorExtractor extractor;
Mat descriptors1, descriptors2;
extractor.compute(img1, keypoints1, descriptors1);
extractor.compute(img2, keypoints2, descriptors2);
// computing descriptors
SurfDescriptorExtractor extractor;
Mat descriptors1, descriptors2;
extractor.compute(img1, keypoints1, descriptors1);
extractor.compute(img2, keypoints2, descriptors2);
// matching descriptors
BFMatcher matcher(NORM_L2);
// matching descriptors
BFMatcher matcher(NORM_L2);
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
// drawing the results
namedWindow("matches", 1);
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);
imshow("matches", img_matches);
waitKey(0);
// drawing the results
namedWindow("matches", 1);
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);
imshow("matches", img_matches);
waitKey(0);
return 0;
return 0;
}

View File

@@ -15,7 +15,7 @@ const string defaultQueryImageName = "../../opencv/samples/cpp/matching_to_many_
const string defaultFileWithTrainImages = "../../opencv/samples/cpp/matching_to_many_images/train/trainImages.txt";
const string defaultDirToSaveResImages = "../../opencv/samples/cpp/matching_to_many_images/results";
void printPrompt( const string& applName )
static void printPrompt( const string& applName )
{
cout << "/*\n"
<< " * This is a sample on matching descriptors detected on one image to descriptors detected in image set.\n"
@@ -36,7 +36,7 @@ void printPrompt( const string& applName )
<< defaultQueryImageName << " " << defaultFileWithTrainImages << " " << defaultDirToSaveResImages << endl;
}
void maskMatchesByTrainImgIdx( const vector<DMatch>& matches, int trainImgIdx, vector<char>& mask )
static void maskMatchesByTrainImgIdx( const vector<DMatch>& matches, int trainImgIdx, vector<char>& mask )
{
mask.resize( matches.size() );
fill( mask.begin(), mask.end(), 0 );
@@ -47,7 +47,7 @@ void maskMatchesByTrainImgIdx( const vector<DMatch>& matches, int trainImgIdx, v
}
}
void readTrainFilenames( const string& filename, string& dirName, vector<string>& trainFilenames )
static void readTrainFilenames( const string& filename, string& dirName, vector<string>& trainFilenames )
{
trainFilenames.clear();
@@ -73,7 +73,7 @@ void readTrainFilenames( const string& filename, string& dirName, vector<string>
file.close();
}
bool createDetectorDescriptorMatcher( const string& detectorType, const string& descriptorType, const string& matcherType,
static bool createDetectorDescriptorMatcher( const string& detectorType, const string& descriptorType, const string& matcherType,
Ptr<FeatureDetector>& featureDetector,
Ptr<DescriptorExtractor>& descriptorExtractor,
Ptr<DescriptorMatcher>& descriptorMatcher )
@@ -91,7 +91,7 @@ bool createDetectorDescriptorMatcher( const string& detectorType, const string&
return isCreated;
}
bool readImages( const string& queryImageName, const string& trainFilename,
static bool readImages( const string& queryImageName, const string& trainFilename,
Mat& queryImage, vector <Mat>& trainImages, vector<string>& trainImageNames )
{
cout << "< Reading the images..." << endl;
@@ -131,7 +131,7 @@ bool readImages( const string& queryImageName, const string& trainFilename,
return true;
}
void detectKeypoints( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
static void detectKeypoints( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
const vector<Mat>& trainImages, vector<vector<KeyPoint> >& trainKeypoints,
Ptr<FeatureDetector>& featureDetector )
{
@@ -141,14 +141,14 @@ void detectKeypoints( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
cout << ">" << endl;
}
void computeDescriptors( const Mat& queryImage, vector<KeyPoint>& queryKeypoints, Mat& queryDescriptors,
static void computeDescriptors( const Mat& queryImage, vector<KeyPoint>& queryKeypoints, Mat& queryDescriptors,
const vector<Mat>& trainImages, vector<vector<KeyPoint> >& trainKeypoints, vector<Mat>& trainDescriptors,
Ptr<DescriptorExtractor>& descriptorExtractor )
{
cout << "< Computing descriptors for keypoints..." << endl;
descriptorExtractor->compute( queryImage, queryKeypoints, queryDescriptors );
descriptorExtractor->compute( trainImages, trainKeypoints, trainDescriptors );
int totalTrainDesc = 0;
for( vector<Mat>::const_iterator tdIter = trainDescriptors.begin(); tdIter != trainDescriptors.end(); tdIter++ )
totalTrainDesc += tdIter->rows;
@@ -157,7 +157,7 @@ void computeDescriptors( const Mat& queryImage, vector<KeyPoint>& queryKeypoints
cout << ">" << endl;
}
void matchDescriptors( const Mat& queryDescriptors, const vector<Mat>& trainDescriptors,
static void matchDescriptors( const Mat& queryDescriptors, const vector<Mat>& trainDescriptors,
vector<DMatch>& matches, Ptr<DescriptorMatcher>& descriptorMatcher )
{
cout << "< Set train descriptors collection in the matcher and match query descriptors to them..." << endl;
@@ -175,13 +175,13 @@ void matchDescriptors( const Mat& queryDescriptors, const vector<Mat>& trainDesc
double matchTime = tm.getTimeMilli();
CV_Assert( queryDescriptors.rows == (int)matches.size() || matches.empty() );
cout << "Number of matches: " << matches.size() << endl;
cout << "Build time: " << buildTime << " ms; Match time: " << matchTime << " ms" << endl;
cout << ">" << endl;
}
void saveResultImages( const Mat& queryImage, const vector<KeyPoint>& queryKeypoints,
static void saveResultImages( const Mat& queryImage, const vector<KeyPoint>& queryKeypoints,
const vector<Mat>& trainImages, const vector<vector<KeyPoint> >& trainKeypoints,
const vector<DMatch>& matches, const vector<string>& trainImagesNames, const string& resultDir )
{

View File

@@ -7,9 +7,9 @@
using namespace cv;
using namespace std;
void help(char** argv)
static void help(char** argv)
{
cout << "\nDemonstrate mean-shift based color segmentation in spatial pyramid.\n"
cout << "\nDemonstrate mean-shift based color segmentation in spatial pyramid.\n"
<< "Call:\n " << argv[0] << " image\n"
<< "This program allows you to set the spatial and color radius\n"
<< "of the mean shift window as well as the number of pyramid reduction levels explored\n"
@@ -17,7 +17,7 @@ void help(char** argv)
}
//This colors the segmentations
void floodFillPostprocess( Mat& img, const Scalar& colorDiff=Scalar::all(1) )
static void floodFillPostprocess( Mat& img, const Scalar& colorDiff=Scalar::all(1) )
{
CV_Assert( !img.empty() );
RNG rng = theRNG();
@@ -39,7 +39,7 @@ string winName = "meanshift";
int spatialRad, colorRad, maxPyrLevel;
Mat img, res;
void meanShiftSegmentation( int, void* )
static void meanShiftSegmentation( int, void* )
{
cout << "spatialRad=" << spatialRad << "; "
<< "colorRad=" << colorRad << "; "
@@ -53,7 +53,7 @@ int main(int argc, char** argv)
{
if( argc !=2 )
{
help(argv);
help(argv);
return -1;
}

View File

@@ -6,9 +6,9 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "This program demonstrates finding the minimum enclosing box or circle of a set\n"
cout << "This program demonstrates finding the minimum enclosing box or circle of a set\n"
"of points using functions: minAreaRect() minEnclosingCircle().\n"
"Random points are generated and then enclosed.\n"
"Call:\n"
@@ -21,7 +21,7 @@ int main( int /*argc*/, char** /*argv*/ )
help();
Mat img(500, 500, CV_8UC3);
RNG& rng = theRNG();
RNG& rng = theRNG();
for(;;)
{
@@ -32,25 +32,25 @@ int main( int /*argc*/, char** /*argv*/ )
Point pt;
pt.x = rng.uniform(img.cols/4, img.cols*3/4);
pt.y = rng.uniform(img.rows/4, img.rows*3/4);
points.push_back(pt);
}
RotatedRect box = minAreaRect(Mat(points));
Point2f center, vtx[4];
float radius = 0;
minEnclosingCircle(Mat(points), center, radius);
box.points(vtx);
img = Scalar::all(0);
for( i = 0; i < count; i++ )
circle( img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA );
for( i = 0; i < 4; i++ )
line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, CV_AA);
circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, CV_AA);
circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, CV_AA);
imshow( "rect & circle", img );

View File

@@ -7,12 +7,12 @@
using namespace cv;
void help()
static void help()
{
printf("\nShow off image morphology: erosion, dialation, open and close\n"
"Call:\n morphology2 [image]\n"
"This program also shows use of rect, elipse and cross kernels\n\n");
"Call:\n morphology2 [image]\n"
"This program also shows use of rect, elipse and cross kernels\n\n");
printf( "Hot keys: \n"
"\tESC - quit the program\n"
"\tr - use rectangle structuring element\n"
@@ -31,7 +31,7 @@ int open_close_pos = 0;
int erode_dilate_pos = 0;
// callback function for open/close trackbar
void OpenClose(int, void*)
static void OpenClose(int, void*)
{
int n = open_close_pos - max_iters;
int an = n > 0 ? n : -n;
@@ -44,7 +44,7 @@ void OpenClose(int, void*)
}
// callback function for erode/dilate trackbar
void ErodeDilate(int, void*)
static void ErodeDilate(int, void*)
{
int n = erode_dilate_pos - max_iters;
int an = n > 0 ? n : -n;

View File

@@ -10,7 +10,7 @@
using namespace std;
using namespace cv;
void help()
static void help()
{
cout << "\nThis program demonstrates the multi cascade recognizer. It is a generalization of facedetect sample.\n\n"
"Usage: ./multicascadeclassifier \n"

View File

@@ -6,7 +6,7 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nThis program demonstrates usage of depth sensors (Kinect, XtionPRO,...).\n"
"The user gets some of the supported output images.\n"
@@ -23,7 +23,7 @@ void help()
<< endl;
}
void colorizeDisparity( const Mat& gray, Mat& rgb, double maxDisp=-1.f, float S=1.f, float V=1.f )
static void colorizeDisparity( const Mat& gray, Mat& rgb, double maxDisp=-1.f, float S=1.f, float V=1.f )
{
CV_Assert( !gray.empty() );
CV_Assert( gray.type() == CV_8UC1 );
@@ -53,30 +53,30 @@ void colorizeDisparity( const Mat& gray, Mat& rgb, double maxDisp=-1.f, float S=
float t = V * (1 - (1 - f) * S);
Point3f res;
if( hi == 0 ) //R = V, G = t, B = p
if( hi == 0 ) //R = V, G = t, B = p
res = Point3f( p, t, V );
if( hi == 1 ) // R = q, G = V, B = p
if( hi == 1 ) // R = q, G = V, B = p
res = Point3f( p, V, q );
if( hi == 2 ) // R = p, G = V, B = t
if( hi == 2 ) // R = p, G = V, B = t
res = Point3f( t, V, p );
if( hi == 3 ) // R = p, G = q, B = V
if( hi == 3 ) // R = p, G = q, B = V
res = Point3f( V, q, p );
if( hi == 4 ) // R = t, G = p, B = V
if( hi == 4 ) // R = t, G = p, B = V
res = Point3f( V, p, t );
if( hi == 5 ) // R = V, G = p, B = q
if( hi == 5 ) // R = V, G = p, B = q
res = Point3f( q, p, V );
uchar b = (uchar)(std::max(0.f, std::min (res.x, 1.f)) * 255.f);
uchar g = (uchar)(std::max(0.f, std::min (res.y, 1.f)) * 255.f);
uchar r = (uchar)(std::max(0.f, std::min (res.z, 1.f)) * 255.f);
rgb.at<Point3_<uchar> >(y,x) = Point3_<uchar>(b, g, r);
rgb.at<Point3_<uchar> >(y,x) = Point3_<uchar>(b, g, r);
}
}
}
float getMaxDisparity( VideoCapture& capture )
static float getMaxDisparity( VideoCapture& capture )
{
const int minDistance = 400; // mm
float b = (float)capture.get( CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE ); // mm
@@ -84,7 +84,7 @@ float getMaxDisparity( VideoCapture& capture )
return b * F / minDistance;
}
void printCommandLineParams()
static void printCommandLineParams()
{
cout << "-cd Colorized disparity? (0 or 1; 1 by default) Ignored if disparity map is not selected to show." << endl;
cout << "-fmd Fixed max disparity? (0 or 1; 0 by default) Ignored if disparity map is not colorized (-cd 0)." << endl;
@@ -96,7 +96,7 @@ void printCommandLineParams()
cout << "-r Filename of .oni video file. The data will grabbed from it." << endl ;
}
void parseCommandLine( int argc, char* argv[], bool& isColorizeDisp, bool& isFixedMaxDisp, int& imageMode, bool retrievedImageFlags[],
static void parseCommandLine( int argc, char* argv[], bool& isColorizeDisp, bool& isFixedMaxDisp, int& imageMode, bool retrievedImageFlags[],
string& filename, bool& isFileReading )
{
// set defaut values

View File

@@ -9,14 +9,14 @@
using namespace cv;
using namespace std;
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");
}
// 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");
// }
int main(int argc, char** argv)
{
@@ -33,16 +33,16 @@ int main(int argc, char** argv)
if( img.data )
{
strcpy(_filename, argv[1]);
strcpy(_filename, argv[1]);
}
else
{
f = fopen(argv[1], "rt");
if(!f)
{
fprintf( stderr, "ERROR: the specified file could not be loaded\n");
return -1;
}
fprintf( stderr, "ERROR: the specified file could not be loaded\n");
return -1;
}
}
HOGDescriptor hog;
@@ -51,58 +51,58 @@ int main(int argc, char** argv)
for(;;)
{
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;
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++ )
{
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);
}
for( i = 0; i < found_filtered.size(); i++ )
{
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);
}
imshow("people detector", img);
int c = waitKey(0) & 255;
if( c == 'q' || c == 'Q' || !f)
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;
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++ )
{
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);
}
for( i = 0; i < found_filtered.size(); i++ )
{
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);
}
imshow("people detector", img);
int c = waitKey(0) & 255;
if( c == 'q' || c == 'Q' || !f)
break;
}
if(f)

View File

@@ -43,7 +43,7 @@ private:
bool stop = false;
void mouseCallback(int event, int x, int y, int flags, void* userdata)
static void mouseCallback(int event, int x, int y, int flags, void* userdata)
{
if (stop)
return;
@@ -52,7 +52,7 @@ void mouseCallback(int event, int x, int y, int flags, void* userdata)
renderer->onMouseEvent(event, x, y, flags);
}
void openGlDrawCallback(void* userdata)
static void openGlDrawCallback(void* userdata)
{
if (stop)
return;
@@ -280,7 +280,7 @@ void PointCloudRenderer::onMouseEvent(int event, int x, int y, int /*flags*/)
mouse_dy_ = clamp(mouse_dy_, -mouseClamp, mouseClamp);
}
Point3d rotate(Point3d v, double yaw, double pitch)
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);

View File

@@ -29,7 +29,7 @@ vector<Scalar> classColors;
#define _ANN_ 0 // artificial neural networks
#define _EM_ 0 // expectation-maximization
void on_mouse( int event, int x, int y, int /*flags*/, void* )
static void on_mouse( int event, int x, int y, int /*flags*/, void* )
{
if( img.empty() )
return;
@@ -87,7 +87,7 @@ void on_mouse( int event, int x, int y, int /*flags*/, void* )
}
}
void prepare_train_data( Mat& samples, Mat& classes )
static void prepare_train_data( Mat& samples, Mat& classes )
{
Mat( trainedPoints ).copyTo( samples );
Mat( trainedPointsMarkers ).copyTo( classes );
@@ -98,7 +98,7 @@ void prepare_train_data( Mat& samples, Mat& classes )
}
#if _NBC_
void find_decision_boundary_NBC()
static void find_decision_boundary_NBC()
{
img.copyTo( imgDst );
@@ -125,7 +125,7 @@ void find_decision_boundary_NBC()
#if _KNN_
void find_decision_boundary_KNN( int K )
static void find_decision_boundary_KNN( int K )
{
img.copyTo( imgDst );
@@ -151,7 +151,7 @@ void find_decision_boundary_KNN( int K )
#endif
#if _SVM_
void find_decision_boundary_SVM( CvSVMParams params )
static void find_decision_boundary_SVM( CvSVMParams params )
{
img.copyTo( imgDst );
@@ -185,7 +185,7 @@ void find_decision_boundary_SVM( CvSVMParams params )
#endif
#if _DT_
void find_decision_boundary_DT()
static void find_decision_boundary_DT()
{
img.copyTo( imgDst );

View File

@@ -11,147 +11,147 @@
#include "opencv2/opencv.hpp"
void help(std::string errorMessage)
static void help(std::string errorMessage)
{
std::cout<<"Program init error : "<<errorMessage<<std::endl;
std::cout<<"\nProgram call procedure : retinaDemo [processing mode] [Optional : media target] [Optional LAST parameter: \"log\" to activate retina log sampling]"<<std::endl;
std::cout<<"\t[processing mode] :"<<std::endl;
std::cout<<"\t -image : for still image processing"<<std::endl;
std::cout<<"\t -video : for video stream processing"<<std::endl;
std::cout<<"\t[Optional : media target] :"<<std::endl;
std::cout<<"\t if processing an image or video file, then, specify the path and filename of the target to process"<<std::endl;
std::cout<<"\t leave empty if processing video stream coming from a connected video device"<<std::endl;
std::cout<<"\t[Optional : activate retina log sampling] : an optional last parameter can be specified for retina spatial log sampling"<<std::endl;
std::cout<<"\t set \"log\" without quotes to activate this sampling, output frame size will be divided by 4"<<std::endl;
std::cout<<"\nExamples:"<<std::endl;
std::cout<<"\t-Image processing : ./retinaDemo -image lena.jpg"<<std::endl;
std::cout<<"\t-Image processing with log sampling : ./retinaDemo -image lena.jpg log"<<std::endl;
std::cout<<"\t-Video processing : ./retinaDemo -video myMovie.mp4"<<std::endl;
std::cout<<"\t-Live video processing : ./retinaDemo -video"<<std::endl;
std::cout<<"\nPlease start again with new parameters"<<std::endl;
std::cout<<"Program init error : "<<errorMessage<<std::endl;
std::cout<<"\nProgram call procedure : retinaDemo [processing mode] [Optional : media target] [Optional LAST parameter: \"log\" to activate retina log sampling]"<<std::endl;
std::cout<<"\t[processing mode] :"<<std::endl;
std::cout<<"\t -image : for still image processing"<<std::endl;
std::cout<<"\t -video : for video stream processing"<<std::endl;
std::cout<<"\t[Optional : media target] :"<<std::endl;
std::cout<<"\t if processing an image or video file, then, specify the path and filename of the target to process"<<std::endl;
std::cout<<"\t leave empty if processing video stream coming from a connected video device"<<std::endl;
std::cout<<"\t[Optional : activate retina log sampling] : an optional last parameter can be specified for retina spatial log sampling"<<std::endl;
std::cout<<"\t set \"log\" without quotes to activate this sampling, output frame size will be divided by 4"<<std::endl;
std::cout<<"\nExamples:"<<std::endl;
std::cout<<"\t-Image processing : ./retinaDemo -image lena.jpg"<<std::endl;
std::cout<<"\t-Image processing with log sampling : ./retinaDemo -image lena.jpg log"<<std::endl;
std::cout<<"\t-Video processing : ./retinaDemo -video myMovie.mp4"<<std::endl;
std::cout<<"\t-Live video processing : ./retinaDemo -video"<<std::endl;
std::cout<<"\nPlease start again with new parameters"<<std::endl;
}
int main(int argc, char* argv[]) {
// welcome message
std::cout<<"****************************************************"<<std::endl;
std::cout<<"* Retina demonstration : demonstrates the use of is a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl;
std::cout<<"* As a summary, these are the retina model properties:"<<std::endl;
std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl;
std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl;
std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl;
std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl;
std::cout<<"* for more information, reer to the following papers :"<<std::endl;
std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl;
std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl;
std::cout<<"* => reports comments/remarks at benoit.alexandre.vision@gmail.com"<<std::endl;
std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl;
std::cout<<"****************************************************"<<std::endl;
std::cout<<" NOTE : this program generates the default retina parameters file 'RetinaDefaultParameters.xml'"<<std::endl;
std::cout<<" => you can use this to fine tune parameters and load them if you save to file 'RetinaSpecificParameters.xml'"<<std::endl;
// welcome message
std::cout<<"****************************************************"<<std::endl;
std::cout<<"* Retina demonstration : demonstrates the use of is a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl;
std::cout<<"* As a summary, these are the retina model properties:"<<std::endl;
std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl;
std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl;
std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl;
std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl;
std::cout<<"* for more information, reer to the following papers :"<<std::endl;
std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl;
std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl;
std::cout<<"* => reports comments/remarks at benoit.alexandre.vision@gmail.com"<<std::endl;
std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl;
std::cout<<"****************************************************"<<std::endl;
std::cout<<" NOTE : this program generates the default retina parameters file 'RetinaDefaultParameters.xml'"<<std::endl;
std::cout<<" => you can use this to fine tune parameters and load them if you save to file 'RetinaSpecificParameters.xml'"<<std::endl;
// basic input arguments checking
if (argc<2)
{
help("bad number of parameter");
return -1;
}
// basic input arguments checking
if (argc<2)
{
help("bad number of parameter");
return -1;
}
bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
std::string inputMediaType=argv[1];
std::string inputMediaType=argv[1];
// declare the retina input buffer... that will be fed differently in regard of the input media
cv::Mat inputFrame;
cv::VideoCapture videoCapture; // in case a video media is used, its manager is declared here
// declare the retina input buffer... that will be fed differently in regard of the input media
cv::Mat inputFrame;
cv::VideoCapture videoCapture; // in case a video media is used, its manager is declared here
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
if (!strcmp(inputMediaType.c_str(), "-image") && argc >= 3)
{
std::cout<<"RetinaDemo: processing image "<<argv[2]<<std::endl;
// image processing case
inputFrame = cv::imread(std::string(argv[2]), 1); // load image in RGB mode
}else
if (!strcmp(inputMediaType.c_str(), "-video"))
{
if (argc == 2 || (argc == 3 && useLogSampling)) // attempt to grab images from a video capture device
{
videoCapture.open(0);
}else// attempt to grab images from a video filestream
{
std::cout<<"RetinaDemo: processing video stream "<<argv[2]<<std::endl;
videoCapture.open(argv[2]);
}
//////////////////////////////////////////////////////////////////////////////
// checking input media type (still image, video file, live video acquisition)
if (!strcmp(inputMediaType.c_str(), "-image") && argc >= 3)
{
std::cout<<"RetinaDemo: processing image "<<argv[2]<<std::endl;
// image processing case
inputFrame = cv::imread(std::string(argv[2]), 1); // load image in RGB mode
}else
if (!strcmp(inputMediaType.c_str(), "-video"))
{
if (argc == 2 || (argc == 3 && useLogSampling)) // attempt to grab images from a video capture device
{
videoCapture.open(0);
}else// attempt to grab images from a video filestream
{
std::cout<<"RetinaDemo: processing video stream "<<argv[2]<<std::endl;
videoCapture.open(argv[2]);
}
// grab a first frame to check if everything is ok
videoCapture>>inputFrame;
}else
{
// bad command parameter
help("bad command parameter");
return -1;
}
// grab a first frame to check if everything is ok
videoCapture>>inputFrame;
}else
{
// bad command parameter
help("bad command parameter");
return -1;
}
if (inputFrame.empty())
{
help("Input media could not be loaded, aborting");
return -1;
}
if (inputFrame.empty())
{
help("Input media could not be loaded, aborting");
return -1;
}
//////////////////////////////////////////////////////////////////////////////
// Program start in a try/catch safety context (Retina may throw errors)
try
{
// create a retina instance with default parameters setup, uncomment the initialisation you wanna test
cv::Ptr<cv::Retina> myRetina;
//////////////////////////////////////////////////////////////////////////////
// Program start in a try/catch safety context (Retina may throw errors)
try
{
// create a retina instance with default parameters setup, uncomment the initialisation you wanna test
cv::Ptr<cv::Retina> myRetina;
// if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
if (useLogSampling)
// if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
if (useLogSampling)
{
myRetina = new cv::Retina(inputFrame.size(), true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0);
}
else// -> else allocate "classical" retina :
myRetina = new cv::Retina(inputFrame.size());
// save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
myRetina->write("RetinaDefaultParameters.xml");
else// -> else allocate "classical" retina :
myRetina = new cv::Retina(inputFrame.size());
// load parameters if file exists
myRetina->setup("RetinaSpecificParameters.xml");
myRetina->clearBuffers();
// save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
myRetina->write("RetinaDefaultParameters.xml");
// declare retina output buffers
cv::Mat retinaOutput_parvo;
cv::Mat retinaOutput_magno;
// load parameters if file exists
myRetina->setup("RetinaSpecificParameters.xml");
myRetina->clearBuffers();
// processing loop with stop condition
bool continueProcessing=true; // FIXME : not yet managed during process...
while(continueProcessing)
{
// if using video stream, then, grabbing a new frame, else, input remains the same
if (videoCapture.isOpened())
videoCapture>>inputFrame;
// declare retina output buffers
cv::Mat retinaOutput_parvo;
cv::Mat retinaOutput_magno;
// run retina filter
myRetina->run(inputFrame);
// Retrieve and display retina output
myRetina->getParvo(retinaOutput_parvo);
myRetina->getMagno(retinaOutput_magno);
cv::imshow("retina input", inputFrame);
cv::imshow("Retina Parvo", retinaOutput_parvo);
cv::imshow("Retina Magno", retinaOutput_magno);
cv::waitKey(10);
}
}catch(cv::Exception e)
{
std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
}
// processing loop with stop condition
bool continueProcessing=true; // FIXME : not yet managed during process...
while(continueProcessing)
{
// if using video stream, then, grabbing a new frame, else, input remains the same
if (videoCapture.isOpened())
videoCapture>>inputFrame;
// Program end message
std::cout<<"Retina demo end"<<std::endl;
// run retina filter
myRetina->run(inputFrame);
// Retrieve and display retina output
myRetina->getParvo(retinaOutput_parvo);
myRetina->getMagno(retinaOutput_magno);
cv::imshow("retina input", inputFrame);
cv::imshow("Retina Parvo", retinaOutput_parvo);
cv::imshow("Retina Magno", retinaOutput_magno);
cv::waitKey(10);
}
}catch(cv::Exception e)
{
std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
}
return 0;
// Program end message
std::cout<<"Retina demo end"<<std::endl;
return 0;
}

View File

@@ -6,41 +6,41 @@
using namespace cv;
void help()
static void help()
{
printf("\n"
"This program demonstrated a simple method of connected components clean up of background subtraction\n"
"When the program starts, it begins learning the background.\n"
"You can toggle background learning on and off by hitting the space bar.\n"
"Call\n"
"./segment_objects [video file, else it reads camera 0]\n\n");
printf("\n"
"This program demonstrated a simple method of connected components clean up of background subtraction\n"
"When the program starts, it begins learning the background.\n"
"You can toggle background learning on and off by hitting the space bar.\n"
"Call\n"
"./segment_objects [video file, else it reads camera 0]\n\n");
}
void refineSegments(const Mat& img, Mat& mask, Mat& dst)
static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
{
int niters = 3;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat temp;
dilate(mask, temp, Mat(), Point(-1,-1), niters);
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 );
dst = Mat::zeros(img.size(), CV_8UC3);
dst = Mat::zeros(img.size(), CV_8UC3);
if( contours.size() == 0 )
return;
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0, largestComp = 0;
double maxArea = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
const vector<Point>& c = contours[idx];
@@ -60,35 +60,35 @@ int main(int argc, char** argv)
{
VideoCapture cap;
bool update_bg_model = true;
help();
if( argc < 2 )
cap.open(0);
else
cap.open(std::string(argv[1]));
if( !cap.isOpened() )
{
printf("\nCan not open camera or video file\n");
return -1;
}
Mat tmp_frame, bgmask, out_frame;
cap >> tmp_frame;
if(!tmp_frame.data)
{
printf("can not read data from the video source\n");
return -1;
}
namedWindow("video", 1);
namedWindow("segmented", 1);
BackgroundSubtractorMOG bgsubtractor;
bgsubtractor.set("noiseSigma", 10);
for(;;)
{
cap >> tmp_frame;
@@ -109,6 +109,6 @@ int main(int argc, char** argv)
printf("Learn background is in state = %d\n",update_bg_model);
}
}
return 0;
}

View File

@@ -29,11 +29,11 @@ const char* helphelp =
"select3dobj -w <board_width> -h <board_height> [-s <square_size>]\n"
" -i <camera_intrinsics_filename> -o <output_prefix> [video_filename/cameraId]\n"
"\n"
" -w <board_width> Number of chessboard corners wide\n"
" -h <board_height> Number of chessboard corners width\n"
" [-s <square_size>] Optional measure of chessboard squares in meters\n"
" -w <board_width> Number of chessboard corners wide\n"
" -h <board_height> Number of chessboard corners width\n"
" [-s <square_size>] Optional measure of chessboard squares in meters\n"
" -i <camera_intrinsics_filename> Camera matrix .yml file from calibration.cpp\n"
" -o <output_prefix> Prefix the output segmentation images with this\n"
" -o <output_prefix> Prefix the output segmentation images with this\n"
" [video_filename/cameraId] If present, read from that video file or that ID\n"
"\n"
"Using a camera's intrinsics (from calibrating a camera -- see calibration.cpp) and an\n"
@@ -57,10 +57,10 @@ const char* helphelp =
" q - Exit the program\n"
"\n\n";
void help()
{
puts(helphelp);
}
// static void help()
// {
// puts(helphelp);
// }
struct MouseEvent
@@ -88,19 +88,19 @@ static bool readCameraMatrix(const string& filename,
fs["image_height"] >> calibratedImageSize.height;
fs["distortion_coefficients"] >> distCoeffs;
fs["camera_matrix"] >> cameraMatrix;
if( distCoeffs.type() != CV_64F )
distCoeffs = Mat_<double>(distCoeffs);
if( cameraMatrix.type() != CV_64F )
cameraMatrix = Mat_<double>(cameraMatrix);
return true;
}
static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point3f>& corners)
{
corners.resize(0);
for( int i = 0; i < boardSize.height; i++ )
for( int j = 0; j < boardSize.width; j++ )
corners.push_back(Point3f(float(j*squareSize),
@@ -119,7 +119,7 @@ static Point3f image2plane(Point2f imgpt, const Mat& R, const Mat& tvec,
}
static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFrame,
static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFrame,
const Mat& cameraMatrix, const Mat& rvec, const Mat& tvec,
const vector<Point3f>& box, int nobjpt, bool runExtraSegmentation)
{
@@ -128,7 +128,7 @@ static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFram
return Rect();
vector<Point3f> objpt;
vector<Point2f> imgpt;
objpt.push_back(box[0]);
if( nobjpt > 1 )
objpt.push_back(box[1]);
@@ -140,9 +140,9 @@ static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFram
if( nobjpt > 3 )
for( int i = 0; i < 4; i++ )
objpt.push_back(Point3f(objpt[i].x, objpt[i].y, box[3].z));
projectPoints(Mat(objpt), rvec, tvec, cameraMatrix, Mat(), imgpt);
if( shownFrame.data )
{
if( nobjpt == 1 )
@@ -158,7 +158,7 @@ static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFram
{
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);
}
}
else
for( int i = 0; i < 8; i++ )
{
@@ -167,7 +167,7 @@ static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFram
line(shownFrame, imgpt[i], imgpt[i%4], Scalar(0,255,0), 3, CV_AA);
}
}
if( nobjpt <= 2 )
return Rect();
vector<Point> hull;
@@ -175,7 +175,7 @@ static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFram
Mat selectedObjMask = Mat::zeros(frame.size(), CV_8U);
fillConvexPoly(selectedObjMask, &hull[0], (int)hull.size(), Scalar::all(255), 8, 0);
Rect roi = boundingRect(Mat(hull)) & Rect(Point(), frame.size());
if( runExtraSegmentation )
{
selectedObjMask = Scalar::all(GC_BGD);
@@ -185,7 +185,7 @@ static Rect extract3DBox(const Mat& frame, Mat& shownFrame, Mat& selectedObjFram
3, GC_INIT_WITH_RECT + GC_INIT_WITH_MASK);
bitwise_and(selectedObjMask, Scalar::all(1), selectedObjMask);
}
frame.copyTo(selectedObjFrame, selectedObjMask);
return roi;
}
@@ -197,7 +197,7 @@ static int select3DBox(const string& windowname, const string& selWinName, const
{
const float eps = 1e-3f;
MouseEvent mouse;
setMouseCallback(windowname, onMouse, &mouse);
vector<Point3f> tempobj(8);
vector<Point2f> imgpt(4), tempimg(8);
@@ -206,19 +206,19 @@ static int select3DBox(const string& windowname, const string& selWinName, const
Mat R, selectedObjMask, selectedObjFrame, shownFrame;
Rodrigues(rvec, R);
box.resize(4);
for(;;)
{
float Z = 0.f;
bool dragging = (mouse.buttonState & CV_EVENT_FLAG_LBUTTON) != 0;
int npt = nobjpt;
if( (mouse.event == CV_EVENT_LBUTTONDOWN ||
mouse.event == CV_EVENT_LBUTTONUP ||
dragging) && nobjpt < 4 )
{
Point2f m = mouse.pt;
if( nobjpt < 2 )
imgpt[npt] = m;
else
@@ -232,7 +232,7 @@ static int select3DBox(const string& windowname, const string& selWinName, const
if( norm(m - imgpt[i]) < norm(m - imgpt[nearestIdx]) )
nearestIdx = i;
}
if( npt == 2 )
{
float dx = box[1].x - box[0].x, dy = box[1].y - box[0].y;
@@ -242,9 +242,9 @@ static int select3DBox(const string& windowname, const string& selWinName, const
}
else
tempobj[0] = Point3f(box[nearestIdx].x, box[nearestIdx].y, 1.f);
projectPoints(Mat(tempobj), rvec, tvec, cameraMatrix, Mat(), tempimg);
Point2f a = imgpt[nearestIdx], b = tempimg[0], d1 = b - a, d2 = m - a;
float n1 = (float)norm(d1), n2 = (float)norm(d2);
if( n1*n2 < eps )
@@ -256,7 +256,7 @@ 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) ||
(npt > 0 && norm(box[npt] - box[npt-1]) > eps &&
mouse.event == CV_EVENT_LBUTTONUP) )
@@ -268,19 +268,19 @@ static int select3DBox(const string& windowname, const string& selWinName, const
box[nobjpt] = box[nobjpt-1];
}
}
// reset the event
mouse.event = -1;
//mouse.buttonState = 0;
npt++;
}
frame.copyTo(shownFrame);
extract3DBox(frame, shownFrame, selectedObjFrame,
cameraMatrix, rvec, tvec, box, npt, false);
imshow(windowname, shownFrame);
imshow(selWinName, selectedObjFrame);
int c = waitKey(30);
if( (c & 255) == 27 )
{
@@ -305,17 +305,17 @@ static bool readModelViews( const string& filename, vector<Point3f>& box,
roiList.resize(0);
poseList.resize(0);
box.resize(0);
FileStorage fs(filename, FileStorage::READ);
if( !fs.isOpened() )
return false;
fs["box"] >> box;
FileNode all = fs["views"];
if( all.type() != FileNode::SEQ )
return false;
FileNodeIterator it = all.begin(), it_end = all.end();
for(; it != it_end; ++it)
{
FileNode n = *it;
@@ -326,7 +326,7 @@ static bool readModelViews( const string& filename, vector<Point3f>& box,
poseList.push_back(Vec6f((float)np[0], (float)np[1], (float)np[2],
(float)np[3], (float)np[4], (float)np[5]));
}
return true;
}
@@ -339,25 +339,25 @@ static bool writeModelViews(const string& filename, const vector<Point3f>& box,
FileStorage fs(filename, FileStorage::WRITE);
if( !fs.isOpened() )
return false;
fs << "box" << "[:";
fs << box << "]" << "views" << "[";
size_t i, nviews = imagelist.size();
CV_Assert( nviews == roiList.size() && nviews == poseList.size() );
for( i = 0; i < nviews; i++ )
{
Rect r = roiList[i];
Vec6f p = poseList[i];
fs << "{" << "image" << imagelist[i] <<
"roi" << "[:" << r.x << r.y << r.width << r.height << "]" <<
"pose" << "[:" << p[0] << p[1] << p[2] << p[3] << p[4] << p[5] << "]" << "}";
}
fs << "]";
return true;
}
@@ -389,82 +389,82 @@ int main(int argc, char** argv)
"\tSPACE - Skip the frame; move to the next frame (not in video mode)\n"
"\tENTER - Confirm the selection. Grab next object in video mode.\n"
"\tq - Exit the program\n";
if(argc < 5)
{
puts(helphelp);
puts(helphelp);
puts(help);
return 0;
}
const char* intrinsicsFilename = 0;
const char* outprefix = 0;
const char* inputName = 0;
int cameraId = 0;
Size boardSize;
double squareSize = 1;
const char* inputName = 0;
int cameraId = 0;
Size boardSize;
double squareSize = 1;
vector<string> imageList;
for( int i = 1; i < argc; i++ )
{
if( strcmp(argv[i], "-i") == 0 )
intrinsicsFilename = argv[++i];
else if( strcmp(argv[i], "-o") == 0 )
outprefix = argv[++i];
else if( strcmp(argv[i], "-w") == 0 )
{
if(sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0)
{
printf("Incorrect -w parameter (must be a positive integer)\n");
puts(help);
return 0;
}
}
else if( strcmp(argv[i], "-h") == 0 )
{
if(sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0)
{
printf("Incorrect -h parameter (must be a positive integer)\n");
puts(help);
return 0;
}
}
else if( strcmp(argv[i], "-s") == 0 )
{
if(sscanf(argv[++i], "%lf", &squareSize) != 1 || squareSize <= 0)
{
printf("Incorrect -w parameter (must be a positive real number)\n");
puts(help);
return 0;
}
}
else if( argv[i][0] != '-' )
{
if( isdigit(argv[i][0]))
sscanf(argv[i], "%d", &cameraId);
else
inputName = argv[i];
}
else
{
printf("Incorrect option\n");
puts(help);
return 0;
}
intrinsicsFilename = argv[++i];
else if( strcmp(argv[i], "-o") == 0 )
outprefix = argv[++i];
else if( strcmp(argv[i], "-w") == 0 )
{
if(sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0)
{
printf("Incorrect -w parameter (must be a positive integer)\n");
puts(help);
return 0;
}
}
else if( strcmp(argv[i], "-h") == 0 )
{
if(sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0)
{
printf("Incorrect -h parameter (must be a positive integer)\n");
puts(help);
return 0;
}
}
else if( strcmp(argv[i], "-s") == 0 )
{
if(sscanf(argv[++i], "%lf", &squareSize) != 1 || squareSize <= 0)
{
printf("Incorrect -w parameter (must be a positive real number)\n");
puts(help);
return 0;
}
}
else if( argv[i][0] != '-' )
{
if( isdigit(argv[i][0]))
sscanf(argv[i], "%d", &cameraId);
else
inputName = argv[i];
}
else
{
printf("Incorrect option\n");
puts(help);
return 0;
}
}
if( !intrinsicsFilename || !outprefix ||
boardSize.width <= 0 || boardSize.height <= 0 )
{
printf("Some of the required parameters are missing\n");
puts(help);
return 0;
}
if( !intrinsicsFilename || !outprefix ||
boardSize.width <= 0 || boardSize.height <= 0 )
{
printf("Some of the required parameters are missing\n");
puts(help);
return 0;
}
Mat cameraMatrix, distCoeffs;
Size calibratedImageSize;
readCameraMatrix(intrinsicsFilename, cameraMatrix, distCoeffs, calibratedImageSize );
VideoCapture capture;
VideoCapture capture;
if( inputName )
{
if( !readStringList(inputName, imageList) &&
@@ -476,10 +476,10 @@ int main(int argc, char** argv)
}
else
capture.open(cameraId);
if( !capture.isOpened() && imageList.empty() )
return fprintf( stderr, "Could not initialize video capture\n" ), -2;
const char* outbarename = 0;
{
outbarename = strrchr(outprefix, '/');
@@ -498,30 +498,30 @@ int main(int argc, char** argv)
else
outbarename = outprefix;
}
Mat frame, shownFrame, selectedObjFrame, mapxy;
namedWindow("View", 1);
Mat frame, shownFrame, selectedObjFrame, mapxy;
namedWindow("View", 1);
namedWindow("Selected Object", 1);
setMouseCallback("View", onMouse, 0);
bool boardFound = false;
string indexFilename = format("%s_index.yml", outprefix);
vector<string> capturedImgList;
vector<Rect> roiList;
vector<Vec6f> poseList;
vector<Point3f> box, boardPoints;
readModelViews(indexFilename, box, capturedImgList, roiList, poseList);
calcChessboardCorners(boardSize, (float)squareSize, boardPoints);
int frameIdx = 0;
bool grabNext = !imageList.empty();
puts(screen_help);
for(int i = 0;;i++)
{
for(int i = 0;;i++)
{
Mat frame0;
if( !imageList.empty() )
{
@@ -538,7 +538,7 @@ int main(int argc, char** argv)
{
double sx = (double)frame0.cols/calibratedImageSize.width;
double sy = (double)frame0.rows/calibratedImageSize.height;
// adjust the camera matrix for the new resolution
cameraMatrix.at<double>(0,0) *= sx;
cameraMatrix.at<double>(0,2) *= sx;
@@ -554,17 +554,17 @@ int main(int argc, char** argv)
remap(frame0, frame, mapxy, Mat(), INTER_LINEAR);
vector<Point2f> foundBoardCorners;
boardFound = findChessboardCorners(frame, boardSize, foundBoardCorners);
Mat rvec, tvec;
if( boardFound )
solvePnP(Mat(boardPoints), Mat(foundBoardCorners), cameraMatrix,
distCoeffs, rvec, tvec, false);
frame.copyTo(shownFrame);
drawChessboardCorners(shownFrame, boardSize, Mat(foundBoardCorners), boardFound);
selectedObjFrame = Mat::zeros(frame.size(), frame.type());
if( boardFound && grabNext )
if( boardFound && grabNext )
{
if( box.empty() )
{
@@ -573,7 +573,7 @@ int main(int argc, char** argv)
if( code == -100 )
break;
}
if( !box.empty() )
{
Rect r = extract3DBox(frame, shownFrame, selectedObjFrame,
@@ -596,10 +596,10 @@ int main(int argc, char** argv)
break;
}
imwrite(path, selectedObjFrame(r));
capturedImgList.push_back(string(path));
roiList.push_back(r);
float p[6];
Mat RV(3, 1, CV_32F, p), TV(3, 1, CV_32F, p+3);
rvec.convertTo(RV, RV.type());
@@ -612,12 +612,12 @@ int main(int argc, char** argv)
imshow("View", shownFrame);
imshow("Selected Object", selectedObjFrame);
int c = waitKey(imageList.empty() && !box.empty() ? 30 : 300);
int c = waitKey(imageList.empty() && !box.empty() ? 30 : 300);
if( c == 'q' || c == 'Q' )
break;
if( c == '\r' || c == '\n' )
grabNext = true;
}
}
writeModelViews(indexFilename, box, capturedImgList, roiList, poseList);
return 0;

View File

@@ -13,16 +13,16 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout <<
"\nA program using pyramid scaling, Canny, contours, contour simpification and\n"
"memory storage (it's got it all folks) to find\n"
"squares in a list of images pic1-6.png\n"
"Returns sequence of squares detected on the image.\n"
"the sequence is stored in the specified memory storage\n"
"Call:\n"
"./squares\n"
cout <<
"\nA program using pyramid scaling, Canny, contours, contour simpification and\n"
"memory storage (it's got it all folks) to find\n"
"squares in a list of images pic1-6.png\n"
"Returns sequence of squares detected on the image.\n"
"the sequence is stored in the specified memory storage\n"
"Call:\n"
"./squares\n"
"Using OpenCV version %s\n" << CV_VERSION << "\n" << endl;
}
@@ -33,7 +33,7 @@ const char* wndname = "Square Detection Demo";
// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
double angle( Point pt1, Point pt2, Point pt0 )
static double angle( Point pt1, Point pt2, Point pt0 )
{
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
@@ -44,23 +44,23 @@ double angle( Point pt1, Point pt2, Point pt0 )
// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
void findSquares( const Mat& image, vector<vector<Point> >& squares )
static void findSquares( const Mat& image, vector<vector<Point> >& squares )
{
squares.clear();
Mat pyr, timg, gray0(image.size(), CV_8U), gray;
// down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;
// find squares in every color plane of the image
for( int c = 0; c < 3; c++ )
{
int ch[] = {c, 0};
mixChannels(&timg, 1, &gray0, 1, ch, 1);
// try several threshold levels
for( int l = 0; l < N; l++ )
{
@@ -86,14 +86,14 @@ void findSquares( const Mat& image, vector<vector<Point> >& squares )
findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
vector<Point> approx;
// test each contour
for( size_t i = 0; i < contours.size(); i++ )
{
// approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
// square contours should have 4 vertices after approximation
// relatively large area (to filter out noisy contours)
// and be convex.
@@ -126,7 +126,7 @@ void findSquares( const Mat& image, vector<vector<Point> >& squares )
// the function draws all the squares in the image
void drawSquares( Mat& image, const vector<vector<Point> >& squares )
static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
{
for( size_t i = 0; i < squares.size(); i++ )
{
@@ -146,7 +146,7 @@ int main(int /*argc*/, char** /*argv*/)
help();
namedWindow( wndname, 1 );
vector<vector<Point> > squares;
for( int i = 0; names[i] != 0; i++ )
{
Mat image = imread(names[i], 1);
@@ -155,7 +155,7 @@ int main(int /*argc*/, char** /*argv*/)
cout << "Couldn't load " << names[i] << endl;
continue;
}
findSquares(image, squares);
drawSquares(image, squares);

View File

@@ -8,11 +8,11 @@
Learning OpenCV: Computer Vision with the OpenCV Library
by Gary Bradski and Adrian Kaehler
Published by O'Reilly Media, October 3, 2008
AVAILABLE AT:
AVAILABLE AT:
http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
Or: http://oreilly.com/catalog/9780596516130/
ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
OTHER OPENCV SITES:
* The source code is on sourceforge at:
@@ -41,17 +41,17 @@
using namespace cv;
using namespace std;
int print_help()
static int print_help()
{
cout <<
" Given a list of chessboard images, the number of corners (nx, ny)\n"
" on the chessboards, and a flag: useCalibrated for \n"
" calibrated (0) or\n"
" uncalibrated \n"
" (1: use cvStereoCalibrate(), 2: compute fundamental\n"
" matrix separately) stereo. \n"
" Calibrate the cameras and display the\n"
" rectified results along with the computed disparity images. \n" << endl;
cout <<
" Given a list of chessboard images, the number of corners (nx, ny)\n"
" on the chessboards, and a flag: useCalibrated for \n"
" calibrated (0) or\n"
" uncalibrated \n"
" (1: use cvStereoCalibrate(), 2: compute fundamental\n"
" matrix separately) stereo. \n"
" Calibrate the cameras and display the\n"
" rectified results along with the computed disparity images. \n" << endl;
cout << "Usage:\n ./stereo_calib -w board_width -h board_height [-nr /*dot not view results*/] <image list XML/YML file>\n" << endl;
return 0;
}
@@ -65,22 +65,22 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
cout << "Error: the image list contains odd (non-even) number of elements\n";
return;
}
bool displayCorners = false;//true;
const int maxScale = 2;
const float squareSize = 1.f; // Set this to your actual square size
// ARRAY AND VECTOR STORAGE:
vector<vector<Point2f> > imagePoints[2];
vector<vector<Point3f> > objectPoints;
Size imageSize;
int i, j, k, nimages = (int)imagelist.size()/2;
imagePoints[0].resize(nimages);
imagePoints[1].resize(nimages);
vector<string> goodImageList;
for( i = j = 0; i < nimages; i++ )
{
for( k = 0; k < 2; k++ )
@@ -105,7 +105,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
timg = img;
else
resize(img, timg, Size(), scale, scale);
found = findChessboardCorners(timg, boardSize, corners,
found = findChessboardCorners(timg, boardSize, corners,
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
if( found )
{
@@ -152,25 +152,25 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
cout << "Error: too little pairs to run the calibration\n";
return;
}
imagePoints[0].resize(nimages);
imagePoints[1].resize(nimages);
objectPoints.resize(nimages);
for( i = 0; i < nimages; i++ )
{
for( j = 0; j < boardSize.height; j++ )
for( k = 0; k < boardSize.width; k++ )
objectPoints[i].push_back(Point3f(j*squareSize, k*squareSize, 0));
}
cout << "Running stereo calibration ...\n";
Mat cameraMatrix[2], distCoeffs[2];
cameraMatrix[0] = Mat::eye(3, 3, CV_64F);
cameraMatrix[1] = Mat::eye(3, 3, CV_64F);
Mat R, T, E, F;
double rms = stereoCalibrate(objectPoints, imagePoints[0], imagePoints[1],
cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
@@ -182,7 +182,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
CV_CALIB_RATIONAL_MODEL +
CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5);
cout << "done with RMS error=" << rms << endl;
// CALIBRATION QUALITY CHECK
// because the output fundamental matrix implicitly
// includes all the output information,
@@ -212,7 +212,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
npoints += npt;
}
cout << "average reprojection err = " << err/npoints << endl;
// save intrinsic parameters
FileStorage fs("intrinsics.yml", CV_STORAGE_WRITE);
if( fs.isOpened() )
@@ -223,15 +223,15 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
}
else
cout << "Error: can not save the intrinsic parameters\n";
Mat R1, R2, P1, P2, Q;
Rect validRoi[2];
stereoRectify(cameraMatrix[0], distCoeffs[0],
cameraMatrix[1], distCoeffs[1],
imageSize, R, T, R1, R2, P1, P2, Q,
CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);
fs.open("extrinsics.yml", CV_STORAGE_WRITE);
if( fs.isOpened() )
{
@@ -240,15 +240,15 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
}
else
cout << "Error: can not save the intrinsic parameters\n";
// OpenCV can handle left-right
// or up-down camera arrangements
bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3));
// COMPUTE AND DISPLAY RECTIFICATION
if( !showRectified )
return;
Mat rmap[2][2];
// IF BY CALIBRATED (BOUGUET'S METHOD)
if( useCalibrated )
@@ -270,7 +270,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0);
Mat H1, H2;
stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3);
R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0];
R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1];
P1 = cameraMatrix[0];
@@ -280,7 +280,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
//Precompute maps for cv::remap()
initUndistortRectifyMap(cameraMatrix[0], distCoeffs[0], R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
initUndistortRectifyMap(cameraMatrix[1], distCoeffs[1], R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);
Mat canvas;
double sf;
int w, h;
@@ -298,7 +298,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
h = cvRound(imageSize.height*sf);
canvas.create(h*2, w, CV_8UC3);
}
for( i = 0; i < nimages; i++ )
{
for( k = 0; k < 2; k++ )
@@ -311,11 +311,11 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
if( useCalibrated )
{
Rect vroi(cvRound(validRoi[k].x*sf), cvRound(validRoi[k].y*sf),
cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
cvRound(validRoi[k].width*sf), cvRound(validRoi[k].height*sf));
rectangle(canvasPart, vroi, Scalar(0,0,255), 3, 8);
}
}
if( !isVerticalStereo )
for( j = 0; j < canvas.rows; j += 16 )
line(canvas, Point(0, j), Point(canvas.cols, j), Scalar(0, 255, 0), 1, 8);
@@ -329,7 +329,7 @@ StereoCalib(const vector<string>& imagelist, Size boardSize, bool useCalibrated=
}
}
static bool readStringList( const string& filename, vector<string>& l )
{
l.resize(0);
@@ -344,13 +344,13 @@ static bool readStringList( const string& filename, vector<string>& l )
l.push_back((string)*it);
return true;
}
int main(int argc, char** argv)
{
Size boardSize;
string imagelistfn;
bool showRectified = true;
for( int i = 1; i < argc; i++ )
{
if( string(argv[i]) == "-w" )
@@ -381,7 +381,7 @@ int main(int argc, char** argv)
else
imagelistfn = argv[i];
}
if( imagelistfn == "" )
{
imagelistfn = "stereo_calib.xml";
@@ -389,10 +389,10 @@ int main(int argc, char** argv)
}
else if( boardSize.width <= 0 || boardSize.height <= 0 )
{
cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl;
cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl;
return 0;
}
vector<string> imagelist;
bool ok = readStringList(imagelistfn, imagelist);
if(!ok || imagelist.empty())
@@ -400,7 +400,7 @@ int main(int argc, char** argv)
cout << "can not open " << imagelistfn << " or the string list is empty" << endl;
return print_help();
}
StereoCalib(imagelist, boardSize, true, showRectified);
return 0;
}

View File

@@ -16,15 +16,15 @@
using namespace cv;
void print_help()
static void print_help()
{
printf("\nDemo stereo matching converting L and R images into disparity and point clouds\n");
printf("\nDemo stereo matching converting L and R images into disparity and point clouds\n");
printf("\nUsage: stereo_match <left_image> <right_image> [--algorithm=bm|sgbm|hh|var] [--blocksize=<block_size>]\n"
"[--max-disparity=<max_disparity>] [--scale=scale_factor>] [-i <intrinsic_filename>] [-e <extrinsic_filename>]\n"
"[--no-display] [-o <disparity_image>] [-p <point_cloud_file>]\n");
}
void saveXYZ(const char* filename, const Mat& mat)
static void saveXYZ(const char* filename, const Mat& mat)
{
const double max_z = 1.0e4;
FILE* fp = fopen(filename, "wt");
@@ -47,11 +47,11 @@ int main(int argc, char** argv)
const char* blocksize_opt = "--blocksize=";
const char* nodisplay_opt = "--no-display=";
const char* scale_opt = "--scale=";
if(argc < 3)
{
print_help();
return 0;
return 0;
}
const char* img1_filename = 0;
const char* img2_filename = 0;
@@ -59,17 +59,17 @@ int main(int argc, char** argv)
const char* extrinsic_filename = 0;
const char* disparity_filename = 0;
const char* point_cloud_filename = 0;
enum { STEREO_BM=0, STEREO_SGBM=1, STEREO_HH=2, STEREO_VAR=3 };
int alg = STEREO_SGBM;
int SADWindowSize = 0, numberOfDisparities = 0;
bool no_display = false;
float scale = 1.f;
StereoBM bm;
StereoSGBM sgbm;
StereoVar var;
for( int i = 1; i < argc; i++ )
{
if( argv[i][0] != '-' )
@@ -136,29 +136,29 @@ int main(int argc, char** argv)
return -1;
}
}
if( !img1_filename || !img2_filename )
{
printf("Command-line parameter error: both left and right images must be specified\n");
return -1;
}
if( (intrinsic_filename != 0) ^ (extrinsic_filename != 0) )
{
printf("Command-line parameter error: either both intrinsic and extrinsic parameters must be specified, or none of them (when the stereo pair is already rectified)\n");
return -1;
}
if( extrinsic_filename == 0 && point_cloud_filename )
{
printf("Command-line parameter error: extrinsic and intrinsic parameters must be specified to compute the point cloud\n");
return -1;
}
int color_mode = alg == STEREO_BM ? 0 : -1;
Mat img1 = imread(img1_filename, color_mode);
Mat img2 = imread(img2_filename, color_mode);
if( scale != 1.f )
{
Mat temp1, temp2;
@@ -168,12 +168,12 @@ int main(int argc, char** argv)
resize(img2, temp2, Size(), scale, scale, method);
img2 = temp2;
}
Size img_size = img1.size();
Rect roi1, roi2;
Mat Q;
if( intrinsic_filename )
{
// reading intrinsic parameters
@@ -183,40 +183,40 @@ int main(int argc, char** argv)
printf("Failed to open file %s\n", intrinsic_filename);
return -1;
}
Mat M1, D1, M2, D2;
fs["M1"] >> M1;
fs["D1"] >> D1;
fs["M2"] >> M2;
fs["D2"] >> D2;
fs.open(extrinsic_filename, CV_STORAGE_READ);
if(!fs.isOpened())
{
printf("Failed to open file %s\n", extrinsic_filename);
return -1;
}
Mat R, T, R1, P1, R2, P2;
fs["R"] >> R;
fs["T"] >> T;
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(img1, img1r, map11, map12, INTER_LINEAR);
remap(img2, img2r, map21, map22, INTER_LINEAR);
img1 = img1r;
img2 = img2r;
}
numberOfDisparities = numberOfDisparities > 0 ? numberOfDisparities : ((img_size.width/8) + 15) & -16;
bm.state->roi1 = roi1;
bm.state->roi2 = roi2;
bm.state->preFilterCap = 31;
@@ -228,12 +228,12 @@ int main(int argc, char** argv)
bm.state->speckleWindowSize = 100;
bm.state->speckleRange = 32;
bm.state->disp12MaxDiff = 1;
sgbm.preFilterCap = 63;
sgbm.SADWindowSize = SADWindowSize > 0 ? SADWindowSize : 3;
int cn = img1.channels();
sgbm.P1 = 8*cn*sgbm.SADWindowSize*sgbm.SADWindowSize;
sgbm.P2 = 32*cn*sgbm.SADWindowSize*sgbm.SADWindowSize;
sgbm.minDisparity = 0;
@@ -243,31 +243,31 @@ int main(int argc, char** argv)
sgbm.speckleRange = bm.state->speckleRange;
sgbm.disp12MaxDiff = 1;
sgbm.fullDP = alg == STEREO_HH;
var.levels = 3; // ignored with USE_AUTO_PARAMS
var.pyrScale = 0.5; // ignored with USE_AUTO_PARAMS
var.nIt = 25;
var.minDisp = -numberOfDisparities;
var.maxDisp = 0;
var.poly_n = 3;
var.poly_sigma = 0.0;
var.fi = 15.0f;
var.lambda = 0.03f;
var.penalization = var.PENALIZATION_TICHONOV; // ignored with USE_AUTO_PARAMS
var.cycle = var.CYCLE_V; // ignored with USE_AUTO_PARAMS
var.flags = var.USE_SMART_ID | var.USE_AUTO_PARAMS | var.USE_INITIAL_DISPARITY | var.USE_MEDIAN_FILTERING ;
var.levels = 3; // ignored with USE_AUTO_PARAMS
var.pyrScale = 0.5; // ignored with USE_AUTO_PARAMS
var.nIt = 25;
var.minDisp = -numberOfDisparities;
var.maxDisp = 0;
var.poly_n = 3;
var.poly_sigma = 0.0;
var.fi = 15.0f;
var.lambda = 0.03f;
var.penalization = var.PENALIZATION_TICHONOV; // ignored with USE_AUTO_PARAMS
var.cycle = var.CYCLE_V; // ignored with USE_AUTO_PARAMS
var.flags = var.USE_SMART_ID | var.USE_AUTO_PARAMS | var.USE_INITIAL_DISPARITY | var.USE_MEDIAN_FILTERING ;
Mat disp, disp8;
//Mat img1p, img2p, dispp;
//copyMakeBorder(img1, img1p, 0, 0, numberOfDisparities, 0, IPL_BORDER_REPLICATE);
//copyMakeBorder(img2, img2p, 0, 0, numberOfDisparities, 0, IPL_BORDER_REPLICATE);
int64 t = getTickCount();
if( alg == STEREO_BM )
bm(img1, img2, disp);
else if( alg == STEREO_VAR ) {
var(img1, img2, disp);
}
}
else if( alg == STEREO_SGBM || alg == STEREO_HH )
sgbm(img1, img2, disp);
t = getTickCount() - t;
@@ -291,10 +291,10 @@ int main(int argc, char** argv)
waitKey();
printf("\n");
}
if(disparity_filename)
imwrite(disparity_filename, disp8);
if(point_cloud_filename)
{
printf("storing the point cloud...");
@@ -304,6 +304,6 @@ int main(int argc, char** argv)
saveXYZ(point_cloud_filename, xyz);
printf("\n");
}
return 0;
}

View File

@@ -37,7 +37,7 @@
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//
//
//M*/
@@ -60,7 +60,7 @@ using namespace std;
using namespace cv;
using namespace cv::detail;
void printUsage()
static void printUsage()
{
cout <<
"Rotation model images stitcher.\n\n"
@@ -141,7 +141,7 @@ int blend_type = Blender::MULTI_BAND;
float blend_strength = 5;
string result_name = "result.jpg";
int parseCmdArgs(int argc, char** argv)
static int parseCmdArgs(int argc, char** argv)
{
if (argc == 1)
{
@@ -471,10 +471,10 @@ int main(int argc, char* argv[])
Ptr<detail::BundleAdjusterBase> adjuster;
if (ba_cost_func == "reproj") adjuster = new detail::BundleAdjusterReproj();
else if (ba_cost_func == "ray") adjuster = new detail::BundleAdjusterRay();
else
{
cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n";
return -1;
else
{
cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n";
return -1;
}
adjuster->setConfThresh(conf_thresh);
Mat_<uchar> refine_mask = Mat::zeros(3, 3, CV_8U);
@@ -544,18 +544,18 @@ int main(int argc, char* argv[])
if (warp_type == "plane") warper_creator = new cv::PlaneWarper();
else if (warp_type == "cylindrical") warper_creator = new cv::CylindricalWarper();
else if (warp_type == "spherical") warper_creator = new cv::SphericalWarper();
else if (warp_type == "fisheye") warper_creator = new cv::FisheyeWarper();
else if (warp_type == "stereographic") warper_creator = new cv::StereographicWarper();
else if (warp_type == "compressedPlaneA2B1") warper_creator = new cv::CompressedRectilinearWarper(2, 1);
else if (warp_type == "compressedPlaneA1.5B1") warper_creator = new cv::CompressedRectilinearWarper(1.5, 1);
else if (warp_type == "compressedPlanePortraitA2B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(2, 1);
else if (warp_type == "compressedPlanePortraitA1.5B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(1.5, 1);
else if (warp_type == "paniniA2B1") warper_creator = new cv::PaniniWarper(2, 1);
else if (warp_type == "paniniA1.5B1") warper_creator = new cv::PaniniWarper(1.5, 1);
else if (warp_type == "paniniPortraitA2B1") warper_creator = new cv::PaniniPortraitWarper(2, 1);
else if (warp_type == "paniniPortraitA1.5B1") warper_creator = new cv::PaniniPortraitWarper(1.5, 1);
else if (warp_type == "mercator") warper_creator = new cv::MercatorWarper();
else if (warp_type == "transverseMercator") warper_creator = new cv::TransverseMercatorWarper();
else if (warp_type == "fisheye") warper_creator = new cv::FisheyeWarper();
else if (warp_type == "stereographic") warper_creator = new cv::StereographicWarper();
else if (warp_type == "compressedPlaneA2B1") warper_creator = new cv::CompressedRectilinearWarper(2, 1);
else if (warp_type == "compressedPlaneA1.5B1") warper_creator = new cv::CompressedRectilinearWarper(1.5, 1);
else if (warp_type == "compressedPlanePortraitA2B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(2, 1);
else if (warp_type == "compressedPlanePortraitA1.5B1") warper_creator = new cv::CompressedRectilinearPortraitWarper(1.5, 1);
else if (warp_type == "paniniA2B1") warper_creator = new cv::PaniniWarper(2, 1);
else if (warp_type == "paniniA1.5B1") warper_creator = new cv::PaniniWarper(1.5, 1);
else if (warp_type == "paniniPortraitA2B1") warper_creator = new cv::PaniniPortraitWarper(2, 1);
else if (warp_type == "paniniPortraitA1.5B1") warper_creator = new cv::PaniniPortraitWarper(1.5, 1);
else if (warp_type == "mercator") warper_creator = new cv::MercatorWarper();
else if (warp_type == "transverseMercator") warper_creator = new cv::TransverseMercatorWarper();
}
if (warper_creator.empty())
@@ -563,7 +563,7 @@ int main(int argc, char* argv[])
cout << "Can't create the following warper '" << warp_type << "'\n";
return 1;
}
Ptr<RotationWarper> warper = warper_creator->create(static_cast<float>(warped_image_scale * seam_work_aspect));
for (int i = 0; i < num_images; ++i)

View File

@@ -16,7 +16,7 @@
using namespace std;
using namespace cv;
void help(char **av)
static void help(char **av)
{
cout << "\nThis program demonstrated the use of features2d with the Fast corner detector and brief descriptors\n"
<< "to track planar objects by computing their homography from the key (training) image to the query (test) image\n\n" << endl;

View File

@@ -7,24 +7,24 @@
using namespace cv;
using namespace std;
void help()
static void help()
{
cout << "\nThis program demonstrates the famous watershed segmentation algorithm in OpenCV: watershed()\n"
"Usage:\n"
"./watershed [image_name -- default is fruits.jpg]\n" << endl;
cout << "\nThis program demonstrates the famous watershed segmentation algorithm in OpenCV: watershed()\n"
"Usage:\n"
"./watershed [image_name -- default is fruits.jpg]\n" << endl;
cout << "Hot keys: \n"
"\tESC - quit the program\n"
"\tr - restore the original image\n"
"\tw or SPACE - run watershed segmentation algorithm\n"
"\t\t(before running it, *roughly* mark the areas to segment on the image)\n"
"\t (before that, roughly outline several markers on the image)\n";
cout << "Hot keys: \n"
"\tESC - quit the program\n"
"\tr - restore the original image\n"
"\tw or SPACE - run watershed segmentation algorithm\n"
"\t\t(before running it, *roughly* mark the areas to segment on the image)\n"
"\t (before that, roughly outline several markers on the image)\n";
}
Mat markerMask, img;
Point prevPt(-1, -1);
void onMouse( int event, int x, int y, int flags, void* )
static void onMouse( int event, int x, int y, int flags, void* )
{
if( x < 0 || x >= img.cols || y < 0 || y >= img.rows )
return;
@@ -48,7 +48,7 @@ int main( int argc, char** argv )
{
char* filename = argc >= 2 ? argv[1] : (char*)"fruits.jpg";
Mat img0 = imread(filename, 1), imgGray;
if( img0.empty() )
{
cout << "Couldn'g open image " << filename << ". Usage: watershed <image_name>\n";
@@ -83,9 +83,9 @@ int main( int argc, char** argv )
int i, j, compCount = 0;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(markerMask, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
if( contours.empty() )
continue;
Mat markers(markerMask.size(), CV_32S);
@@ -96,14 +96,14 @@ int main( int argc, char** argv )
if( compCount == 0 )
continue;
vector<Vec3b> colorTab;
for( i = 0; i < compCount; i++ )
{
int b = theRNG().uniform(0, 255);
int g = theRNG().uniform(0, 255);
int r = theRNG().uniform(0, 255);
colorTab.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));
}
@@ -113,7 +113,7 @@ int main( int argc, char** argv )
printf( "execution time = %gms\n", t*1000./getTickFrequency() );
Mat wshed(markers.size(), CV_8UC3);
// paint the watershed image
for( i = 0; i < markers.rows; i++ )
for( j = 0; j < markers.cols; j++ )