Aplikasi Color Tracking OpenCV Pada Linux

Jangan lupa webcam-nya dipasang.

Package yang diperlukan adalah:

  • GCC 4.3 or later. In Ubuntu/Debian it can be installed with
sudo apt-get install build-essential
  • CMake 2.6 or higher
  • Subversion (SVN) client
  • GTK+ 2.x or higher, including headers (e.g. libgtk2.0-dev)
  • pkgconfig
  • libpng, zlib, libjpeg, libtiff, libjasper with development files (e.g. libjpeg-dev)
  • Python 2.3 or later with developer packages (e.g. python-dev)
  • SWIG 1.3.30 or later
  • libavcodec etc. from ffmpeg 0.4.9-pre1 or later + headers. (Video support with FFMPEG)
  • libdc1394 2.x + headers for video capturing from IEEE1394 cameras

Untuk menginstal package di atas bisa gunakan command console berikut.

sudo apt-get install build-essential
sudo apt-get install cmake
sudo apt-get install pkg-config
sudo apt-get install libpng12-0 libpng12-dev libpng++-dev libpng3
sudo apt-get install libpnglite-dev libpngwriter0-dev libpngwriter0c2
sudo apt-get install zlib1g-dbg zlib1g zlib1g-dev
sudo apt-get install libjasper-dev libjasper-runtime libjasper1
sudo apt-get install pngtools libtiff4-dev libtiff4 libtiffxx0c2 libtiff-tools
sudo apt-get install libjpeg8 libjpeg8-dev libjpeg8-dbg libjpeg-prog
sudo apt-get install ffmpeg libavcodec-dev libavcodec52 libavformat52 libavformat-dev
sudo apt-get install libgstreamer0.10-0-dbg libgstreamer0.10-0 libgstreamer0.10-dev
sudo apt-get install libxine1-ffmpeg libxine-dev libxine1-bin
sudo apt-get install libunicap2 libunicap2-dev
sudo apt-get install libdc1394-22-dev libdc1394-22 libdc1394-utils
sudo apt-get install swig
sudo apt-get install libv4l-0 libv4l-dev
sudo apt-get install python-numpy

Notes:

  • Not all those packages are necessarily needed. CMAKE will show you what you have installed.
  • For adding other features such as CUDA or a GUI (gtk+ 2.X or Qt), refer to the InstallGuide.
  • You might have to be logged in as root or use “sudo apt-get” instead of “apt-get” in all the commands mentioned above.
  • If you also want to use OpenCV from Python, add this:
    apt-get install libpython2.6 python-dev python2.6-dev  # Only if you want to use python
  • If your system has trouble with building “libjpeg.so”, you may need to build it manually, or try this:
    apt-get install libjpeg-progs libjpeg-dev
  • On Ubuntu 10.10 this apt-get was needed to recognize gstream-app and gstreamer-vid development headers
    apt-get install libgstreamer-plugins-base0.10-dev

referensi:

http://opencv.willowgarage.com/wiki/InstallGuide_Linux

http://opencv.willowgarage.com/wiki/InstallGuide%20:%20Debian

http://www.samontab.com/web/2011/06/installing-opencv-2-2-in-ubuntu-11-04/

______________________________________________________

Menginstall openCV

Untuk mengkompile kode yang dibuat diperlukan sebuah file yang bernama makefile. File makefile dapat dibuat sendiri atau dengan menggunakan bantuan aplikasi cmake yang sudah diinstall tadi.

Dengan cmake ini kita akan mengkompile dan menginstall openCV pada Linux. Download terlebih dahulu openCV -nya. Kemudian extract. Lalu ikuti langkah berikut.

Building OpenCV from source using CMake, using the command line

  1. Create a temporary directory, which we denote as <cmake_binary_dir>, where you want to put the generated Makefiles, project files as well the object files and output binaries.
  2. a. Enter the <cmake_binary_dir> and type
    •     cmake [<some optional parameters...>] <path to the OpenCV source directory>

      For example, if you downloaded the project to ~/opencv, you can do the following:

          cd ~/opencv # the directory containing INSTALL, CMakeLists.txt etc.
          mkdir release
          cd release
          cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON ..

