Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
um have code for template matching in opencv with c++. now i want draw rectangle only when sample object infront of the screen, according to my code always appear rectangle in the screen and when sample image in the front of screen it will track by rectangle. sorry for the my bad english. thank you.
C++
#include <iostream>
#include "opencv2/opencv.hpp"
#include <sstream>
#include <windows.h>
#include <iostream>
#include <windows.h>

//#include <sstream>


using namespace cv;
using namespace std;

Point point1, point2; /* vertical points of the bounding box */
int drag = 0;
Rect rect; /* bounding box */
Mat img, roiImg; /* roiImg - the part of the image in the bounding box */
int select_flag = 0;
bool go_fast = false;

Mat mytemplate;
HANDLE hSerial = CreateFile(L"\\\\.\\COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
char outputChars[5] = {};
    DWORD btsIO;




///------- template matching -----------------------------------------------------------------------------------------------

Mat TplMatch( Mat &img, Mat &mytemplate )
{
  Mat result;

  matchTemplate( img, mytemplate, result, CV_TM_SQDIFF_NORMED );
  normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

  return result;
}


///------- Localizing the best match with minMaxLoc ------------------------------------------------------------------------

Point minmax( Mat &result )
{
  double minVal, maxVal;
  Point  minLoc, maxLoc, matchLoc;

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

  return matchLoc;
}


///------- tracking --------------------------------------------------------------------------------------------------------

void track()
{
roiImg=imread("stamp1.jpg");

            mytemplate=imread("stamp1.jpg");
    if (select_flag)
    {
        //roiImg.copyTo(mytemplate);
//         select_flag = false;
        go_fast = true;
    }

//     imshow( "mytemplate", mytemplate ); waitKey(0);

    Mat result  =  TplMatch( img, mytemplate );
    Point match =  minmax( result );

    rectangle( img, match, Point( match.x + mytemplate.cols , match.y + mytemplate.rows ), CV_RGB(255, 0, 255), 5 );
    char test[32];
    //char testy[32];
sprintf(test,"%dx\n%dy\n", (int)match.x, (int)match.y);
//  sprintf(testx,"%dx\n", (int)match.x);
    //WriteFile(hSerial, testx, strlen(testx), &btsIO, NULL);
//sprintf(testy,"%dy\n", (int)match.y);

        //WriteFile(hSerial, "kjl" ,4,&btsIO,NULL);
WriteFile(hSerial, test, strlen(test), &btsIO, NULL);



    std::cout << "match: " << match << endl;

    /// latest match is the new template
    Rect ROI = cv::Rect( match.x, match.y, mytemplate.cols, mytemplate.rows );
   /* roiImg = img( ROI );
    roiImg.copyTo(mytemplate);
    imshow( "roiImg", roiImg ); //waitKey(0);*/
}


///------- MouseCallback function ------------------------------------------------------------------------------------------

void mouseHandler(int event, int x, int y, int flags, void *param)
{
    if (event == CV_EVENT_LBUTTONDOWN && !drag)
    {
        /// left button clicked. ROI selection begins
        point1 = Point(x, y);
        drag = 1;
    }

    if (event == CV_EVENT_MOUSEMOVE && drag)
    {
        /// mouse dragged. ROI being selected
        Mat img1 = img.clone();
        point2 = Point(x, y);
        rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0);
        imshow("image", img1);
    }

    if (event == CV_EVENT_LBUTTONUP && drag)
    {
        point2 = Point(x, y);
        rect = Rect(point1.x, point1.y, x - point1.x, y - point1.y);
        drag = 0;
        roiImg = img(rect);
        roiImg.copyTo(mytemplate);
        roiImg=imread("stamp1.jpg");
  imshow("MOUSE roiImg", roiImg); waitKey(0);
    }

    if (event == CV_EVENT_LBUTTONUP)
    {
        /// ROI selected
        select_flag = 1;
        drag = 0;
    }

}



///------- Main() ----------------------------------------------------------------------------------------------------------

int main()
{


if (hSerial !=INVALID_HANDLE_VALUE)
    {
        printf("Port opened! \n");

        DCB dcbSerialParams;
        GetCommState(hSerial,&dcbSerialParams);

        dcbSerialParams.BaudRate = CBR_9600;
        dcbSerialParams.ByteSize = 8;
        dcbSerialParams.Parity = NOPARITY;
        dcbSerialParams.StopBits = ONESTOPBIT;

        SetCommState(hSerial, &dcbSerialParams);
    }
    else
    {
        if (GetLastError() == ERROR_FILE_NOT_FOUND)
        {
            printf("Serial port doesn't exist! \n");
        }

        printf("Error while setting up serial port! \n");
    }



    int k;

///open webcam
    VideoCapture cap(0);
    if (!cap.isOpened())
      return 1;

    ///open video file
   // VideoCapture cap;
    //cap.open( "Megamind.avi" );
    if ( !cap.isOpened() )
    {   cout << "Unable to open video file" << endl;    return -1;    }
  /*  /// Set video to 320x240
     cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);
     cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);*/

    cap >> img;

    //5GaussianBlur( img, img, Size(7,7), 3.0 );
    imshow( "image", img );



    while (1)
    {

        cap >> img;
        if ( img.empty() )
            break;

    // Flip the frame horizontally and add blur
cv::flip( img, img, 1 );
GaussianBlur( img, img, Size(7,7), 6.0 );

        if ( rect.width == 0 && rect.height == 0 )

         cvSetMouseCallback( "image", mouseHandler, NULL );
        // cout"AS";

        else
            track();

        imshow("image", img);
//  waitKey(100);   k = waitKey(75);
    k = waitKey(go_fast ? 30 : 10000);
        if (k == 27)
            break;
    }
      CloseHandle(hSerial);

    return 0;
}
Posted
Updated 12-Jun-15 5:39am
v2
Comments
Sergey Alexandrovich Kryukov 10-Jun-15 15:09pm    
Sorry, this is not C++ code; it won't compile. Did you notice that it starts with
#include
#include
#include
?

I do understand that this is merely the artifact of HTML markup, but who will fix it? Note there is the item "encode" in menu; it will do the trick; and sandwich it in the <pre lang="c++"> block
Stefan_Lang 15-Jun-15 4:23am    
First, there is no way anyone will understand what you're doing if you don't specify, exactly, what you mean by 'template', and what, by your definition, is considered a 'match'. Hint: in C++ template has a very specific meaning - obviously you mean something entirely different! this is confusing for anyone willing to offer advice, like me.

Second, there's a lot of code with no explanations. The few comments in your code are trivially obsolete. What's worse, your using statements make it impossible to spot where you are using library functions just from looking at the code.

Third, some of your code is free-floating, not within a named function. What is that code supposed to be? when should it be executed? Is there a function header missing?

Fourth, you are excused for your english, but since you already realize this problem, please be much more verbose in the description of your problem. Describe it three times in three different ways if you must I do not really understand your problem from your current description.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900