Wednesday, April 27, 2011

Adaboost and SVM

The following is an interesting study on application of Adaptive Boosting with Support Vector Machine based classifier.


Authors claim better performance on imbalanced data-sets (ranging from 150:500 to 30: 500) when compared to regular SVM based approach. It performs better than Adaboost used with classifiers such as decision trees, neural networks. 

Sunday, April 24, 2011

JQuery Servlet Ajax application

In this post, I am demonstrating a simple ajax application using jquery and java servlets.


My other JQuery posts will be listed here.

In this Sample Project, I am trying to suggest the names of the countries starting with A.

So, if we type more than two letters, than it suggests the names of the countries.

The following is the screenshot for the above application.



First we define a html file as follows:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Example</title>
    </head>
    <body>
        <center>
            <h3>Ajax Example using JQuery and Servlets</h3>
        </center>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                alert("Thanks for visiting!");
                $(".name").keyup(function(){
                    $country = $("#name").val();
                    if ($country.length > 1) {
                        $.ajax({
                            url: 'SampleServlet',
                            type: "POST",
                            data: {country:$country },
                            error: function(){
                                alert("Data Error");
                            },
                            success: function (data){
                                $("#flag").html("Country Suggestion: " + data) ;
                            }
                        });
                    }
                });
            });
        </script>
        <form id="sampleform" >
            <center>
                Enter Country starting with A:  
                <input id="name" class="name" type="text" >                                                    
                 <br/><br/>
                <div id="flag"> </div>
                <br/><br/><br/>
                Type Atleast Two Letters *
            </center>
        </form>
    </body>
</html>



The above program needs "jquery-1.5.1.js" file which is a JQuery library.

Save this file as .js file. This library should be placed in the same location where the jsp page is present.

This jsp program is calling SampleServlet Program as follows:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sriram
 */
public class SampleServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SampleServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SampleServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the
            + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("country") ;
        System.out.println(name);
        String result = this.countryList(name) ;
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println(result);
    }

    public String countryList(String name) {
        String country[] = new String[5] ;
        country[0] = "America" ;
        country[1] = "Australia" ;
        country[2] = "Argentina" ;
        country[3] = "Africa" ;
        country[4] = "Antartica" ;

        int flag = name.length() ;
        for (int i = 0 ; i < country.length ; i++) {
            if (country[i].substring(0, flag).equalsIgnoreCase(name)) {
                return country[i] ;
            }
        }
        return "Country Not Available in List!!" ;
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


The web.xml configuration for the SampleServlet program is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.
com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>SampleServlet</servlet-name>
        <servlet-class>SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SampleServlet</servlet-name>
        <url-pattern>/SampleServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


The jsp program atleast two let as parameter and sends it to POST method in SimpleServlet using ajax. There is a callback function which displays the output in an alert box and ultimatly in the jsp page.


There Source code is given as follows. It consists of a war file. Place this war file in the webapps folder of your server and paste http://localhost:8080/Sample/Sample.jsp in the url of the browser.

Saturday, April 23, 2011

Simple JQuery-Servlet Application

In this post, I am demonstrating a simple ajax application using jquery and java servlets.



Name the project as Sample.The jsp program here calls the GET method.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Example</title>
    </head>
    <body>
        <center>
            <h3>Getter Example using Servlets</h3>
        </center>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                alert("Thanks for visiting!");
                $(".Submit").click(function(){
                    $name=$("#name").val();
                    alert($name) ;
                    $.get("SampleServlet", {name:$name}, function(data) {
                        alert(data) ;
                        $("#flag").html(data) ;
                    });
                });
            });
        </script>
        <form id="sampleform" method="POST">
            <center>
                Enter your Name:  <input id="name" class="name" type="text">  <br/><br/>
                <input class="Submit" name="Submit" type="button" value="Submit" id="Submit"> 
            </center>
        </form>
        <div id="flag"> </div>
    </body>
</html>

** The above program needs "jquery-1.5.1.js" file which is a JQuery library.
Save this file as .js file. This library should be placed in the same location where the jsp page is present.

This jsp program is calling SampleServlet Program as follows:
                                           

                                             
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sriram
 */
public class SampleServlet extends HttpServlet {
   

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("name") ;
        System.out.println(name);
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Hello " + name);
        }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


The web.xml configuration for the SampleServlet program is as follows:
                                             

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>SampleServlet</servlet-name>
        <servlet-class>SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SampleServlet</servlet-name>
        <url-pattern>/SampleServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
The jsp program takes a name as parameter and sends it to GET method in SimpleServlet using ajax. There is a callback function which displays the output in an alert box and ultimatly in the jsp page.


There Source code is given as follows. It consists of a war file. Place this war file in the webapps folder of your server and paste http://localhost:8080/Sample/Sample.jsp in the url of the browser.

Download Source Code


Sunday, April 17, 2011

Python Vs Java Vs C++

This is a good doc I found on the web. Go through it if like to compare and contrast Python, Java and C++





