Exemple #1
0
std::string ImageFinder::FindImage(char *data, int width, int height, int scrollx, int scrolly)
{
    Mat Screen = Mat(height, width, CV_8UC4, data);

    int result_cols =  Screen.cols - ImageToFind.cols + 1;
    int result_rows = Screen.rows - ImageToFind.rows + 1;

    if(result_cols<=0 || result_rows<=0)
        return std::string("-1|0|0|") + std::to_string(Width) + std::string("|") + std::to_string(Height);

    if(Result.cols != result_cols || Result.rows != result_rows)
    {
        Result.release();
        Result.create( result_rows, result_cols, CV_32FC1 );
    }

    matchTemplate( Screen, ImageToFind, Result, CV_TM_CCOEFF_NORMED );

    double minVal; double maxVal; Point minLoc; Point maxLoc;
    Point matchLoc;

    minMaxLoc( Result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

    matchLoc = maxLoc;

    Screen.release();
    //Result.release();

    return std::to_string((int)(maxVal * 100.0)) + std::string("|") + std::to_string(matchLoc.x + scrollx) + std::string("|") + std::to_string(matchLoc.y + scrolly) + std::string("|") + std::to_string(Width) + std::string("|") + std::to_string(Height);
}
Point PatchMatcher::getNewOffset(bool *foundMask) const {

    int minX, maxX, minY, maxY;
    getBoundaries(*outputMask, &minX, &maxX, &minY, &maxY);

    if (maxX < 0 || maxY < 0) {
        *foundMask = false;
        return Point(randRange(0, outputMask->width()  - patch->width()  + 1),
                     randRange(0, outputMask->height() - patch->height() + 1));
    } else {
        *foundMask = true;

        Image<float> C;

        // Compute allowed translations window
        minX = max(0, minX - patch->width()  + OVERLAP_WIDTH);
        minY = max(0, minY - patch->height() + OVERLAP_WIDTH);
        maxX = min(output->width()  - 1, maxX + patch->width()  - OVERLAP_WIDTH);
        maxY = min(output->height() - 1, maxY + patch->height() - OVERLAP_WIDTH);
        const Rect outputRect(minX, minY, maxX - minX + 1, maxY - minY + 1);

        Mat patchF, outputF;
        assert(patch->type() == CV_8UC3);
        assert(output->type() == CV_8UC3);

        patch->convertTo(patchF, CV_32FC3);
        ((Mat) *output)(outputRect).convertTo(outputF, CV_32FC3);

        matchTemplate(outputF, patchF, C, TM_SQDIFF);

        exp(C * factor, C);

//        imshow("C", C.greyImage());

        float acc, *data = (float *) C.data;

        for (int i = 0; i < C.height() * C.width(); i++) {
            acc += data[i];
            data[i] = acc;
        }

        int a = 0, b = C.height() * C.width() - 1;
        const float p = data[b] * (static_cast <float> (rand()) / static_cast <float> (RAND_MAX));

        // Dichotomy search
        while (b - a > 0) {
            const int m = (a + b) / 2;
            if (p > data[m])
                a = m + 1;
            else
                b = m;
        }

        // Seems to work
//        assert(p <= data[a] && (a == 0 || p > data[a-1]));
//        assert(data[a] == C(a % C.width(), a / C.width()));

        return Point(minX + a % C.width(), minY + a / C.width());
    }
}
Exemple #3
0
float NNClassifier::calcNCC(const Mat &patch1, const Mat &patch2)
{
    if(NCC_USE_OPENCV)
    {
        Mat nccMat;
        matchTemplate(patch1, patch2, nccMat, CV_TM_CCORR_NORMED);
        
        return nccMat.at<float>(0);
    }
    else
    {
        if(NCC_FAST)
        {
            Mat v0, v1;
            
            v0 = patch1.reshape(0, 1);
            v1 = patch2.reshape(0, 1);
            
            double norm0 = 0., norm1 = 0., v0v1 = 0.;
            
            float *data0 = v0.ptr<float>(0);
            float *data1 = v1.ptr<float>(0);
            
            for(int i = 0; i < v0.cols; i++)
            {
                norm0 += data0[i] * data0[i];
                norm1 += data1[i] * data1[i];
                v0v1 += data0[i] * data1[i];
            }
        
            norm0 = sqrt(norm0);
            norm1 = sqrt(norm1);
            
            double ret = v0v1 / norm0 / norm1;
            return ret;
        }
        else
        {
            Mat v0, v1; // convert image to 1 dimension vector
            
            v0 = patch1;
            v1 = patch2;
            
            v0 = v0.reshape(0, v0.cols * v0.rows);
            v1 = v1.reshape(0, v1.cols * v1.rows);
            
            Mat v01 = v0.t() * v1;
            
            float norm0, norm1;
            
            norm0 = norm(v0);
            norm1 = norm(v1);
            
            // should not add "abs"
            float ret = v01.at<float>(0) / norm0 / norm1;
            
            return ret;
        }
    }
}
Exemple #4
0
static bool matchTemplate_CCOEFF(InputArray _image, InputArray _templ, OutputArray _result)
{
    matchTemplate(_image, _templ, _result, CV_TM_CCORR);

    UMat image_sums, temp;
    integral(_image, image_sums, CV_32F);

    int type = image_sums.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);

    ocl::Kernel k("matchTemplate_Prepared_CCOEFF", ocl::imgproc::match_template_oclsrc,
                  format("-D CCOEFF -D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn));
    if (k.empty())
        return false;

    UMat templ  = _templ.getUMat();
    UMat result = _result.getUMat();

    if (cn==1)
    {
        Scalar templMean = mean(templ);
        float templ_sum = (float)templMean[0];

        k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, templ_sum);
    }
    else
    {
        Vec4f templ_sum = Vec4f::all(0);
        templ_sum = (Vec4f)mean(templ);

       k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, templ_sum);    }

    size_t globalsize[2] = { result.cols, result.rows };
    return k.run(2, globalsize, NULL, false);
}
Exemple #5
0
//----------------------------------------------------------------------------------
void PAN::templateMatch(Mat inputimg, Mat find, Point &point, float &threshold, float &percentage)
{
	int erosion_size = 3;
	Mat element = getStructuringElement(MORPH_ELLIPSE, Size(2 * erosion_size + 1, 2 * erosion_size + 1), Point(erosion_size, erosion_size));
	if (inputimg.channels() >= 2){
		cvtColor(inputimg,inputimg, COLOR_BGR2GRAY);
		erode(inputimg, inputimg, element);
	}
	if (find.channels() >= 2){
		cvtColor(find,find, COLOR_BGR2GRAY);
		erode(find,find, element);
	}
	int resultrows, resultcols;
	double minv, maxv;
	Point minloc, maxloc;

	Mat result;

	resultrows = inputimg.rows - find.rows + 1;
	resultcols = inputimg.cols - find.cols + 1;

	matchTemplate(inputimg, find, result, CV_TM_CCOEFF_NORMED);
	minMaxLoc(result, &minv, &maxv, &minloc, &maxloc, Mat());
	imshow("find", find);
	waitKey(0);
	point = maxloc;
	threshold = (float)maxv;
	percentage = ((float)(maxv)* 100);
	//imshow("template match result", result);
	//waitKey();

}
float MedianFlow::calcNCC(const cv::Mat &img0, const cv::Mat &img1)
{
    if(NCC_USE_OPENCV)
    {
        Mat nccMat;
        matchTemplate(img0, img1, nccMat, CV_TM_CCORR_NORMED);
        
        return nccMat.at<float>(0);
    }
    else
    {
        Mat v0, v1; // convert image to 1 dimension vector
        
        img0.convertTo(v0, CV_32F);
        img1.convertTo(v1, CV_32F);
        
        v0 = v0.reshape(0, v0.cols * v0.rows);
        v1 = v1.reshape(0, v1.cols * v1.rows);
        
        Mat v01 = v0.t() * v1;
        
        float norm0, norm1;
        
        norm0 = norm(v0);
        norm1 = norm(v1);
        
        return v01.at<float>(0) / norm0 / norm1;
    }
}
Exemple #7
0
static bool matchTemplate_SQDIFF_NORMED(InputArray _image, InputArray _templ, OutputArray _result)
{
    matchTemplate(_image, _templ, _result, CV_TM_CCORR);

    int type = _image.type(), cn = CV_MAT_CN(type);

    ocl::Kernel k("matchTemplate_SQDIFF_NORMED", ocl::imgproc::match_template_oclsrc,
                  format("-D SQDIFF_NORMED -D T=%s -D cn=%d", ocl::typeToStr(type),  cn));
    if (k.empty())
        return false;

    UMat image = _image.getUMat(), templ = _templ.getUMat();
    _result.create(image.rows - templ.rows + 1, image.cols - templ.cols + 1, CV_32F);
    UMat result = _result.getUMat();

    UMat image_sums, image_sqsums;
    integral(image.reshape(1), image_sums, image_sqsums, CV_32F, CV_32F);

    UMat templ_sqsum;
    if (!sumTemplate(_templ, templ_sqsum))
        return false;

    k.args(ocl::KernelArg::ReadOnlyNoSize(image_sqsums), ocl::KernelArg::ReadWrite(result),
           templ.rows, templ.cols, ocl::KernelArg::PtrReadOnly(templ_sqsum));

    size_t globalsize[2] = { result.cols, result.rows };

    return k.run(2, globalsize, NULL, false);
}
Point ImageProcessor::findRobot(Mat * room, Robot * robot)
{
	Point robotPos;
	
	// load picture of robot into "bot"
	Mat bot = robot->peekSymbol().clone();
	
	// Needed for matchTemplate, which finds the robot picture inside the bigger pic
	Mat rtn((room->rows - bot.rows) + 1, (room->cols - bot.cols) + 1,DataType<float>::type); 
	
	//A openCV algorithm that will fill rtn with itegers where the minimum point is where the robot is found
	matchTemplate(*(room), bot, rtn, CV_TM_SQDIFF);


	Point robotLoc;
	robotLoc.x = 0; robotLoc.y = 0; // Point robotLoc(0,0) wasn't working for some reason
	double minVal = 0;

	minMaxLoc(rtn, &minVal,(double *)0,&robotLoc,(Point *)0,Mat());
	
	//what this should be is the position it is in with relation to the rtn Mat * the size of the robot pic in pixels
	robotPos.x = robotLoc.x;
	robotPos.y = robotLoc.y;

	// Assume robot is facing "up" or "down"
	robotPos.x += robot->getWidth() / 2;
	robotPos.y += robot->getLength() / 2;

	return robotPos;
}
Exemple #9
0
//RETURNS THE TOP-LEFT CORNER OF THE REFLECTION OF sourceTemplate ON image
cv::Rect findBestMatchLocation( const cv::Mat& image, const cv::Rect& source_rect, 
        double* nsigma, const cv::Mat& mask )
{
    cv::Mat image_gray;
    cvtColor( image, image_gray, CV_RGB2GRAY, 1 );
    cv::Mat image_copy = image_gray.clone();
    
    // Create template.
    cv::Mat image_template_copy = image_gray.clone();
    cv::Mat sourceTemplate = image_template_copy( source_rect );
    flip( sourceTemplate, sourceTemplate, 0 );

    // Creates results matrix where the top left corner of the 
    // template is slid across each pixel of the source
    int result_cols = image.cols-sourceTemplate.cols+1;
    int result_rows = image.rows-sourceTemplate.rows+1;
    cv::Mat result;
    result.create( result_cols,result_rows, CV_32FC1 );

    // Mask image to match only in selected ROI.
    if( !mask.empty() )
    {
        cv::Mat tmp;
		image_copy.copyTo( tmp, mask );
        image_copy = tmp;
    }

    //0:CV_TM_SQDIFF
    //1:CV_TM_SQDIFF_NORMED
    //2:CV_TM_CORR
    //3:CV_TM_CCOR_NORMED
    //4:CV_TM_CCOEFF
    //5:CV_TM_CCOEFF_NORMED <----Most succesful at finding reflections
    
    int match_method = CV_TM_CCOEFF_NORMED; // 4 seemed good for stddev thresholding.

    //matchTemplate( masked_scene, sourceTemplate, result, match_method );
    matchTemplate( image_gray, sourceTemplate, result, match_method );

    double minVal, maxVal; 
    cv::Point minLoc, maxLoc, matchLoc;
    minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat() );
     
    if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    {
        matchLoc = minLoc;	
    }
    else 
    {
        matchLoc = maxLoc;
    }
    cv::Scalar mean, stddev;
    meanStdDev( result, mean, stddev, cv::Mat() );
    *nsigma = ( maxVal-mean[0] )/ stddev[0];
    // matchLoc is the location of the top left corner of the reflection
    // that matchTemplate found

    return cv::Rect( matchLoc, source_rect.size() );
}
int CBrakeBeamPillarRoundPinDetector::FindBrakeBeamClampYPos(int brakeBeamClampXPos, int index)
{
    Mat templateImage[2];
    string templateFileName[2];
    char currentDirectory[MAX_PATH];						//当前路径
    GetModuleFileName(NULL, currentDirectory, MAX_PATH);	//获取当前路径
    for (int i = strlen(currentDirectory)-1; i != 0; --i)
    {
        if (currentDirectory[i] != '\\')
        {
            currentDirectory[i] = currentDirectory[i+1];
        }
        else
            break;
    }
    strcat(currentDirectory, "\\Images");
    string templateImagePath = currentDirectory;

    //读取模板图像
    templateFileName[0] = templateImagePath + "\\Template\\template_1.jpg";
    templateFileName[1] = templateImagePath + "\\Template\\template_2.jpg";
    templateImage[0] = imread(templateFileName[0], 0);
    templateImage[1] = imread(templateFileName[1], 0);
    float maxMatchVal = -1.0;
    Point matchPoint;
    int templateIndex = 0;
    int middleBarLeftLine = 0;

    middleBarLeftLine = brakeBeamClampXPos;								//获得中间杆的左边缘

    for (int j = 0; j != 2; ++j)
    {
        Mat compareResult;																//匹配结果矩阵
        //定义查找夹扣的ROI
        Mat searchBrakeBeamClamp_ROI = m_srcImageArray[index](Rect(middleBarLeftLine,
                                       m_srcImageArray[index].rows/3, 180, m_srcImageArray[index].rows/3));

        compareResult.create(searchBrakeBeamClamp_ROI.rows - templateImage[j].rows + 1,
                             searchBrakeBeamClamp_ROI.cols - templateImage[j].cols + 1, CV_32FC1);

        matchTemplate(searchBrakeBeamClamp_ROI, templateImage[j], compareResult, CV_TM_CCOEFF_NORMED);	//模板匹配

        double minVal,maxVal;															//矩阵中最小值,最大值
        Point minLoc;																	//最小值的坐标
        Point matchLoc;																	//最匹配值的坐标
        minMaxLoc(compareResult, &minVal, &maxVal, &minLoc, &matchLoc, cv::Mat());		//寻找最匹配的点
        if (maxVal > maxMatchVal)
        {
            maxMatchVal = maxVal;
            matchPoint.x = matchLoc.x + middleBarLeftLine;
            matchPoint.y = matchLoc.y + m_srcImageArray[index].rows/3;
            templateIndex = j;
        }
    }
    return matchPoint.y;
}
Exemple #11
0
CV_IMPL void
cvMatchTemplate( const CvArr* _img, const CvArr* _templ, CvArr* _result, int method )
{
    cv::Mat img = cv::cvarrToMat(_img), templ = cv::cvarrToMat(_templ),
        result = cv::cvarrToMat(_result);
    CV_Assert( result.size() == cv::Size(std::abs(img.cols - templ.cols) + 1,
                                         std::abs(img.rows - templ.rows) + 1) &&
              result.type() == CV_32F );
    matchTemplate(img, templ, result, method);
}
//==============================================================================
Mat 
patch_model::
calc_response(const Mat &im,const bool sum2one)
{
  Mat I = this->convert_image(im);
  Mat res; matchTemplate(I,P,res,CV_TM_CCOEFF_NORMED); 
  if(sum2one){
    normalize(res,res,0,1,NORM_MINMAX); res /= sum(res)[0];
  }return res;
}
double PyramidTemplateMatcher::findBest(const MatchingData& data, Rect* roi, Mat& out_result, Point& out_location){
      TimingBlock t("PyramidTemplateMatcher::findBest");
      double out_score;
      Mat source;
      if(roi != NULL)
         source = data.getSource()(*roi);
      else
         source = data.getSource();
      const Mat& target = data.getTarget();

#ifdef ENABLE_GPU
      if(_use_gpu){
         gpu::GpuMat gSource, gTarget;
         gSource.upload(source);
         gTarget.upload(target);
         gpu::matchTemplate(gSource,gTarget,gResult,CV_TM_CCOEFF_NORMED);
         gpu::minMaxLoc(gResult, NULL, &out_score, NULL, &out_location);
         return out_score;
      }
#endif

      if(data.isSameColor()){ // pure color target
         source = data.getOrigSource();
         if(roi != NULL)
            source = source(*roi);
         if(data.isBlack()){ // black target
            Mat inv_source, inv_target;
            bitwise_not(source, inv_source);
            bitwise_not(data.getOrigTarget(), inv_target);
            matchTemplate(inv_source, inv_target, out_result, CV_TM_SQDIFF_NORMED);   
         } 
         else{
            matchTemplate(source, data.getOrigTarget(), out_result, CV_TM_SQDIFF_NORMED);   
         }
         result = Mat::ones(out_result.size(), CV_32F) - result;
      }
      else{
         matchTemplate(source, target, out_result, CV_TM_CCOEFF_NORMED);
      }
      minMaxLoc(result, NULL, &out_score, NULL, &out_location);
      return out_score;
}
//==============================================================================
void 
patch_model::
train(const vector<Mat> &images,
      const Size psize,
      const float var,
      const float lambda,
      const float mu_init,
      const int nsamples,
      const bool visi)
{
  int N = images.size(),n = psize.width*psize.height;

  //compute desired response map
  Size wsize = images[0].size();
  if((wsize.width < psize.width) || (wsize.height < psize.height)){
    cerr << "Invalid image size < patch size!" << endl; throw std::exception();
  }
  int dx = wsize.width-psize.width,dy = wsize.height-psize.height;
  Mat F(dy,dx,CV_32F);
  for(int y = 0; y < dy; y++){   float vy = (dy-1)/2 - y;
    for(int x = 0; x < dx; x++){ float vx = (dx-1)/2 - x;
      F.fl(y,x) = exp(-0.5*(vx*vx+vy*vy)/var);
    }
  }
  normalize(F,F,0,1,NORM_MINMAX);

  //allocate memory
  Mat I(wsize.height,wsize.width,CV_32F);
  Mat dP(psize.height,psize.width,CV_32F);
  Mat O = Mat::ones(psize.height,psize.width,CV_32F)/n;
  P = Mat::zeros(psize.height,psize.width,CV_32F);

  //optimise using stochastic gradient descent
  RNG rn(getTickCount()); double mu=mu_init,step=pow(1e-8/mu_init,1.0/nsamples);
  for(int sample = 0; sample < nsamples; sample++){ int i = rn.uniform(0,N);
    I = this->convert_image(images[i]); dP = 0.0;
    for(int y = 0; y < dy; y++){
      for(int x = 0; x < dx; x++){
    Mat Wi = I(Rect(x,y,psize.width,psize.height)).clone();
    Wi -= Wi.dot(O); normalize(Wi,Wi);
    dP += (F.fl(y,x) - P.dot(Wi))*Wi;
      }
    }    
    P += mu*(dP - lambda*P); mu *= step;
    if(visi){
      Mat R; matchTemplate(I,P,R,CV_TM_CCOEFF_NORMED);
      Mat PP; normalize(P,PP,0,1,NORM_MINMAX);
      normalize(dP,dP,0,1,NORM_MINMAX);
      normalize(R,R,0,1,NORM_MINMAX);
      imshow("P",PP); imshow("dP",dP); imshow("R",R); 
      if(waitKey(10) == 27)break;
    }
  }return;
}
Exemple #15
0
//Thread tracking du MatchTemplate (combiné aux points d'intérêts
void *matchTemplate(void * args)
{
	/*
	   DEBUT TRAITEMENT MATCHTEMPLATE
	 */
	Mat result(imgOriginal.cols - Ball.getPicture().cols + 1, imgOriginal.rows - Ball.getPicture().rows + 1, CV_32FC1);
	matchTemplate(imgOriginal, Ball.getPicture(), result, CV_TM_SQDIFF_NORMED);
	//normalize(result, result, -1, 1, NORM_MINMAX, -1, Mat());
	double minVal, maxVal;
	Point minLoc, maxLoc;
	minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
	//Rect target = Rect(maxLoc.x, maxLoc.y, Ball.getPicture().cols, Ball.getPicture().rows);
	Rect target = Rect(minLoc.x, minLoc.y, Ball.getPicture().cols, Ball.getPicture().rows);
	/*
	   FIN TRAITEMENT MATCHTEMPLATE
	 */


	/*
		DEBUT TRAITEMENT KEYPOINTS
	 */

	Mat imgGray1;
	int minHessian = 400;
	cvtColor(imgOriginal(target), imgGray1, COLOR_BGR2GRAY);
	Ptr<SURF> detector = SURF::create(minHessian);
	vector<KeyPoint> keypoints_f1;
	detector->detect(imgGray1, keypoints_f1);
	Mat img_kp1;
	//drawKeypoints(imgGray1, keypoints_f1, img_kp1, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
	Ptr<SURF> extractor = SURF::create();
	Mat desc1;	
	extractor->compute(imgGray1, keypoints_f1, desc1);
	//BFMatcher matcher(NORM_L2);
	//vector<DMatch> matches;
	//matcher.match(desc1, Ball.getDesc(),matches);
	//Mat img_matches;
	//drawMatches(imgGray1, keypoints_f1, Ball.getimgGray(), Ball.getKP(), matches, img_matches);
	//imshow("test", img_matches);
	/*
	   FIN TRAITEMENT KEYPOINTS
	 */
	if(minVal<0.3)// && keypoints_f1.size()>=Ball.getKP().size())
	{
		rectangle(imgOriginal, target, Scalar::all(-1), 2, 8, 0);
		Ball.setCurrentTLD((float)(target.x+(target.width/2))/fSize.width*100, (float)(target.y+(target.height/2))/fSize.height*100, 0);
	}
	else
	{
		Ball.setFoundTLD(false);
	}
	return NULL;
}
Exemple #16
0
static bool matchTemplate_CCOEFF(InputArray _image, InputArray _templ, OutputArray _result)
{
    matchTemplate(_image, _templ, _result, CV_TM_CCORR);

    UMat image_sums, temp;
    integral(_image, temp);

    if (temp.depth() == CV_64F)
        temp.convertTo(image_sums, CV_32F);
    else
        image_sums = temp;

    int type = image_sums.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);

    ocl::Kernel k("matchTemplate_Prepared_CCOEFF", ocl::imgproc::match_template_oclsrc,
                  format("-D CCOEFF -D T=%s -D elem_type=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn));
    if (k.empty())
        return false;

    UMat templ = _templ.getUMat();
    Size size = _image.size(), tsize = templ.size();
    _result.create(size.height - templ.rows + 1, size.width - templ.cols + 1, CV_32F);
    UMat result = _result.getUMat();

    if (cn == 1)
    {
        float templ_sum = static_cast<float>(sum(_templ)[0]) / tsize.area();

        k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result),
                templ.rows, templ.cols, templ_sum);
    }
    else
    {
        Vec4f templ_sum = Vec4f::all(0);
        templ_sum = sum(templ) / tsize.area();

        if (cn == 2)
            k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols,
                   templ_sum[0], templ_sum[1]);
        else if (cn==3)
            k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols,
                   templ_sum[0], templ_sum[1], templ_sum[2]);
        else
            k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols,
                   templ_sum[0], templ_sum[1], templ_sum[2], templ_sum[3]);
    }

    size_t globalsize[2] = { result.cols, result.rows };
    return k.run(2, globalsize, NULL, false);
}
Exemple #17
0
/*
void Socket_Data(Copter cop, char* buf[])
{
	int buf_idx=0;
	char num =0x00;
	char flag=0x00;

	
	if(cop.number == 1)
	{
		buf_idx = 43;
		num = 0x01;
	}
	else if(cop.number == 2)
	{
		buf_idx = 21;
		num = 0x02;
	}
	if(cop.Flag)
		flag = 0x01;

	int Z_DATA = cop.Z_avr*10;

	(*buf)[buf_idx] = num;
	(*buf)[--buf_idx] = flag;
	(*buf)[--buf_idx] = 0xff & (cop.real_cx>>(8*3));
	(*buf)[--buf_idx] = 0xff & (cop.real_cx>>(8*2));
	(*buf)[--buf_idx] = 0xff & (cop.real_cx>>8);
	(*buf)[--buf_idx] = 0xff & (cop.real_cx);

	(*buf)[--buf_idx] = 0xff & (cop.real_cy>>(8*3));
	(*buf)[--buf_idx] = 0xff & (cop.real_cy>>(8*2));
	(*buf)[--buf_idx] = 0xff & (cop.real_cy>>8);
	(*buf)[--buf_idx] = 0xff & (cop.real_cy);

	(*buf)[--buf_idx] = 0xff & (cop.space_X>>(8*3));
	(*buf)[--buf_idx] = 0xff & (cop.space_X>>(8*2));
	(*buf)[--buf_idx] = 0xff & (cop.space_X>>8);
	(*buf)[--buf_idx] = 0xff & (cop.space_X);

	(*buf)[--buf_idx] = 0xff & (cop.space_Y>>(8*3));
	(*buf)[--buf_idx] = 0xff & (cop.space_Y>>(8*2));
	(*buf)[--buf_idx] = 0xff & (cop.space_Y>>8);
	(*buf)[--buf_idx] = 0xff & (cop.space_Y);

	(*buf)[--buf_idx] = 0xff & (Z_DATA>>(8*3));
	(*buf)[--buf_idx] = 0xff & (Z_DATA>>(8*2));
	(*buf)[--buf_idx] = 0xff & (Z_DATA>>8);
	(*buf)[--buf_idx] = 0xff & (Z_DATA);

	
	(*buf)[44] = 0xff;
}
*/
void Take_Copter_Init(Mat Cam, Mat Cam2, Mat Pic, Mat Pic2, Copter& cop)
{
    Mat Corr_1;
    Mat Corr_2;
    Mat Result;
    double min,max;
    Point Copter_point;
	
	matchTemplate(Cam,Pic,Corr_1,CV_TM_CCOEFF_NORMED);
	matchTemplate(Cam2,Pic2,Corr_2,CV_TM_CCOEFF_NORMED);
    Result = (0.5*Corr_1) + (0.5*Corr_2);

    minMaxLoc(Result,&min,&max,NULL,&Copter_point);
    cop.x = Copter_point.x-(TEMPLATE_WIDTH/3);
    cop.y = Copter_point.y-(TEMPLATE_HEIGHT/3);
    cop.width = TEMPLATE_WIDTH;
    cop.height = TEMPLATE_HEIGHT;

    if(cop.x<0) cop.x = 0;
    if(cop.y<0) cop.y = 0;
    if(1920-cop.x <=TEMPLATE_WIDTH){ cop.x = 1920-TEMPLATE_WIDTH-1; }
    if(1080-cop.y <=TEMPLATE_HEIGHT){ cop.y = 1080-TEMPLATE_HEIGHT-1; }
	cop.center_x = cop.x+(cop.width/2);
	cop.center_y = cop.y+(cop.height/2);
	cop.prev_cx[0] = cop.center_x;
	cop.prev_cy[0] = cop.center_y;
	for(int i=1; i<V_BUFFER_SIZE; i++)
	{
		cop.prev_cx[i] = cop.center_x;
		cop.prev_cy[i] = cop.center_y;
	}
    if(cop.number==1)
	cop.Copter_Layer = Cam_Image(Rect(cop.x , cop.y , cop.width , cop.height ));
	else if(cop.number==2)
	cop.Copter_Layer = Cam_Image(Rect(cop.x , cop.y , cop.width , cop.height));

}
Exemple #18
0
void PMTrackingAlgo::track(cv::Mat img){
    cv::Mat result;
    double minVal; double maxVal;
    cv::Point minLoc; cv::Point maxLoc;

    matchTemplate(img, m_tmpl, result, 5);

    minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());

    //printf("[ScaleOpt] Found maximum %f at (%i,%i) \n", maxVal, maxLoc.x, maxLoc.y);
    cv::Point center;
    center.x = maxLoc.x + m_size.width/2;
    center.y = maxLoc.y + m_size.height/2;
    m_coordinate = center;
}
Exemple #19
0
Mat Scraper::FindMatch(const Mat haystack, const Mat needle)
{
    Mat result;

    // Create the result matrix
    int result_cols =  haystack.cols - needle.cols + 1;
    int result_rows = haystack.rows - needle.rows + 1;
    result.create( result_cols, result_rows, CV_32FC1 );

    // Do the Matching and evaluate Threshold
    //  Method = 0: CV_TM_SQDIFF, 1: CV_TM_SQDIFF_NORMED 2: CV_TM_CCORR 3: CV_TM_CCORR_NORMED 4: CV_TM_CCOEFF 5: CV_TM_CCOEFF_NORMED
    matchTemplate(haystack, needle, result, CV_TM_CCORR_NORMED );
    threshold(result, result, 0.9, 1.0, CV_THRESH_TOZERO);

    return result;
}
float TemplateClassifier::getScore( cv::Mat roi, cv::Mat templ )
{
	float score = -1.0f;

	cv::Mat imgResize;
	cv::resize( roi, imgResize, cv::Size(templ.cols, templ.rows) );

	cv::Mat result;
	result.create( 1, 1, CV_32FC1 );

	matchTemplate( imgResize, templ, result, _method );

	if(_method == CV_TM_SQDIFF)
		score = (result.at<float>(0,0)<_thresh)? result.at<float>(0,0):-1.0f;
	else
		score = (result.at<float>(0,0)>_thresh)? result.at<float>(0,0):-1.0f;

	return score;
}
Exemple #21
0
void AppTemplate::calcScore(Rect b_inner,Rect b_outer)//*******************
{
	Mat cm;
	confidence_map.copyTo(cm);
	Rect rw=b_inner&Rect(0,0,cm.cols,cm.rows);
	Scalar fg=mean(cm(rw));//be careful with the range
	Mat mask=Mat::zeros(confidence_map.size(),CV_8UC1);
	rectangle(mask,b_outer,Scalar(1),-1);//mask out the whole GT
	cm.setTo(Scalar(0),mask);
	Mat matching_map;
	if (confidence_map.rows==0)
	{
		score=0;
		return;
	}
	matchTemplate(cm,Mat(b_inner.height,b_inner.width,CV_32FC1,Scalar(255)),matching_map,CV_TM_SQDIFF);
	Point minloc;
	minMaxLoc(matching_map,0,0,&minloc);
	Scalar bg=mean(cm(Rect(minloc.x,minloc.y,b_inner.width,b_inner.height)));
	score=(fg[0]-bg[0]);///fg[0];
}
int DetectRegion::detect(const Mat& frame)
{
	assert(m_regions.size() == m_templates.size());
	Mat result;
	Scalar score;

	int sub = 0, count = 0;
	while (sub < m_regions.size())
	{
		matchTemplate(frame(m_regions[sub]), 
				m_templates[sub], result, CV_TM_CCOEFF_NORMED);
		score = mean(result);

		if (score[0] < 0.9)
			++count;

		++sub;
	}

	return count;
}
/**
  * Logica que realiza el match_template normal.
  * Se llama dentro de normal(Mat)
  **/
