Object Tracking Using OpenCV

In continuation of the previous 2 posts, I managed to implement a program to detect and track a blue object in a video file. The current code only detects one object. If you put two objects of blue colour in front of the camera it clubs them together and treats them as a single object. This is not a problem for my project since all the objects in my project are of different colours. The one major improvement from the previous code is the conversion for colour space into HSV for thresholding. The detected object is bounded with a rectangle of minimum area enclosing the detected blue pixels.

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>


#include <iostream>

using namespace cv;
using namespace std;

int main(int, char**)
{
  Size dim;
  VideoCapture cap(1); 
  if(!cap.isOpened())  
    return -1;

  Mat result;
  Mat temp;
    
  namedWindow("frame",CV_WINDOW_AUTOSIZE);
  for(;;){
    Mat frame;
    cap >> frame; // get a new frame from camera
    result=frame.clone();
    dim=frame.size();

    cvtColor(frame,temp,CV_BGR2HSV);
    inRange(temp,Scalar(70,100,100),Scalar(130,255,255),result);

    vector<Point> points;
    Mat_<uchar>::iterator it = result.begin<uchar>();
    Mat_<uchar>::iterator end = result.end<uchar>();
    for (; it != end; ++it)
      if (*it)
	points.push_back(it.pos());

    RotatedRect box = cv::minAreaRect(cv::Mat(points));

    double angle = box.angle;
    if (angle < -45.)
      angle += 90.;
      
    cv::Point2f vertices[4];
    box.points(vertices);
    for(int i = 0; i < 4; ++i)
      cv::line(frame, vertices[i], vertices[(i + 1) % 4], cv::Scalar(255, 0, 0), 1, CV_AA);
    
    imwrite("result.jpg",result);		
    imwrite("resutl_hsv.jpg",temp);
    imwrite("input.jpg",frame);
    imshow("frame",frame);
    if(waitKey(30) >= 0) break;
    }
  return 0;
}

Sample Results:
Image after color space conversion from RGB to HSV

Image after successful thresholding

Final Result

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s