DISCLAIMER: I don't own the document. Its publicly downloadable at:
Computer Language Tour
C++ / Java / Python

Thursday, April 14, 2011

Rsync Upload Download from Remote Machine


I recently discovered how simple it was to use rsync to upload or download files from remote machine form command line:

In order to upload your current folder contents to a remote server, you need to give the following command in Linux:

In order to download a folder to current folder, you need to give the following command:


a->archive
v->verbose
z->compress/zip while transfer


Writing it down for my future reference.




Tuesday, April 12, 2011

Check Image if valid

This is the python script i came up with to check if an image is valid/corrupt. It is quite useful if you want to check large number of downloaded images to be valid images or corrupt images. I just open an image using PIL python module. If its a valid image, it gets opened normally otherwise an exception is raised.

It gets the job done.

import glob
from PIL import Image
for filename in glob.glob("*.jpg"):
  
    try:
        im=Image.open(filename,'r')
        pass
    except:
        print "error in"+filename
        a=open('error_report1','a');
        a.write(filename)
        a.write("\n");


Monday, April 11, 2011

How Kinect works?

libsvm python example

In this post we see on how to install and use LIBSVM using python.

My other posts on libsvm will be posted here.

For intro to classification, click here.
The following is the easiest way to install libsvm python module in Ubuntu.

 $sudo apt-get install python-libsvm

In order to use it, use the following program sample:



This again reminds me on how simple python is!!!
Cheers!!

Sunday, April 10, 2011

count files in a directory

To list files in a directory to count the number of files we issue the following command in Linux:
$ls-l | wc -l


I was reminded of how cool Linux was, again!

Cheers

Saturday, April 9, 2011

blkproc in OpenCV

I've seen a couple of guys in many forums  of OpenCV (even the most popular Yahoo group) asking what is the equivalent of blkproc of Matlab in Opencv for which there were no replies. I'm not sure why people didn't care to answer that. For some there were replies which claimed that OpenCV doesn't have the  equivalent of blkproc.
Btw, My other programs in OpenCV will be posted here

I did some research (after which I felt a little foolish) on this. It turned out that there is a equivalent of blkproc of Matlab in Opencv. 

It is "cvSetImageROI", of course its that! (:p)

When you set an ROI for an image, it does basically the same what blkproc of Matlab does.

In Matlab we have the following, B = blkproc(A,[m n],fun) where fun is a inline function, m and n are block size in x and y directions and A is the Matrix we want to apply the function (bulk processing).

The OpenCV equivalent of the same would be:


while(condition)
{
cvSetImageROI( image, cvRect(point_x, point_y,  length_block_x, length_block_y) );
foo (image);
cvResetImageROI(image);
}


image is the IplImage we want to operate on, cvRect(x,y,length, width) defines the region of interest.
foo(image) would be the processing we would want to do on the block ROI we set.

Cheers!!

Normalize Image pixel values of 0 to 255 into values of 0 to 1 in OpenCV

I found this code it to be useful in Normalizing an gray image with values 0 to 255 into values of 0 to 1.

I found the following in a blog mehrez.kristou.org. I'm not sure why the blog is down right now or has been deleted. Had to get the following from google search cache. Thought of sharing with everyone.

If you are looking to energy Normalize an Image, click here.

I think Matlab function im2double does the same. This is likely to be the equivalent of im2double in OpenCV.

We cannot directly normalize the image as it takes only 8 bit unsigned integers as values. So we convert the scale and normalize it to values from 0 to 1 (from 0 to 255).


Friday, April 8, 2011

Change Array type in OpenCV

Most of the operations in OpenCV require the arrays to be of same type (CV_32FC1 or CV_8U or CV_8S, etc).

Btw, My other programs in OpenCV will be posted here

If you try to operate cvAdd or cvMul, etc on different array types, it would result in compilation error.

In order to change type, one must use
cvConvertScale(CvMat* src, CvMat* dst, double scale, double shift);


src-> source array (with you source type).
dst-> Destination array (with you destination type).


Then the operations. In Matlab it can be achieved quite simply like:
im=double(im);


But cvConvertScale seems to be the only way of changing the type of array in OpenCV

Thursday, April 7, 2011

Energy Normalize Image in OpenCV

Hi all. Its been a while since I've written a post. In this post we discuss on how to Energy Normalize an image with given mean and variance using OpenCV.

Btw, My other programs in OpenCV will be posted here

Energy in an Image is normalized when we divide the Image pixel values with the mean value of all the pixels in the image. This is energy normalization


NOTE:
Normalizing the entire image by the mean will not give proper results (all the values from 0-255 will become values <2 or <3 (or very low values). Operating them on a block the block basis is the KEY to do it.


Other form of normalization of image you may be looking for might be Mean Normalization. There is a Mean Normalization built-in method to do it in OpenCV.

Algorithm:


image=image/mean(image);

For Block By Block processing use cvSetImageROI in Opencv (blkproc in matlab)

The code is as follows. The following returns an IplImage with energy normalized: