Friday, January 2, 2015

How to use Support Vector Machine classifier in OpenCV for Linearly Separable Data sets.

In this tutorial I’m going to illustrate very basic and simple coding example targeting beginners to use Support Vector Machine (SVM) Implementation in OpenCV for Linearly Separable Data sets. I’m not going to explain the complex mathematical background of finding the optimal hyperplane. However in the first section of the post I’m going to give a simple introduction about support vector machines. 

When we consider classification and machine learning methods SVM is one of simple and easy to use classification method. Regarding image processing there are number of uses of SVM. Image classification and hand written character recognition are some uses of SVM. SVM can be easily used to classify feature vectors extracted from images. 

SVM is a supervised learning method. It defines separating hyperplanes between labeled data sets. These hyper planes can be used to categorize new data set which we don’t know the class label. 

To understand the problem easily instead of hyperplanes and vectors in a high dimensional space I used lines and points in the Cartesian plane (See the below figure).
Here the problem is to select a one from all possible lines which can be used to separate two classes, After defining such hyperplane we can categories new sample data to a class using that separating hyperplane, but it is difficult to define an optimal hyperplane. Based on a criterion we can estimate the worth of the lines. The operation of the SVM algorithm is based on finding the hyperplane that gives the optimal separating hyperplane (largest minimum distance to the training examples). 

Support vectors are the elements of the training set that would change the position of the dividing hyperplane if removed. Support vectors are the critical elements of the training set.


In this section I’m going to illustrate how we can use the SVM implementation in OpenCV to classify very simple data set. The SVM implementation in OpenCV is based on LibSVM.

In this example, to train the SVM I used 10 points (x and y coordinates lying on a Cartesian plane). I separate these points in to two classes named as 0 and 1 (See following table).


 
Table 1

To train the SVM we have to pass a N * M Mat of features (N rows, M columns) and a Nx1 Mat of class-labels

float trainingData[10][2] = { { 100, 10 }, { 150, 10 }, { 600, 200 }, { 600, 10}, { 10, 100 }, { 455, 10 }, { 345, 255 }, { 10, 501 }, { 401, 255 }, { 30, 150 } };

Here I create 10 * 2 data set as the feature space.

float labels[10] = { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0 };

Here I create 10 * 1 data set as class labels. These class labels are mapped with the set of features as shown in Table 1.

SVM training function only accepts data as Mat objects so we need to create Mat objects from arrays defined above. Then after completing the training process we can use the trained SVM to classify given coordinates in to a class.

Following code can be used to train and predict using SVM. I have added comments to easily understand the code.

#include <opencv\cv.h>
#include <opencv\highgui.h>
#include "opencv2/ml/ml.hpp"

void main(){
 float labels[10] = { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0 };
 cv::Mat lablesMat(10, 1, CV_32FC1, labels);

 float trainingData[10][2] = { { 100, 10 }, { 150, 10 }, { 600, 200 }, { 600, 10 }, { 10, 100 }, { 455, 10 }, { 345, 255 }, { 10, 501 }, { 401, 255 }, { 30, 150 } };

 cv::Mat trainDataMat(10, 2, CV_32FC1, trainingData);

 //Define parameters for SVM
 CvSVMParams params;
 //SVM type is defined as n-class classification n>=2, allows imperfect separation of classes
 params.svm_type = CvSVM::C_SVC;
 // No mapping is done, linear discrimination (or regression) is done in the original feature space.
 params.kernel_type = CvSVM::LINEAR;
 //Define the termination criterion for SVM algorithm.
 //Here stop the algorithm after the achieved algorithm-dependent accuracy becomes lower than epsilon
 //or run for maximum 100 iterations
 params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);

 CvSVM svm;
 //Call train function
 svm.train(trainDataMat, lablesMat, cv::Mat(), cv::Mat(), params);

 //Create test features
 float testData[2] = { 150, 15 };

 cv::Mat testDataMat(2, 1, CV_32FC1, testData);

 //Predict the class labele for test data sample
 float predictLable = svm.predict(testDataMat);

 std::cout << "Predicted label :" << predictLable << "\n";

 system("PAUSE");

}

In line 29 I pass data to predict the class label.

First I pass {150,15}. The class label was correctly predicted as 0. Following figure shows the output.



Then I changed the line no 29 to pass {400,200} as the  test data. Here is the output.


By doing some modifications to the above code as shown in the following code example, we can graphically represent the decision regions given by the SVM.

#include <opencv\cv.h>
#include <opencv\highgui.h>
#include "opencv2/ml/ml.hpp"

void main(){
 int width = 650, height = 650;
 //Create a mat object
 cv::Mat image = cv::Mat::zeros(height, width, CV_8UC3);

 // Set up training data
 float labels[10] = { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0 }; //
 cv::Mat labelsMat(10, 1, CV_32FC1, labels);
 float trainingData[10][2] = { { 100, 10 }, { 150, 10 }, { 600, 200 }, { 600, 10 }, { 10, 100 }, { 455, 10 }, { 345, 255 }, { 10, 501 }, { 401, 255 }, { 30, 150 } };//
 cv::Mat trainingDataMat(10, 2, CV_32FC1, trainingData);

 // Define up SVM's parameters
 CvSVMParams params;
 params.svm_type = CvSVM::C_SVC;
 params.kernel_type = CvSVM::LINEAR;
 params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);

 // Train the SVM
 CvSVM SVM;
 SVM.train(trainingDataMat, labelsMat, cv::Mat(), cv::Mat(), params);

 cv::Vec3b green(0, 255, 0), blue(255, 0, 0);
 // Show the decision regions given by the SVM
 for (int i = 0; i < image.rows; ++i)
 for (int j = 0; j < image.cols; ++j)
 {
  cv::Mat sampleMat = (cv::Mat_<float>(1, 2) << j, i);
  float response = SVM.predict(sampleMat);

  if (response == 1)
   image.at<cv::Vec3b>(i, j) = green;
  else if (response == 0)
   image.at<cv::Vec3b>(i, j) = blue;

 }

 // Show the training data
 int thickness = -1;
 int lineType = 8;
 circle(image, cv::Point(100, 10), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(150, 10), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(600, 200), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(600, 10), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(10, 100), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(455, 10), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(345, 255), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(10, 501), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(401, 255), 5, cv::Scalar(255, 255, 255), thickness, lineType);
 circle(image, cv::Point(30, 150), 5, cv::Scalar(255, 255, 255), thickness, lineType);

 //Show the test data
 circle(image, cv::Point(400, 200), 5, cv::Scalar(0, 0, 255), thickness, lineType);

 imwrite("result.png", image);        // save the image

 imshow("SVM Simple Example", image); // show it to the user
 cv::waitKey(0);

}

The following image shows the output of the code.


White dots shows the points of training data set. The red dot shows the point belongs to the test data which is {400,200}.

You can download the VisualStudio project from here. I have used OpenCV 2.4.9.

(To create the above code samples I used example codes provided in the link 1.)
References:
1. http://docs.opencv.org/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.html
2. http://docs.opencv.org/modules/ml/doc/support_vector_machines.html#cvsvmparams
3. http://web.mit.edu/6.034/wwwbob/svm-notes-long-08.pdf

Sunday, August 24, 2014

How to find the Greatest common divisor of an integer array in java

In this post I'm going to illustrate very simple algorithm to find the Greatest Common Divisor (GCD)  of set of integers (an array) using java.

  • In this algorithm we first find the smallest integer in the int array. 
  • Then we get the modulus for each element in the numbers of the array by dividing smallest integer and add all those modulus together. 
  • After processing each element in the array we check if the total of modulus is equals to 0.  If it is equal to 0 then the GCD is  current smallest value if that total is not equals 0 we deduct 1 from the previous smallest value and do the same computation. 
  • The algorithm will continue with  the same operations until total of modulus becomes 0 or until smallest integer is 2.
  • If there is any GCD, algorithm will return it or otherwise it will return -1.

See the following implementation of the algorithm.


public class GCD {

    public static int findGcd(int... numbers) {

        //Find the smallest integer in the number list
        
        int smallest = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < smallest) {
                smallest = numbers[i];
            }
        }

        //Find the GCD
        while (smallest > 1) {
            
            int counter = 0;
            int modTot = 0;
            
            while (counter < numbers.length) {

                modTot += numbers[counter] % smallest;
                counter++;

            }

            if (modTot == 0) {
                //Return the gcd if any
                return smallest;
            }

            //System.out.print(" "+ smallest);
            smallest--;

        }
        //return -1 if there is no gcd
        return -1;
    }

    public static void main(String[] x) {
        System.out.println("The GCD of 15 18 42 108 : "+GCD.findGcd(new int[]{15, 18, 42,108}));
    }
}