That will generate makefiles for the Release configuration and will put them in ~/opencv/release directory. If you want tu use special features such as IPP or TBB, please refer to the InstallGuide

  1. a. Enter the created temporary directory (<cmake_binary_dir>) and run make utility. Then you can run “sudo make install” :
    •     make
          sudo make install
  2. If you did not want to run “make install”, refer to the InstallGuide

Setelah itu,

Now you have to configure OpenCV. First, open the opencv.conf file with the following code:

sudo gedit /etc/ld.so.conf.d/opencv.conf

Add the following line at the end of the file(it may be an empty file, that is ok) and then save it:

/usr/local/lib

Run the following code to configure the library:

sudo ldconfig

Now you have to open another file:

sudo gedit /etc/bash.bashrc

Add these two lines at the end of the file and save it:

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
export PKG_CONFIG_PATH

Finally, close the console and open a new one, restart the computer or logout and then login again. OpenCV will not work correctly until you do this.

There is a final step to configure Python with OpenCV. You need to copy the file cv.so into the correct place. You can do that by just executing the following command:

sudo cp /usr/local/lib/python2.7/site-packages/cv.so /usr/local/lib/python2.7/dist-packages/cv.so

referensi:

http://opencv.willowgarage.com/wiki/InstallGuide%20:%20Debian

http://www.samontab.com/web/2011/06/installing-opencv-2-2-in-ubuntu-11-04/

http://www.wikihow.com/Compile-a-C/C%2B%2B-Program-in-Ubuntu

______________________________________________________

KODE DAN APLIKASI

Contoh aplikasi C++ (file .cpp) color filtering http://mablresearch.rit.edu/wiki/index.php/Color_filtering_GUI_using_openCV