void MatchTemplate::normal()
{
    /// Create the result matrix
    Mat result;
    int result_cols =  mOriginalImage.cols - mTemplateImg.cols + 1;
    int result_rows = mOriginalImage.rows - mTemplateImg.rows + 1;
    result.create( result_rows, result_cols, CV_32FC1 );

    /// @LuisAlonso, el tiempo del match template empieza aqui

    mBenchmark->startTimer();
    mBenchmark->startTickCPU();

    /// Realiza el match template
    matchTemplate( mOriginalImage, mTemplateImg, result, MATCH_METHOD );

    mBenchmark->markLapTimer();
    mBenchmark->markLapTickCPU();

    /// @LuisAlonso, y termina aqui

    normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

    /// Localizing the best match with minMaxLoc
    double minVal; double maxVal; Point minLoc; Point maxLoc; Point matchLoc;
    minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

    /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
    if( MATCH_METHOD  == CV_TM_SQDIFF || MATCH_METHOD == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
    else
    { matchLoc = maxLoc; }

    /// Show me what you got
    rectangle( result, matchLoc, Point( matchLoc.x + mTemplateImg.cols , matchLoc.y + mTemplateImg.rows ), Scalar::all(0), 2, 8, 0 );

    /// Notifica a quien este conectado
    emit onMatchTemplateFinished(result);
}
Exemple #24
0
void TemplateTracker::track(Mat &depthImage, Rect segRegion) {

	/*if(deathFlagShouldRemove) {

		return;
	}*/

	Mat img = depthImage;

	int result_cols =  img.cols - templ.cols + 1;
	int result_rows = img.rows - templ.rows + 1;

	Mat result;
	result.create( result_cols, result_rows, CV_32FC1 );

	matchTemplate(depthImage, templ, result, CV_TM_CCORR_NORMED);

	normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
	

	double minVal; double maxVal; Point minLoc; Point maxLoc;
	Point matchLoc;

	minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

	matchLoc = maxLoc;
	
	trackedRegion = Rect(matchLoc.x, matchLoc.y, templ.cols, templ.rows);

	// All the if/elses based on body type make me cry
	if(bodyType == HEAD) {
		reconciledHeads(segRegion, trackedRegion, depthImage);
	}
	else if(bodyType == CHEST) {
		
	}
	
}
void LKTracker::normCrossCorrelation(const Mat& img1, const Mat& img2, vector<Point2f>& points1, vector<Point2f>& points2)
{
	Mat rec0(10, 10, CV_8U);
	Mat rec1(10, 10, CV_8U);
	Mat res(1, 1, CV_32F);

	//double maxDis = 3.0f * sqrt(window_size.width*window_size.width + window_size.height*window_size.height); // 过滤距离过远的光流
	similarity.clear();
	for (int i = 0; i < points1.size(); i++) {
		if (status[i] == 1 /*&& norm(points1[i] - points2[i]) < maxDis*/) {
			getRectSubPix(img1, Size(10, 10), points1[i], rec0);
			getRectSubPix(img2, Size(10, 10), points2[i], rec1);
			matchTemplate(rec0, rec1, res, CV_TM_CCOEFF_NORMED);
			similarity.push_back( ((float *)(res.data))[0] );
		}
		else {
			similarity.push_back(0.0);
		}
	}
	rec0.release();
	rec1.release();
	res.release();
}
/**
 * @function MatchingMethod
 * @brief Trackbar callback
 */
Point TemplateMatching::MatchingMethod(int, void *)
{
    /// Source image to display
    Mat img_display;
    img.copyTo( img_display );

    /// Create the result matrix
    int result_cols =  img.cols - templ.cols + 1;
    int result_rows = img.rows - templ.rows + 1;

    result.create( result_rows, result_cols, CV_32FC1 );

    /// Do the Matching and Normalize
    matchTemplate( img, templ, result, match_method );
    normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

    /// Localizing the best match with minMaxLoc
    double minVal; double maxVal; Point minLoc; Point maxLoc;
    Point matchLoc;

    minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );


    /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
    if( match_method  == TM_SQDIFF || match_method == TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
    else
    { matchLoc = maxLoc; }

    /// Show me what you got

    //  rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
    targetResult = Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows );

    return targetResult;
}
Exemple #27
0
///Returns true if an im1 is contained in im2 or viceversa
bool crossCorr(cv::Mat im1, cv::Mat im2)
{
	//im1 roi from the previous frame
	//im2 roi fromcurrent frame
	if (im1.rows <= 0 || im1.cols <= 0 || im2.rows <= 0 || im2.cols <= 0)
		return false;

	cv::Mat result, larger_im, smaller_im;

	/// Create the result matrix
	int result_cols;
	int result_rows;

	//select largest image
	if (im2.cols > im1.cols)
	{
		larger_im = im2;
		smaller_im = im1;
	}
	else
	{
		larger_im = im1;
		smaller_im = im2;
	}
	//check rows to be also larger otherwise crop the smaller to remove extra rows
	if (larger_im.rows < smaller_im.rows)
	{
		//add rows to match sizes
		cv::Mat rows = cv::Mat::ones(smaller_im.rows - larger_im.rows, larger_im.cols, larger_im.type());
		larger_im.push_back(rows);
	}

	result_cols = larger_im.cols - smaller_im.cols + 1;
	result_rows = larger_im.rows - smaller_im.rows + 1;
	result.create(result_cols, result_rows, CV_32FC1);

	/// Do the Matching and Normalize
	matchTemplate(larger_im, smaller_im, result, CV_TM_CCORR_NORMED);
	//normalize(result, result, 0, 1, NORM_MINMAX, -1, cv::Mat());

	/// Localizing the best match with minMaxLoc
	double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
	cv::Point matchLoc;

	minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());

	matchLoc = maxLoc;

	/// Show me what you got
	cv::Mat scene = larger_im.clone();
	rectangle(scene, matchLoc, cv::Point(matchLoc.x + smaller_im.cols, matchLoc.y + smaller_im.rows), cv::Scalar(0, 0, 255), 2, 8, 0);
	//imshow(image_window, scene);
	//imshow(result_window, result);

	//if (maxVal>0.89 && minVal <0.3)
	bool ret;
	int thresWidth = (larger_im.cols)*.7;
	if ( (maxVal > 0.5) && (smaller_im.cols > thresWidth) )//good threshold and consistent size
	{

		//std::cout << "matched" << endl;
		ret = true;
	}
	else
	{
		//std::cout << "non matched" << endl;
		ret = false;
	}
	//cv::imshow("match1", scene);
	//cv::imshow("match2", smaller_im);

	return ret;
}
Exemple #28
0
void *image_show( void *)        /*analiza imagem*/
{
    Mat frameCopy;
    Mat frameAnalize;
    Mat result;
    mouseInfo.event=-1;
    sleep(1);
    timer timer_image_show;
    while(1)
    {

        timer_image_show.a();
        pthread_mutex_lock(&in_frame);
        frameCopy=frame;
        pthread_mutex_unlock(&in_frame);

        
        if(mouseInfo.x > 26 && mouseInfo.y >26 && mouseInfo.event==EVENT_LBUTTONDOWN)
        {
            Cerro;
            printf("Change! \n");
            Rect myDim(mouseInfo.x-25,mouseInfo.y-25, 50, 50);
            frameAnalize = frameCopy(myDim).clone();     
            frameAnalize.copyTo(frameAnalize);
        }
        else if(mouseInfo.event == -1)
        {
            Rect myDim(frameCopy.cols/2,frameCopy.rows/2, 50, 50);
            frameAnalize = frameCopy(myDim);     
            frameAnalize.copyTo(frameAnalize);
            mouseInfo.event=-2;
        }
        
        /// Create the result matrix
        int result_cols =  frameCopy.cols - frameAnalize.cols + 1;
        int result_rows = frameCopy.rows - frameAnalize.rows + 1;
        result.create( result_cols, result_rows, CV_32FC1 );

        /// Do the Matching and Normalize
        int match_method=1; //1-5
        matchTemplate( frameCopy, frameAnalize, result, match_method );
        normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

        /// Localizing the best match with minMaxLoc
        double minVal; double maxVal; Point minLoc; Point maxLoc;
        Point matchLoc;
        minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

        /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
        if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
            { matchLoc = minLoc; }
        else
            { matchLoc = maxLoc; }
        
        /// make retangles
        rectangle( frameCopy, matchLoc, Point( matchLoc.x + frameAnalize.cols , matchLoc.y + frameAnalize.rows ), Scalar::all(0), 2, 8, 0 );
        rectangle( result, matchLoc, Point( matchLoc.x + frameAnalize.cols , matchLoc.y + frameAnalize.rows ), Scalar::all(0), 2, 8, 0 );

        /// make a dif with the original and the matched
        Rect myDim2(matchLoc.x,matchLoc.y,50 , 50);
        Mat frameAnalizado = frameCopy(myDim2).clone(); 
        //Mat subt = frameAnalize - frameAnalizado;

        /// Make a simple text to debug
        char str[256];
        sprintf(str, "x:%d/y:%d", matchLoc.x+25, matchLoc.y+25);
        putText(frameCopy, str, cvPoint(30,30), FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);

        sprintf(str, "maxVal:%.8f/minVal:%.8f", maxVal, minVal);
        putText(frameCopy, str, cvPoint(30,60), FONT_HERSHEY_COMPLEX_SMALL, 0.6, cvScalar(200,200,250), 1, CV_AA);

        //draw lines
        //pthread_mutex_lock(&in_window);
        line(frameCopy, Point (0,matchLoc.y+25), Point (frameCopy.cols,matchLoc.y+25), cvScalar(200,200,250), 1, 8, 0);
        line(frameCopy, Point (matchLoc.x+25,0), Point (matchLoc.x+25,frameCopy.rows), cvScalar(200,200,250), 1, 8, 0);
        //line(frameCopy, Point (0,0), Point (frameCopy.cols,frameCopy.rows), cvScalar(200,200,250), 1, 8, 0);

        /// Show de imgs
        imshow("image_show",frameCopy);
        namedWindow("image_show", CV_WINDOW_NORMAL); 
        setMouseCallback("image_show", CallBackFunc, NULL);
        
        imshow("analize",frameAnalize);
        namedWindow("analize", CV_WINDOW_NORMAL);
        
        //imshow("result",result);
        //namedWindow("result", CV_WINDOW_NORMAL); 
        
        imshow("analizado",frameAnalizado);
        namedWindow("analizado", CV_WINDOW_NORMAL); waitKey(30);
        
        //imshow("sub",subt);
        //namedWindow("sub", CV_WINDOW_NORMAL); 
        Caviso;  printf("Fps do streaming: %.2f\n",1/timer_image_show.b()); //end_fps();
        Caviso;  printf("tempo de image_show: %f s \n",timer_image_show.b());
        waitKey(30);
        //pthread_mutex_unlock(&in_window);
        
    }
    Cerro; printf("Image_show Down !\n");
    return NULL;
}
void CAutomaticBreakingDeviceTABFallOffDetector::DetectError(vector<SErrorInfoArray>& errorInfoArray,
	vector<Mat>& resultImageArray, /*vector<PositionOfComponents>& positionOfComponents, */int statues /*= 0*/)
{
	//将车厢的方向统一
	flip(m_srcImageArray[2], m_srcImageArray[2], 1);
	flip(m_srcImageArray[3], m_srcImageArray[3], 1);
	flip(resultImageArray[m_interstedIndex[2]], resultImageArray[m_interstedIndex[2]], 1);
	flip(resultImageArray[m_interstedIndex[3]], resultImageArray[m_interstedIndex[3]], 1);



	int count = 0;								//找到的脱轨自动制动装置拉环的个数
	int flag[4] = {0,0,0,0};
	for (int i = 0; i <4; ++i)
	{
		Rect roiRect;
		roiRect.x = 0;
		roiRect.y = m_srcImageArray[i].rows/5;
		roiRect.width = m_srcImageArray[i].cols/4+60;
		roiRect.height = m_srcImageArray[i].rows/5*3;

		float maxMatchVal = -1.0;
		Point matchPoint;
		int templateIndex = 0;

		for (int j = 0; j != m_templateImageArray.size(); ++j)
		{
			Mat compareResult;																//匹配结果矩阵
			//定义查找移动杠杆的ROI
			Mat searchTruckLiveLever_ROI;

			if (!IsValidRectInMat(m_srcImageArray[i], roiRect))
			{
				continue;
			}

			searchTruckLiveLever_ROI = m_srcImageArray[i](roiRect);
			compareResult.create(searchTruckLiveLever_ROI.rows - m_templateImageArray[j].rows + 1, 
				searchTruckLiveLever_ROI.cols - m_templateImageArray[j].cols + 1, CV_32FC1);

			matchTemplate(searchTruckLiveLever_ROI, m_templateImageArray[j], compareResult, CV_TM_CCOEFF_NORMED);	//模板匹配

			double minVal,maxVal;															//矩阵中最小值,最大值
			Point minLoc;																	//最小值的坐标
			Point matchLoc;																	//最匹配值的坐标
			minMaxLoc(compareResult, &minVal, &maxVal, &minLoc, &matchLoc, cv::Mat());		//寻找最匹配的点
			if (maxVal > maxMatchVal)
			{
				maxMatchVal = maxVal;
				matchPoint.x = matchLoc.x + roiRect.x;
				matchPoint.y =roiRect.y+matchLoc.y;
				templateIndex = j;
			}
		}

		//如果最高匹配值大于0.6则视为匹配
		if (maxMatchVal >= 0.45)
		{
			++count;
			flag[i] = 1;
			if (statues == 1)
			{
				Mat ROI= m_srcImageArray[i](cv::Rect(matchPoint.x, matchPoint.y, m_templateImageArray[templateIndex].cols, m_templateImageArray[templateIndex].rows));	//抠出夹扣螺栓大概位置
				Mat ROICanny= m_srcImageArray[i](cv::Rect(matchPoint.x, matchPoint.y, m_templateImageArray[templateIndex].cols, m_templateImageArray[templateIndex].rows)).clone();
				Canny(ROICanny, ROICanny,20, 120);		
				vector<Vec4i> lines;		
				HoughLinesP(ROICanny,lines,1,CV_PI/180,10,30, 150);  
				std::vector<cv::Vec4i>::const_iterator it= lines.begin();
				if (lines.size()==0)
				{
				}
				else
				{
					double tanb,tanc,tanResult,tanResult2,tanResult3;
					tanc=0;
					tanb=0;

					while (it!=lines.end()) {       
						cv::Point pt1((*it)[0]+matchPoint.x,(*it)[1]+matchPoint.y);        
						cv::Point pt2((*it)[2]+matchPoint.x,(*it)[3]+matchPoint.y);
						double m_i=(*it)[0]-(*it)[2];
						double m_i2=abs(m_i);
						if(m_i2>tanc){
							tanc=m_i2;
							tanb=abs((*it)[1]-(*it)[3]);
						}     
						++it;   
					}
					tanResult=tanb/tanc;
					tanResult2 = atan(tanResult);
					tanResult3=tanResult2*180.0/3.141592654;
					if(tanResult3<=30){
					}
					else
					{
						SErrorInfoArray sei;
						sei.errorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_FALLOFF;
						sei.realErrorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_FALLOFF;
						sei.errorImageFile = m_srcImageFileArray[i];
						switch (i)
						{
						case 0:
							sei.leftPos = 0;
							sei.rightPos = 300;
							sei.topPos = 500;
							sei.bottomPos = 800;
							sei.confidence = 61;
							sei.errorImageIndex = m_interstedIndex[0];
							rectangle(resultImageArray[m_interstedIndex[0]], Point(0,500),Point(300,800),Scalar(0,0,255),2);
							break;
						case 1:
							sei.leftPos = 1100;
							sei.rightPos = 1399;
							sei.topPos = 500;
							sei.bottomPos = 900;
							sei.confidence = 67;
							sei.errorImageIndex = m_interstedIndex[1];
							rectangle(resultImageArray[m_interstedIndex[0]], Point(1100,500),Point(1399,900),Scalar(0,0,255),2);
							break;
						case 2:
							sei.leftPos = 1100;
							sei.rightPos = 1399;
							sei.topPos = 500;
							sei.bottomPos = 900;
							sei.confidence = 62;
							sei.errorImageIndex = m_interstedIndex[2];
							rectangle(resultImageArray[m_interstedIndex[0]], Point(0,500),Point(300,800),Scalar(0,0,255),2);
							break;
						case 3:
							sei.leftPos = 0;
							sei.rightPos = 300;
							sei.topPos = 500;
							sei.bottomPos = 800;
							sei.confidence = 63;
							sei.errorImageIndex = m_interstedIndex[3];
							rectangle(resultImageArray[m_interstedIndex[0]], Point(1100,500),Point(1399,900),Scalar(0,0,255),2);
							break;
						}
						errorInfoArray.push_back(sei);
						continue;
					}
				}
			}
		}
	}

	if (count < 2 && statues == 0)
	{
		if (flag[0] == 1 || flag[2] == 1)
		{
			if (flag[0] == 0)
			{

				SErrorInfoArray sei;
				sei.errorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.realErrorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.errorImageFile = m_srcImageFileArray[0];
				sei.leftPos = 0;
				sei.rightPos = 300;
				sei.topPos = 500;
				sei.bottomPos = 800;
				sei.confidence = 61;
				sei.errorImageIndex = m_interstedIndex[0];
				rectangle(resultImageArray[m_interstedIndex[0]], Point(0,500),Point(300,800),Scalar(0,0,255),2);
				sei.errorImageIndex = m_interstedIndex[0];
				errorInfoArray.push_back(sei);
			}
			if (flag[2] == 0)
			{

				SErrorInfoArray sei;
				sei.errorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.realErrorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.errorImageFile = m_srcImageFileArray[1];
				sei.leftPos = 1100;
				sei.rightPos = 1399;
				sei.topPos = 500;
				sei.bottomPos = 900;
				sei.errorImageIndex = m_interstedIndex[2];
				rectangle(resultImageArray[m_interstedIndex[0]], Point(0,500),Point(300,800),Scalar(0,0,255),2);
				sei.confidence = 67;
				sei.errorImageIndex = m_interstedIndex[1];
				errorInfoArray.push_back(sei);
			}
		}
		else
		{
			if (flag[1] == 0)
			{
				SErrorInfoArray sei;
				sei.errorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.realErrorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.errorImageFile = m_srcImageFileArray[2];
				sei.leftPos = 1100;
				sei.rightPos = 1399;
				sei.topPos = 500;
				sei.bottomPos = 900;
				sei.errorImageIndex = m_interstedIndex[1];
				rectangle(resultImageArray[m_interstedIndex[0]], Point(1100,500),Point(1399,900),Scalar(0,0,255),2);
				sei.confidence = 62;
				sei.errorImageIndex = m_interstedIndex[2];
				errorInfoArray.push_back(sei);
			}
			if (flag[3] == 0)
			{
				SErrorInfoArray sei;
				sei.errorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.realErrorMask |= DEMO_ERROR_DERAILMENT_AUTOMATIC_BREAKING_DEVICE_TAB_LOST;
				sei.errorImageFile = m_srcImageFileArray[3];
				sei.leftPos = 0;
				sei.rightPos = 300;
				sei.topPos = 500;
				sei.bottomPos = 800;
				sei.errorImageIndex = m_interstedIndex[3];
				rectangle(resultImageArray[m_interstedIndex[0]], Point(1100,500),Point(1399,900),Scalar(0,0,255),2);
				sei.confidence = 63;
				sei.errorImageIndex = m_interstedIndex[3];
				errorInfoArray.push_back(sei);
			}
		}
	}

	//将方向调回原来的方向
	flip(m_srcImageArray[2], m_srcImageArray[2], 1);
	flip(m_srcImageArray[3], m_srcImageArray[3], 1);
	flip(resultImageArray[m_interstedIndex[2]], resultImageArray[m_interstedIndex[2]], 1);
	flip(resultImageArray[m_interstedIndex[3]], resultImageArray[m_interstedIndex[3]], 1);
}
int main( int argc, char** argv )
{
	int status = EXIT_SUCCESS;

	float max_sqdiff = 0;
	float min_coeff = 999999999;
	float min_corr = 999999999;

	if( argc >= 3 )
	{
		filesDir = std::string(argv[1]);
		templ = cv::imread( std::string(argv[2]) );

		validExtensions.push_back("jpg");
		validExtensions.push_back("png");
		validExtensions.push_back("ppm");

		FilesHelper::getFilesInDirectory(filesDir, positives, validExtensions);

		std::vector< std::string >::iterator pit = positives.begin();
		for( ; pit != positives.end(); pit++ )
		{
			cv::Mat img = cv::imread( filesDir + "/" + *pit);
			cv::Mat imgResize;
			cv::resize( img, imgResize, cv::Size(templ.cols, templ.rows) );

			cv::Mat result;
			result.create( 1, 1, CV_32FC1 );

			matchTemplate( imgResize, templ, result, CV_TM_SQDIFF );
			max_sqdiff = (result.at<float>(0,0)>max_sqdiff)? result.at<float>(0,0):max_sqdiff;

			matchTemplate( imgResize, templ, result, CV_TM_CCORR );
			min_coeff = (result.at<float>(0,0)<min_coeff)? result.at<float>(0,0):min_coeff;

			matchTemplate( imgResize, templ, result, CV_TM_SQDIFF );
			min_corr = (result.at<float>(0,0)<min_corr)? result.at<float>(0,0):min_corr;
		}
		std::cout << "this dataset has values:" << std::endl;
		std::cout << "\tMax Square diff: " << max_sqdiff << "." << std::endl;
		std::cout << "\tMin ccoef: " << min_coeff << "." << std::endl;
		std::cout << "\tMin corr: " << min_corr << "." << std::endl;
	}
	else
	{
		std::cout <<
				"Usage:\n" << argv[0] <<
				" <path to positive images> <path to template image>\n";
		status = EXIT_FAILURE;
	}

	return status;
}