Here is the output for 15, 18, 42 and 108


Here is the output for 3,7 and 12



Sunday, June 15, 2014

Android TCP/IP client-server socket program (part two)

This is the second part of the post. In this part I will describe the implementation of the TCP/IP Android client program. I tested these two programs by connecting two Android devices over a Wi-Fi network. The deice which host the Wi-Fi hotspot has the server program. Then I connected another Android device which has the client program to that Wi-Fi hotspot. If you want to create the server program first check this post.
Client program has one Activity and one layout. You can download the complete client program from here.

Demo of the client application.
Here is the code for client main activity : 

package com.codeoncloud.androidclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
 private TextView tvServerMessage;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  tvServerMessage = (TextView) findViewById(R.id.textViewServerMessage);
  //Create an instance of AsyncTask
  ClientAsyncTask clientAST = new ClientAsyncTask();
  //Pass the server ip, port and client message to the AsyncTask
  clientAST.execute(new String[] { "192.168.1.1", "8080","Hello from client" });
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();
  if (id == R.id.action_settings) {
   return true;
  }
  return super.onOptionsItemSelected(item);
 }
/**
 * AsyncTask which handles the communication with the server 
 */
 class ClientAsyncTask extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
   String result = null;
   try {
    //Create a client socket and define internet address and the port of the server
    Socket socket = new Socket(params[0],
      Integer.parseInt(params[1]));
    //Get the input stream of the client socket
    InputStream is = socket.getInputStream();
    //Get the output stream of the client socket
    PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
    //Write data to the output stream of the client socket
    out.println(params[2]); 
    //Buffer the data coming from the input stream
    BufferedReader br = new BufferedReader(
      new InputStreamReader(is));
    //Read data in the input buffer
    result = br.readLine();
    //Close the client socket
    socket.close();
   } catch (NumberFormatException e) {
    e.printStackTrace();
   } catch (UnknownHostException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   return result;
  }
  @Override
  protected void onPostExecute(String s) {
   //Write server message to the text view
   tvServerMessage.setText(s);
  }
 }
}

This activity will involve in three main functions.
1.    Make a request to connect to the server.
2.    Read the input data stream coming from the server.
3.    Send data to the server.

Unlike the server program in the client program all these three tasks will be done by one AsyncTask, here named as ClientAsyncTask. An instance of the AsyncTask will be created and execution of the AsyncTask will be started in the main UI thread of the program [line 26, 28]. The internet address, the port number of and the client message pass as String parameters to the AsyncTask [line 28]. Check with your server application and change the ip address and port.

1.Make a request to connect to the server.
In the AsyncTask first client socket will be created by giving the server ip and port [line 53]. This will make a reaquest to the given server program over the Wi-Fi network since here I connected two devices using Wi-Fi hotspot.

2.Read the input data stream coming from the server.
Input stream of the client socket will be captured [line 57]. Data coming as the stream will be store in a buffer [line 63]. Data in the incoming buffer will be read line by line [line 66] and return the resulting string [line 76].

3.Send data to the server.
This is done using a Printwriter object. First data output stream of the client socket will be captured in to a Printwriter object [line 59]. Then the client message will write in to the print writer [line 61].

After completing client communication the client socket will be closed [line 68]. Then onPostExecute method of the AsyncTask will be executed and the server message will be write in to the text view [line 81].

Here is the code for main activity layout  :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.codeoncloud.androidclient.MainActivity"
    tools:ignore="MergeRootFrame" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="25dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textViewsrvrMsg"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="Server msg"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textViewServerMessage"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

</FrameLayout>

To perform network related functions we have to grant few permissions from Manifest file.
i.e.
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
The manifest file after adding all the permissions.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codeoncloud.androidclient"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.codeoncloud.androidclient.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have tested the server and client program on two Android devices connected via a Wi-Fi network. When you are testing first run the server application and then run the client application.These two applications has only the essential functionalists to complete a TCP/IP client server communication using plain java sockets. You can add your own functions to improve this program.

Happy coding  :)