//##using C++ library##
#include <iostream>
using namespace std;
#include <stdlib.h>
//##using openCV library##
#include "cv.h"
#include "highgui.h"
#include "cxcore.h"
using namespace cv;
int main ( int argc, char **argv ) //--------------MAIN BODY---------------
{
VideoCapture webCam(0); // video source for webcam
webCam.set(CV_CAP_PROP_FRAME_WIDTH,640);
webCam.set(CV_CAP_PROP_FRAME_HEIGHT,480);
// slices matrcies that hold H,S and V
vector<Mat> slices;
// Cross Element for Erosion/Dilation
Mat cross = getStructuringElement(MORPH_CROSS, Size(5,5));
// create matrices to hold image
Mat camImage;		// raw image from webcam
Mat blurImage;		// blur image
Mat hsvImage;		// hsv image 
Mat hue;			// hue channel
Mat hue1;			// Hue upper bound
Mat hue2;			// Hue lower bound
Mat hue3;			// hue color filtering
Mat sat;			// Sat channel
Mat sat1;			// Sat upper bound
Mat sat2;			// sat lower bound
Mat sat3;			// sat color filtering
Mat val;			// Val channel
Mat val1;			// Val upper bound
Mat val2;			// Val lower bound
Mat val3;			// Val color filtering
Mat erd;			// Erosion Image
Mat dia;			// dialate image
Mat HnS;			// sat and hue channel
Mat HSV;			// HSV color fiter detected

// slide bar values
int HuethresH =0, 
HuethresL =0,
SatthresL =0,
SatthresH = 0,
ValthresL =0,
ValthresH = 0,
erosionCount = 1,
blurSize = 3;

// new window
cvNamedWindow("Color Tune",CV_WINDOW_NORMAL);

// make tune bar
cvCreateTrackbar( "Hue UpperT","Color Tune", &HuethresH, 255, 0 );
cvCreateTrackbar ("Hue LowerT","Color Tune", &HuethresL,255, 0);
cvCreateTrackbar( "Sat UpperT","Color Tune", &SatthresH, 255, 0 );
cvCreateTrackbar( "Sat LowerT","Color Tune", &SatthresL, 255, 0 );
cvCreateTrackbar( "Val UpperT","Color Tune", &ValthresH, 255, 0 );
cvCreateTrackbar( "Val LowerT","Color Tune", &ValthresL, 255, 0 );
cvCreateTrackbar ("EroTime","Color Tune", &erosionCount,15, 0);
cvCreateTrackbar ("BlurSize","Color Tune", &blurSize,15, 0);
// check blurSize bound
if(blurSize == 0)
blurSize = 1; //reset blurSize

// get and display webcam image
while(1)
{
 // get new image over and over from webcam
 webCam >> camImage;

 // check blurSize bound
if(blurSize == 0)
blurSize = 1; //reset blurSize

// blur image
//blur(camImage, blurImage, Size(11,11));
blur(camImage, blurImage, Size(blurSize,blurSize));

// conver raw image to hsv
cvtColor (camImage, hsvImage, CV_RGB2HSV);

// check blurSize bound
if(blurSize == 0)
blurSize = 1; //reset blurSize
blur(hsvImage, hsvImage, Size(blurSize,blurSize));
//blur(hsvImage, hsvImage, Size(5,5));

// split image to H,S and V images
split(hsvImage,slices);

slices[0].copyTo (hue); // get the hue channel
slices[1].copyTo(sat); // get the sat channel
slices[2].copyTo(val); // get the V channel
//apply threshold HUE upper/lower for color range
threshold (hue,hue1,HuethresL,255, CV_THRESH_BINARY); // get lower bound
threshold (hue, hue2,HuethresH,255, CV_THRESH_BINARY_INV); // get upper bound

hue3 = hue1 &hue2; // multiply 2 matrix to get the color range

// apply thresshold for Sat channel
threshold (sat,sat1,SatthresL,255, CV_THRESH_BINARY); // get lower bound
threshold (sat, sat2,SatthresH,255, CV_THRESH_BINARY_INV); // get upper bound
sat3 = sat1 & sat2; // multiply 2 matrix to get the color range

// apply thresshold for Val channel
threshold (val,val1,SatthresL,255, CV_THRESH_BINARY); // get lower bound
threshold (val, val2,SatthresH,255, CV_THRESH_BINARY_INV); // get upper bound
val3 = val1 & val2; // multiply 2 matrix to get the color range
// combine sat and hue filter together
HnS = sat3 & hue3;
// erode and dialation to reduce noise
erode(HnS,erd,cross,Point(-1,-1),erosionCount); // do erode
dilate(HnS,dia,cross,Point(-1,-1),erosionCount);// do dialate
// combine sat, val and hue filter together
HSV = sat3 & hue3 & val3;

// erode and dialation to reduce noise
erode(HSV,erd,cross,Point(-1,-1),erosionCount); // do erode
dilate(HSV,dia,cross,Point(-1,-1),erosionCount); // do dialate

// display image over and over
imshow("Webcam Orignal", camImage);
//imshow("Blur", blurImage);
//imshow("HSV Image", hsvImage);
//imshow("Hue channel",hue);
//imshow("Lower bound",hue1);
//imshow("Upper bound", hue2);
//imshow("L channel", Val);
//imshow("Color detected", hue3);
//imshow("Erosion",erd);
imshow("Hue color",hue3);
//imshow("Sat channel",sat);
imshow("Sat color",sat3);
//imshow("Val color",val3);
imshow("Sat and Hue",HnS);
imshow("HSV",HSV);
// Pause for highgui to process image painting
cvWaitKey(5);
}
//------CLEAN UP------- 
cvDestroyAllWindows();
}

_____________________________________________________

Aplikasi Color Tracking dengan library cvblob

Terlebih dahulu download budel file-nya dan extract. File dapat di diwnload di http://code.google.com/p/cvblob/. Setelah itu install dengan cmake

COMPILING AND INSTALLING

In Linux, if you have unpacked the source in $CVBLOB, enter in a console:

cd $CVBLOB
cmake .
make
sudo make install

lengkapnya bisa dilihat di readme.txt nya.

Jika sudah selesai maka bisa dicoba aplikasi samplenya.

#include <iostream>
#include <iomanip>

#if (defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) || defined(__WINDOWS__) || (defined(__APPLE__) & defined(__MACH__)))
#include <cv.h>
#include <highgui.h>
#else
#include <opencv/cv.h>
#include <opencv/highgui.h>
#endif

#include <cvblob.h>
using namespace cvb;

int main()
{
  CvTracks tracks;

  cvNamedWindow("red_object_tracking", CV_WINDOW_AUTOSIZE);

  CvCapture *capture = cvCaptureFromCAM(0);
  cvGrabFrame(capture);
  IplImage *img = cvRetrieveFrame(capture);

  CvSize imgSize = cvGetSize(img);

  IplImage *frame = cvCreateImage(imgSize, img->depth, img->nChannels);

  IplConvKernel* morphKernel = cvCreateStructuringElementEx(5, 5, 1, 1, CV_SHAPE_RECT, NULL);

  //unsigned int frameNumber = 0;
  unsigned int blobNumber = 0;

  bool quit = false;
  while (!quit&&cvGrabFrame(capture))
  {
    IplImage *img = cvRetrieveFrame(capture);

    cvConvertScale(img, frame, 1, 0);

    IplImage *segmentated = cvCreateImage(imgSize, 8, 1);

    // Detecting red pixels:
    // (This is very slow, use direct access better...)
    for (unsigned int j=0; j<imgSize.height; j++)
      for (unsigned int i=0; i<imgSize.width; i++)
      {
    CvScalar c = cvGet2D(frame, j, i);

    double b = ((double)c.val[0])/255.;
    double g = ((double)c.val[1])/255.;
    double r = ((double)c.val[2])/255.;
    unsigned char f = 255*((r>0.2+g)&&(r>0.2+b));

    cvSet2D(segmentated, j, i, CV_RGB(f, f, f));
      }

    cvMorphologyEx(segmentated, segmentated, NULL, morphKernel, CV_MOP_OPEN, 1);

    //cvShowImage("segmentated", segmentated);

    IplImage *labelImg = cvCreateImage(cvGetSize(frame), IPL_DEPTH_LABEL, 1);

    CvBlobs blobs;
    unsigned int result = cvLabel(segmentated, labelImg, blobs);
    cvFilterByArea(blobs, 500, 1000000);
    cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_BOUNDING_BOX);
    cvUpdateTracks(blobs, tracks, 200., 5);
    cvRenderTracks(tracks, frame, frame, CV_TRACK_RENDER_ID|CV_TRACK_RENDER_BOUNDING_BOX);

    cvShowImage("red_object_tracking", frame);

    /*std::stringstream filename;
    filename << "redobject_" << std::setw(5) << std::setfill('0') << frameNumber << ".png";
    cvSaveImage(filename.str().c_str(), frame);*/

    cvReleaseImage(&labelImg);
    cvReleaseImage(&segmentated);

    char k = cvWaitKey(10)&0xff;
    switch (k)
    {
      case 27:
      case 'q':
      case 'Q':
        quit = true;
        break;
      case 's':
      case 'S':
        for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it)
        {
          std::stringstream filename;
          filename << "redobject_blob_" << std::setw(5) << std::setfill('0') << blobNumber << ".png";
          cvSaveImageBlob(filename.str().c_str(), img, it->second);
          blobNumber++;

          std::cout << filename.str() << " saved!" << std::endl;
        }
        break;
    }

    cvReleaseBlobs(blobs);

    //frameNumber++;
  }

  cvReleaseStructuringElement(&morphKernel);
  cvReleaseImage(&frame);

  cvDestroyWindow("red_object_tracking");

  return 0;
}

Berikut adalah screenshot dari aplikasi di atas.

______________________________________________________

Daftar Pustaka

http://opencv.willowgarage.com/wiki/InstallGuide

http://opencv.willowgarage.com/wiki/InstallGuide%20%3A%20Debian

http://opencv.willowgarage.com/wiki/InstallGuide_Linux

http://www.samontab.com/web/2011/06/installing-opencv-2-2-in-ubuntu-11-04/

http://thebitbangtheory.wordpress.com/2011/10/23/how-to-install-opencv-2-3-1-in-ubuntu-11-10-oneiric-ocelot-with-python-support/

http://www.wikihow.com/Compile-a-C/C%2B%2B-Program-in-Ubuntu

http://ubuntuforums.org/showthread.php?t=1929574&page=2

http://stackoverflow.com/questions/4658764/opencv-unable-to-capture-image-from-isight-webcam

http://mablresearch.rit.edu/wiki/index.php/Color_filtering_GUI_using_openCV

http://mechomaniac.com/OpenCVBallTracking

https://sites.google.com/site/andrewssobral/pandaboard

http://is.gd/rVpk

http://code.google.com/p/cvblob/

2 Responses to Aplikasi Color Tracking OpenCV Pada Linux

  1. Hi , Apakah mas punya tutorial/sumber mengenai body detection menggunakan libraries marilena/opencv/others ?? terimkasih.

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