Some work related to my research ...

Monday, March 11, 2013

ROSCPP + OpenCV Program


Basically, here I am demonstrating how you can start writing your own program with ROS.
Create ROS package. Follow the tutorial link here. I am assuming that ros_workspace folder is added into ROS_PACKAGE_PATH
$ cd ~/ros_workspace
$ roscreate-pkg tbsimctrl std_msgs roscpp opencv2 sensor_msgs cv_bridge image_transport
You may not all the dependencies mentioned above.
$ cd tbsimctrl
$ rospack profile
$ rospack find tbsimctrl
/home/turtlebot/ros_workspace/tbsimctrl
Now create a file “camera_test.cpp” under src folder. The file contains the following piece of code:

#include
#include    //may not be needed
#include  //may not be needed
#include  //may not be needed
#include
#include
#include
#include
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
  ros::init(argc, argv, "captureimg");
  ros::NodeHandle n;

  CvCapture* capture = cvCaptureFromCAM(-1);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 320);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 240);
  IplImage *img = 0;
  img = cvQueryFrame(capture);
  int frameH = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
  int frameW = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  int fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
  cout << frameW << “\t” << frameH << “\t” << fps << endl;
  cvNamedWindow("Left", CV_WINDOW_AUTOSIZE);
  for(int n = 1; n= 30; n++)
  {
        img = cvQueryFrame(capture);
        cvShowImage("Left", img);  //show frames while capturing
        int c = cvWaitKey(20);               // wait 20 ms
        if(c == 27)
          break;
  }
  cvDestroyWindow( "Left" );
  cvReleaseCapture(&capture);
  return 0;
}

The above program captures video from a webcam. Save the file and insert the following statement inside the CMakeLists.txt file inside the tbsimctrl package folder. 
rosbuild_add_executable(${PROJECT_NAME} src/camera_test.cpp)
Now compile and build the package using rosmake
$ cmake .
$ rosmake
Make sure that the package is built with 0 failures. Once it is done, you can test the code as follows:
$ rosrun tbsimctrl tbsimctrl
You should be able to see the video from your webcam.



No comments: