Saturday, October 22, 2011

Face Recognition using OpenCV2 and HaarCascade an Intro Part 2

After learning theory a bit in part1 now we lear how we can detect face in an image. Later we will extend this to detecting face from web cam and avi file. The code is very simple. We will load a image of a person in  IplImage structure. We also need to load haarcascader of frontal face will which enable us to detect the face in image. Opencv 2 provides many haar cascades of face, eye , nose etc which ever you want use. If you have installed openCV v2 in "C:/OpenCV2.0" ,you  find it in "C:/OpenCV2.0/data/haarcascades/"  Location. Now will need to call "cvHaarDetectObjects" OpenCV Function to detect the faces.

Here is the program -

#include "cv.h"
#include "highgui.h"

#include 
#include 


#ifdef _EiC
#define WIN32
#endif

static CvMemStorage* storage_face = 0; //Memory Storage to Sore faces

static CvHaarClassifierCascade* cascade_face = 0; 

void detect_and_draw( IplImage* image );

//Haar cascade - if your openc CV is installed at location C:/OpenCV2.0/
const char* cascade_name_face ="C:/OpenCV2.0/data/haarcascades/haarcascade_frontalface_alt.xml";

/////////////////////////////////////////////////////////////////////////////////

int main()
{
 IplImage  *image =0;
 image = cvLoadImage("viv6v.jpg",1);
 if(!image)
 {
         printf("Error loading image\n");
         return -1;
    }
   
    cascade_face = (CvHaarClassifierCascade*)cvLoad( cascade_name_face, 0, 0, 0 );
    
    if( !cascade_face )
    {
        printf("ERROR: Could not load classifier of face  cascade\n" );
        return -1;
    }

    storage_face = cvCreateMemStorage(0);
    cvNamedWindow( "result", 1 );
    
    // Call function to detect and Draw rectagle around face
    detect_and_draw( image);

    // Wait for key event. 
    cvWaitKey(0);
               
    // release resourses
    cvReleaseImage( &image );
 cvReleaseHaarClassifierCascade(&cascade_face );
 cvReleaseMemStorage( &storage_face);
    cvDestroyWindow("result");

    return 0;
}

////////////////////////////  Function To detect face //////////////////////////

void detect_and_draw( IplImage* img )
{

    double scale = 2;
    
    // create a gray image for the input image
    IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );
    // Scale down the ie. make it small. This will increase the detection speed
    IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),cvRound (img->height/scale)),8, 1 );
    
    int i;

    cvCvtColor( img, gray, CV_BGR2GRAY );
    
 cvResize( gray, small_img, CV_INTER_LINEAR );
    
 // Equalise contrast by eqalizing histogram of image
    cvEqualizeHist( small_img, small_img );
    
 cvClearMemStorage( storage_face);

    if( cascade_face )
    {
         // Detect object defined in Haar cascade. IN our case it is face
         CvSeq* faces = cvHaarDetectObjects( small_img, cascade_face, storage_face,
                                            1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,
                                            cvSize(30, 30) );
        
        // Draw a rectagle around all detected face 
        for( i = 0; i < (faces ? faces->total : 0); i++ )
        {
            CvRect r = *(CvRect*)cvGetSeqElem( faces, i );
   cvRectangle( img, cvPoint(r.x*scale,r.y*scale),cvPoint((r.x+r.width)*scale,(r.y+r.height)*scale),CV_RGB(255,0,0),3,8,0 );
  
  }
    }

    cvShowImage( "result", img );
    cvReleaseImage( &gray );
    cvReleaseImage( &small_img );
}

/////////////////////////////////////////////////////////////////////////////////

Output - Image with 1 Face -

Output - Image with multiple Faces -

Face Recognition using OpenCV2 and HaarCascade an Intro Part 1

In this series of tutorial we will learn how to detect human face. OpenCV library provides very effictive method of object detection including face detection using  Haar Cascades.
The function -
CvSeq* cvHaarDetectObjects(const CvArr* image,CvHaarClassifierCascade* cascade,CvMemStorage* storage,double scale factor=1.1,int min neighbors=3,int flags=0,CvSize min size=cvSize(0,0) );

can detect objects in input image by using HaarCascade structure. But before we jump directly to program we first need to understand about it a bit.

Many approaches have been proposed for detecting and recognizing faces. One of them is a color based approach to face detection. Indeed, color is a low-level cue that can be implemented in a computationally fast and effective way for locating objects. Among the advantages of using color is the computational efficiency and robustness against some geometric changes, when the scene is observed under a uniform illumination field.

However, the main limitation with the use of color lies in its sensitivity to illumination changes. To overcome the limitations of the color based approach, well-known face detection algorithm was proposed by Paul Viola and Michel J.Jhones in 2001 (Paul Viola and Michel J.Jhones “Rapid Object Detection Using Haar-like Features with Cascade of Boosted Classifiers”,IEEE CVPR 2001.)

 It uses Haar-like features and AdaBoost learning algorithm. The Haar-like features are extracted using the notion of integral image which allows very fast feature extraction at different scales, while AdaBoost is used to select the most prominent features among a large number of extracted features and construct a strong classifier from boosting a set of weak classifiers. The use of a cascade of classifiers made this approach one of the first real-time frontal-view face detection methods.
First, a classifier (namely a cascade of boosted classifiers working with haar-like features) is trained with a few hundreds of sample views of a particular object (i.e., a face or a car), called positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary images of the same size.


After a classifier is trained, it can be applied to a region of interest (of the same size as used during the training) in an input image. The classifier gives outputs as "1" if the region is likely to show the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can move the search window across the image and check every location using the classifier. The classifier is designed so that it can be easily "resized" in order to be able to find the objects of interest at different sizes, which is more efficient than resizing the image itself. So, to find an object of an unknown size in the image the scan procedure should be done several times at different scales.


The word "cascade" in the classifier name means that the resultant classifier consists of several simpler classifiers (stages) that are applied subsequently to a region of interest until at some stage the candidate is rejected or all the stages are passed. The word "boosted" means that the classifiers at every stage of the cascade are complex themselves and they are built out of basic classifiers using one of four different boosting techniques (weighted voting). Currently Discrete Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic classifers, and are calculated as described below. The current algorithm uses the following Haar-like features:


In part 2 we will write a C program to detect faces in an image.




Monday, August 1, 2011

Linking OpenCV 2 library in DEVC++

In my earlier post I have discussed how to link OpenCV 1.x with devC++. But with latest release of OpenCV version ie. OpenCV 2 or higher the earlier method will not work. This because, OpenCV have changed the directory structure. So lets learn how to link OpenCV 2 or higher library version in DevC++ IDE.
  • Goto Tools -> Compiler option 
  • In the pop up click on the plus button. This means you are adding new compiler setting. Add your fav. name eg - OpenCV2
  • Now you need to add compiler commands. Add -L"C:\OpenCV2.X\lib" -lcxcore2X0 -lcv2X0 -lcvaux2X0 -lhighgui2X0 -lml2X0  where X stands for version. Eg For open CV 2.0 add --L"C:\OpenCV2.0\lib" -lcxcore200 -lcv200 -lcvaux200 -lhighgui200 -lml200 . Similarly for OpenCV2.1 add -L"C:\OpenCV2.1\lib" -lcxcore210 -lcv210 -lcvaux210 -lhighgui210 -lml210
  • Add linker command similarly as above. -lcxcore2X0 -lcv2X0 -lcvaux2X0 -lhighgui2X0 -lml2X0 For open CV 2.0 add --L"C:\OpenCV2.0\lib" -lcxcore200 -lcv200 -lcvaux200 -lhighgui200 -lml200 . Similarly for OpenCV2.1 add -L"C:\OpenCV2.1\lib" -lcxcore210 -lcv210 -lcvaux210 -lhighgui210 -lml210
  • Goto Directories -> C includes. Add  C:\OpenCV2.0\include or C:\OpenCV2.1\include or C:\OpenCV2.2\include what ever version you have. I assume that you have installed openCV in C:\
  •  Goto Directories -> Library. Add  C:\OpenCV2.0\lib or C:\OpenCV2.1\libor C:\OpenCV2.2\lib what ever version you have.
  • Goto Directories -> Library. Add  C:\OpenCV2.0\bin or C:\OpenCV2.1\bin or C:\OpenCV2.2\bin what ever version you have. 
  • Now lets write a sample project for OpenCV. Open New project window  and select "Console Application".
  • Non in Project Option > Compiler chose "OpenCV2".
Thus you have successfully integrated OpenCV with DevC++.

Monday, June 21, 2010

Open CV Tutorial - Advanced operations on images ' Filter color in Image'

In this tutorial we will learn to filter images, and separate the color. For this I am using Opencv library. In my earlier posts I have discussed how to link opencv in devC++ (here) and in Visual Studio (here). Here I suppose that you know the basic of image processing and programing using opencv.

Here I have given a very basic algo to filter color which will not work with real life images, but will give a insight how to loop through each and every pixel of a image. In this code we will loop through each pixel, find the value of each component ( RGB) and for a specific condition we will determine that pixel is of which color. Here I have Used two functions

CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 )
->
void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
-> Note that cvSet*D function can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.

/******************** CODE TO FILTER COLORS ****************/
#include
#include
#include
#include

int main()
{
 // Decleare image variables
    IplImage* img=0; // original image
    IplImage* white;
    IplImage* blue;     
    IplImage* green;     
    IplImage* red;     
    
    
    //load original image
    img = cvLoadImage("test.jpg",-1);
    if(img==0)
    {
              printf(" ERORR IN LOADING IMAGE !!");
              exit(-1);
    }
    
    // get height and width for image
    int height=img->height;
 int width=img->width;
    
    // create four images
    white=cvCreateImage(cvSize(img->width,img->height),8,1);
    
    blue=cvCreateImage(cvSize(img->width,img->height),8,3);
    green=cvCreateImage(cvSize(img->width,img->height),8,3);
    red=cvCreateImage(cvSize(img->width,img->height),8,3);
    // Two scalar variable to store a pixle data.
    // wt -> white 
    CvScalar s,wt;
    wt.val[0]=255;
    
    // A very simple filter operation
    // This loops through each and every pixle of image and filter accordingly
    for(int i=0;i100 && s.val[1]>100 && s.val[2]>100) // filter white
                cvSet2D(white,i,j,wt);
      
        else if(s.val[0]>100 && s.val[1]<100 && s.val[2]<100) // filter blue
               cvSet2D(blue,i,j,s);
               
        else if(s.val[0]<100 && s.val[1]>100 && s.val[2]<100) // filter green
               cvSet2D(green,i,j,s);
        
        else if(s.val[0]<100 && s.val[1]<100 && s.val[2]>100) // filter red
               cvSet2D(red,i,j,s);
        
     
     }
     

    // Create windows and show them
 cvNamedWindow("img", 1);
 cvShowImage( "img", img );

    cvNamedWindow("white", 1);
 cvShowImage( "white", white );
 
    cvNamedWindow("blue", 1);
 cvShowImage( "blue",blue);
 
 cvNamedWindow("green", 1);
 cvShowImage( "green",green);
 
 cvNamedWindow("red", 1);
 cvShowImage( "red",red);

 // Wait for any to be pressed      
    cvWaitKey(0);

 // Detroy all created windows
 cvDestroyAllWindows();

 // Release the memory occupied by images
    cvReleaseImage( &img );
 cvReleaseImage( &white);
 cvReleaseImage( &blue);
 cvReleaseImage( &green);
 cvReleaseImage( &red);

 return 0;
}


OUTPUT:- 
 test.jpg :-                                       red image:-                       blue image :-                                            
        Green Image                                                                    White Image






ALSO READ :- 


Sunday, June 20, 2010

Open CV Tutorial - Basic operations for images Rotate and Scale

In this tutorials of OpenCV we will do some basic but interesting operartion on images. We rotate the image and scale it down.

For this we will use a matrix and rotate it. 

/************************************************/


#include "cv.h"
#include "highgui.h"
#include "math.h"
int main()
{
IplImage* src;
IplImage* dst;
int delta;
int angle;
src = cvLoadImage("apple.bmp", 1);
dst = cvCloneImage( src );
delta = 1; angle = 0;
cvNamedWindow( "src", 1 );
cvShowImage( "src", src );
for(;;)
{
float m[6];
double factor = (cos(angle*CV_PI/180.) + 1.1)*3;
CvMat M = cvMat( 2, 3, CV_32F, m );
int w = src->width;
int h = src->height;
m[0] = (float)(factor*cos(-angle*2*CV_PI/180.));
m[1] = (float)(factor*sin(-angle*2*CV_PI/180.));
m[2] = w*0.5f;
m[3] = -m[1];
m[4] = m[0];
m[5] = h*0.5f;
cvGetQuadrangleSubPix( src, dst, &M, 1, cvScalarAll(0));
cvNamedWindow( "dst", 1 ); cvShowImage( "dst", dst );
if( cvWaitKey(5) == 27 )
break;
angle = (angle + delta) % 360;
}
return 0;
}

OUTPUT:- 

ALSO READ :- 


OPENCV Tutorial - Basic operations for images Dilate/Erode

Let us do some more image processing in openCV. In this turorial we will do Dilate/Erode operation. This is a basic Morphological Operations.  To learn more about  Morphological Operations I have found a very good tutorial. You can find it here

Now we will use function Erode ( - Erodes image by using arbitrary structuring element and) Dilate -(Dilates image by using arbitrary structuring element).

lets learn a bit about functions -


void cvErode( const CvArr* src, CvArr* dst, IplConvKernel* element=NULL, int iterations=1 );

src
Source image.
dst
Destination image.
element
Structuring element used for erosion. If it is NULL, a 3×3 rectangular structuring element is used.
iterations
Number of times erosion is applied.
The function cvErode erodes the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the minimum is taken:



void cvDilate( const CvArr* src, CvArr* dst, IplConvKernel* element=NULL, int iterations=1 );

src
Source image.
dst
Destination image.
element
Structuring element used for erosion. If it is NULL, a 3×3 rectangular structuring element is used.
iterations
Number of times erosion is applied.
The function cvDilate dilates the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the maximum is taken:

NOTE:- Both functions supports the in-place mode. Erosion can be applied several (iterations) times. In case of color image each channel is processed independently.


After enough learning lets write a program :-


#include "cxcore.h"
#include "highgui.h"
int main()
{
            IplImage* newImg = NULL;
IplImage* dilateImg = NULL;
IplImage* erodeImg = NULL;

cvNamedWindow("src", 1);
cvNamedWindow("dilate",1);
cvNamedWindow("erode",1);

//load original image
newImg = cvLoadImage("apple.bmp",1);
cvShowImage( "src", newImg );

//make a copy of the original image
dilateImg=cvCloneImage( newImg );
erodeImg=cvCloneImage( newImg );

//dilate image
cvDilate(newImg,dilateImg,NULL,4);

//erode image
cvErode(newImg,erodeImg,NULL,4);
cvShowImage( "dilate", dilateImg );
cvShowImage( "erode", erodeImg );
cvWaitKey(0);
cvDestroyWindow( "src" ); cvDestroyWindow( "dilate" ); cvDestroyWindow( "erode" );
cvReleaseImage( &newImg ); cvReleaseImage( &dilateImg ); cvReleaseImage( &erodeImg );
return 0;

}



Open CV Tutorial - Basic operations for images ' Canny edge detection'

 In the last tutorial I have discussed how to setup workspace for different IDEs and basic tutorials about Opencv. Now let us make some more good programs. Lets us make a program for canny edge detection. Canny edge is one of the most widely used edge detection programs used along with other edge detection like Sobel. Read more about Canny algorithm here.


In OpenCV we get a very good implementation of Canny algorithm. The function cvCanny finds the edges on the input image image and marks them in the output image edges using the Canny algorithm. The smallest of threshold1 and threshold2 is used for edge linking, the largest - to find initial segments of strong edges.A brief intro of function is as:-


void cvCanny( const CvArr* image, CvArr* edges, double threshold1,
              double threshold2, int aperture_size=3 );


Explanation of function:-

image

Input image.

edges

Image to store the edges found by the function.

threshold1

The first threshold.

threshold2

The second threshold.

aperture_size ( a bit complicated :( but try to grasp it or use default-3 in most cases)

    

In all cases except 1, aperture_size ×aperture_size separable kernel
    will be used to calculate
    the derivative. For aperture_size=1 3x1 or 1x3 kernel is
    used (Gaussian smoothing is not done).
    There is also special value CV_SCHARR (=-1) that
    corresponds to 3x3 Scharr filter that may
    give more accurate results than 3x3 Sobel. Scharr aperture is:
| -3 0  3|
|-10 0 10|
| -3 0  3|
for x-derivative or transposed for y-derivative.
Now we will write a sample program :-


#include "cv.h"
#include "highgui.h"
int main()
{
IplImage* newImg; // original image
IplImage* grayImg; // gray image for the conversion of the original image
IplImage* cannyImg; // gray image for the canny edge detection
//load original image
newImg = cvLoadImage("apple.bmp",1);
//create a single channel 1 byte image (i.e. gray-level image)
grayImg = cvCreateImage( cvSize(newImg->width, newImg->height), IPL_DEPTH_8U, 1 );
//convert original color image (3 channel rgb color image) to gray-level image
cvCvtColor( newImg, grayImg, CV_BGR2GRAY );
cannyImg = cvCreateImage(cvGetSize(newImg), IPL_DEPTH_8U, 1);
// canny edge detection
cvCanny(grayImg, cannyImg, 50, 150, 3);
cvNamedWindow("src", 1);
cvNamedWindow("canny",1);
cvShowImage( "src", newImg );
cvShowImage( "canny", cannyImg );
cvWaitKey(0);
cvDestroyWindow( "src" );
cvDestroyWindow( "canny" );
cvReleaseImage( &newImg );
cvReleaseImage( &grayImg );
cvReleaseImage( &cannyImg );
return 0;
}


OUTPUT :- 

Also Read :- 

Open CV Tutorial and Introduction

Introduction: -
For past few years I am using OpenCV for my image processing library. Initially I stared with Matlab. But the
as usual the programing in Matlab was easy but the execution was really slow. For my real time image processing project I stared to search for a good Image processing library and found OpenCv. It was not only fast but I can built exe files unlike m files in Matlab. I this tutorial along with a brief intorduction, we will a very simple OpenCV program.

You can download OpenCv library form :- http://sourceforge.net/projects/opencvlibrary/ Latest version is 2.1. You will also have to setup the workspace. You can find it  here. For DevC++ user the setup part is here.

Lets see some important features of OpenCV:-

  • Open source computer vision library in C/C++.
  • Optimized and intended for real-time applications.
  • OS/hardware/window-manager independent.
  • Generic image/video loading, saving, and acquisition.
  • Both low and high level API.
  • Provides interface to Intel's Integrated Performance
  • Primitives (IPP) with processor specific optimization (Intel processors).


OpenCV modules
There are mainly 4 modules in OpenCV. These are

  • cv - Main OpenCV functions.
  • cvaux - Auxiliary (experimental) OpenCV functions.
  • cxcore - Data structures and linear algebra support.
  • highgui - GUI functions.



Image data structure in OpenCV and a Sample Program:-
Now we have done enough reading, Lets try our hands at some programing. In this simple program we will load a image file and show in window. I assume you have sample image :- 
sample.bmp. 


#include "cv.h" //main OpenCV functions
#include "highgui.h" //OpenCV GUI functions¯include <stdio.h> so no need to re include it.
int main()
{
       /* declare a new IplImage pointer, the basic
          image data structure in OpenCV */
          IplImage* newImg;
        /* load an image named "sample.bmp", 1 means
           this is a color image */
            newImg = cvLoadImage("sample.bmp",1);
         //create a new window
             cvNamedWindow("Window", 1);
          //display the image in the window
             cvShowImage("Window", newImg);
             //wait for key to close the window
            cvWaitKey(0);
            cvDestroyWindow( "Window" ); //destroy the window
            cvReleaseImage( &newImg ); //release the memory for the image
    return 0;
}

Sunday, November 22, 2009

How to make you PC Dual Boot Linux and windows




For past few years I have been using Linux (Fedora). When I decided to use Linux the first thing came in my mind is how to make my PC dual boot for both windows and Linux. Though one method was simple I allowed the grub loader to install in my MBR (master boot record) and there I chose  lable "other" as default.

Though that was the most simple thing to do but later I faced a problem. When I tried to boot my pc with windows xp bootable CD it did't booted with that. That was because there was grub loader in MBR.

So later I searched for Installing Fedora or other Linux without installing GRUB in MBR. So by default the windows loader NTLDR should detect the linux partion and it should boot your linux with it. The the problem is that you NTLDR can't detect linux partion. So basically you have to copy a file in your windows partion.

There are few methods to do it :-
  • 1# Use dd to copy GRUB stage1 to a binary file:- Install Fedora and choose the boot loader option to install GRUB in the first sector of the Fedora boot partition (see attachment). Fedora will not boot at first. In linux rescue (see attachment), use the dd command to copy GRUB stage1 located in the first sector of the Fedora boot partition to a binary file in the Windows root directory. Then manually edit boot.ini (see attachment) to add a new entry for Fedora to the Windows boot menu to launch the binary file. 
    • After Fedora is installed...
    • Boot with the Fedora DVD into linux rescue.
    • At the command prompt, enter:

      dd if=/dev/sdxy of=fedora.bin bs=512 count=1


    • NOTE: You change x & y to the drive & partition of the Fedora boot partition with stage1. You may also change the name of the output file to whatever you choose.

    • Copy the binary file to a floppy or a partition that Windows can access (see attachment).
    • Exit linux rescue and reboot into Windows.
    • Copy the binary file to C:\ where boot.ini is also located.
    • Edit boot.ini to add a line similar to this:

      Code:
      c:\fedora.bin="Fedora"


    • Reboot.
    • How it looks on paper

      Code:
                                                boot.ini               /--> kernel
                                                          |                 / 
      BIOS --> Partition Loader --> Boot Sector Code --> ntldr --> XP Menu -----> kernel          grub.conf                  /--> kernel
                 (Master Boot        (Volume Boot          |                \                         |                     / 
                    Record)             Record)       ntdetect.com           \--> fedora.bin --> GRUB stage2 --> GRUB Menu -----> kernel
                                                                                 (GRUB stage1)   (/boot/grub)               \ 
                                                                  
       

    • NOTE: This "dd method" sometimes doesn't work if the Fedora boot partition is not on the same drive as Windows. That can result in an incorrect boot drive number being specified in the code of the binary file at offset 40h. The hex values for the boot drive number are first=80h, second=81h, third=82h, and so on. If the value at offset 40h is FFh, that means that the stage1 program gets the boot drive number from BIOS, and that also could be wrong for the physical layout. The binary file can be edited with any hex editor to change the boot drive number when this happens. In the example below, the value for the boot drive number at offset 40h is FFh. The Fedora boot partition was on the second drive, and the binary file did not work to boot the Fedora system. The binary file was edited with ghex to change the boot drive number to 81h, and then it worked to boot the Fedora system.

  •  2# BOOTPART:-
    • Summary

      Install Fedora and choose the boot loader option to install GRUB in the first sector of the Fedora boot partition (see attachment). Fedora will not boot at first. Use BOOTPART in Windows to create a binary file containing code that loads and executes the boot sector code of the Fedora boot partition (stage1). BOOTPART also edits boot.ini to add a new entry for Fedora to the Windows boot menu to launch the binary file. BOOTPART is often useful when the dd-created binary file fails to work.

      The Steps

      After Fedora is installed...
    • Reboot into Windows.
    • Download BOOTPART from the Internet and unzip the files to your Windows Desktop.
    • Open a Windows Command Prompt window. From here on, everything occurs in this window.
    • Change directories to the Windows Desktop...

      Code:
      cd desktop


    • Enter the command bootpart without any options and your partitions will be listed. Example...

      Code:
      C:\Documents and Settings\User\Desktop>bootpart
      
      Physical number of disk 0 : 9590e5ce
       0 : C:* type=b  (Win95 Fat32), size= 2008093 KB, Lba Pos=63
       1 : C:  type=5  (Extended), size= 18000832 KB, Lba Pos=4016250
       2 : C:  type=7  (HPFS/NTFS), size= 18000801 KB, Lba Pos=4016313
      Physical number of disk 1 : b4f03683
       3 : D:* type=7  (HPFS/NTFS), size= 80035798 KB, Lba Pos=63
      Physical number of disk 2 : 9a109a0
       4 : E:* type=83 (Linux native), size= 104391 KB, Lba Pos=63
       5 : E:  type=8e (Linux LVM), size= 38989755 KB, Lba Pos=208845


    • Now enter the command again in this format...

      Code:
      bootpart [partition number] [filename] [title]
      [partition number] Get this from the output of your bootpart command without options in the previous step. In the above example, partition #4 is the Fedora boot partition and is easy to spot since it is listed as type=83 (Linux native) and the other Linux partition is an LVM physical volume. If there had been several type 83 partitions instead of the LVM PV, here are some clues to find the boot partition: a) it is usually the first type 83 Linux partition in the list, b) it is usually about 100000 KB in size, c) it may have an asterisk (*) by it indicating it is the active partition.

      [filename] This is the name to give the binary file to be created in the Windows root directory. It can be anything you want.

      [title] This the title of the Fedora OS in the Windows boot loader menu. It can be anything you want.



    • Continuing with the example from above, the command could be like this...

      Code:
      bootpart 4 C:\fedora.bin "Fedora"


    • Reboot.
How it looks on paper
Code:
boot.ini               /--> kernel
                                                    |                 / 
BIOS --> Partition Loader --> Boot Sector Code --> ntldr --> XP Menu -----> kernel                          grub.conf                  /--> kernel
           (Master Boot        (Volume Boot          |                \                                         |                     / 
              Record)             Record)       ntdetect.com           \--> fedora.bin --> GRUB stage1 --> GRUB stage2 --> GRUB Menu -----> kernel
                                                                            (BOOTPART)    (boot sector)    (/boot/grub)               \                                                     
  •  #3: GRUB for DOS(my favorate)
    Summary

    Install Fedora and choose the boot loader option to install GRUB in the first sector of the Fedora boot partition (see attachment). Fedora will not boot at first. This method uses GRUB for DOS (aka GRUB4DOS) which is capable of launching the Fedora kernel directly without using any GNU GRUB stages. Even though Fedora's GRUB stages are not required for this method to work, there is still a benefit from choosing to install GRUB in the first sector of the Fedora boot partition. It causes a grub.conf file to be created for Fedora while still sparing the master boot record from changes. Having a grub.conf file is useful for copying menu commands to the GRUB for DOS menu.lst or for using the configfile menu command to launch Fedora. The stage1 code that is installed in the boot sector causes no harm sitting there unused.

    The Steps

    After Fedora is installed...
  • Reboot into Windows.
  • Download the GRUB4DOS zip file.
  • Unzip the file and copy these files to C:\ (or the Windows root directory):



    1. grldr
    2. menu.lst



  • Edit boot.ini (see attachment) to add a line similar to this:

    Code:
    c:\grldr="Start GRUB"


  • Edit menu.lst to add sections for the Linux systems (and to tidy up for the many examples).
  • Reboot.
How it looks on paper
Code:
boot.ini               /--> kernel
                                                    |                 /
BIOS --> Partition Loader --> Boot Sector Code --> ntldr --> XP Menu -----> kernel                /--> kernel
           (Master Boot        (Volume Boot          |                \                          /
              Record)             Record)       ntdetect.com           \--> grldr --> GRUB Menu -----> kernel
                                                                              |                  \
                                                                           menu.lst               \--> kernel
                                                                      (using configfile)
The usual menu commands all work in the GRUB for DOS menu.lst file. The title, root, kernel, and initrd lines can be copied from another configuration file to directly boot a Linux kernel. Or, the configfile command can be used to reload the menu with the information from another system's GRUB configuration file. And, the chainloader command can be used to launch boot sector code.

Wednesday, November 4, 2009

Star Field Effect in C by writing in VGA memory

For past few time I was working on the 16 Bit version of C compiler namely TurboC++. and was programing in few Graphical libraries. I was keen on writing a program in C to show a similar effect like that of Star field effect in the Windows Screen Saver but writing the routes at low level directly to VGA memory. I designed a library for that form a bit of help form net.
                                  Here I am posting a C program to Create a Star field effect in C.  Also I have well Documented the code so that you can under Stand it well.

download the executable  and source code file form exe form here

Library to enable mouse in 16BIT turboC++ (works upto windows XP)

///////////////////////////////////////////////////////////////
///            MOUSE.H WRITTEN BY RITESH RANJAN        
///            
///         ******************************************    
///            feel free to modify and use it   I would to hear from u abt improvements       
///      ************************************************   
///           ritesh_ranjan007@yahoo.com                 
//////////////////////////////////////////////////////////////////

#include< dos.h >

unsigned int mousex,mousey,mouseb;   // global varialble


void showmouse();
void hidemouse();
void readmouse();
void setmousexy();
void setminmaxx(int ,int);
void setminmaxy(int, int);





//////////////////////////////////////////////////////

void showmouse()
{
   _AX=0x1;
   geninterrupt(0x33);
}
///////////////////////////////////////////////////////
void hidemouse()
{
   _AX=0x2;
   geninterrupt(0x33);
}
//////////////////////////////////////////////////////
void readmouse()
{
  _AX=0x3;
  geninterrupt(0x33);
  mouseb=_BX;
  mousex=_CX;
  mousey=_DX;
}

///////////////// move mouse to x,y /////////////////////
void setmousexy(int x,int y)
{
  _AX=0x4;
  _CX=x;
  _DX=y;
  geninterrupt(0x33);
}
/////////////////// set max min x values /////////////////////////////

void setminmaxx(unsigned int min,unsigned int max)
{
  _AX=0x7;
  _CX=min;
  _DX=max;
  geninterrupt(0x33);
}

////////////////////// set max min y values /////////////////////////

void setminmaxy(unsigned int min,unsigned int max)
{
  _AX=0x8;
  _CX=min;
  _DX=max;
  geninterrupt(0x33);
}
/////////////////////////////////////////////////////////////////

Tuesday, November 3, 2009

Image Processing - Code to filter color in MATLAB

In this post we will learn to how filter color in Matlab. Matlab provide very good Image processing tool box with many ready made functions. Here I have illustrated a very basic method to filter color in Matlab. The concept is- in the 3D matrix of RGB color space, if the value at a particular pixel have more value in Red space than blue or Green, and if it is within a tolerance value then consider that pixel Red.
eg -


  elseif im(i,j,1)>200 & im(i,j,2)<50 & im(i,j,3)<50
            white(i,j)=0;
            green(i,j)=0;
            blue(i,j)=0;
            red(i,j)=1;


Copy this code an save as .m file. then run this file.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ------------------------@author:-  RITESH RANJAN
% -------- visit:-  http://programing-tutorial.blogspot.com/
% ------I have used a simple method. There are many more complex
%--------------- methods too that I will discuss Later
% ------------Just copy it save a .m file run in MATLAB 7 or higher
% ----------------Don't forget to change the name of Image file

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear;
im=imread('image.jpg'); %put image name here
imtool(im);
sz=size(im);

for i=1:sz(1)
    for j=1:sz(2)
        if im(i,j,1)>200 & im(i,j,2)>200 & im(i,j,3)>200
            white(i,j)=1;
            green(i,j)=0;
            blue(i,j)=0;
            red(i,j)=0;
        elseif im(i,j,1)>200 & im(i,j,2)<50 & im(i,j,3)<50
            white(i,j)=0;
            green(i,j)=0;
            blue(i,j)=0;
            red(i,j)=1;
        elseif im(i,j,1)<50 & im(i,j,2)>200 & im(i,j,3)<50
            white(i,j)=0;
            green(i,j)=1;
            blue(i,j)=0;
            red(i,j)=0;
        elseif im(i,j,1)<50 & im(i,j,2)<50 & im(i,j,3)>200
            white(i,j)=0;
            green(i,j)=0;
            blue(i,j)=1;
            red(i,j)=0;
        else 
            white(i,j)=0;
            green(i,j)=0;
            blue(i,j)=0;
            red(i,j)=0;
       end
             end
end


imtool(white);
imtool(green);
imtool(blue);
imtool(red);

Image Proseesing - Extacting Shapes using OpenCV

 // This is a program to find SQUARE shape and Circle shape


#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include < math.h >
int main(int argc, char* argv[])
{

    IplImage* img=0;
    IplImage* gray=0;

    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq*  contours;

    img=cvLoadImage("shape.jpg");

    if(img==NULL)
    {
        printf("Error in opening image\n");
        return -1;
    }


    cvNamedWindow("win1",1);
    cvNamedWindow("win2",1);

    gray = cvCreateImage( cvSize(img->width, img->height), IPL_DEPTH_8U, 1 );
    cvCvtColor(img,gray,CV_BGR2GRAY );

    uchar *data;
    data=(uchar* )img->imageData;

    uchar *data_gray;
    data_gray=(uchar* )gray->imageData;

    int  step_g=gray->widthStep;
    int  step=img->widthStep;
    int channels=img->nChannels;

   


     for(int i=0;iheight;i=i++)
     {
         for(int j=0;jwidth;j++)
         {
             
             
             /////////////exracting  white
             if( (data[i*step+j*channels+0]>200) && (data[i*step+j*channels+1]>200) && (data[i*step+j*channels+2]>220) )
                 data_gray[i*step_g+j] = 255;


            else
                data_gray[i*step_g+j] = 0;

         }
         
     }

   // find counters in the gray image - object detection
    cvFindContours( gray, storage, &contours, sizeof(CvContour),
                    CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE , cvPoint(0,0) );

   

    double area;
    double p;
    double metric_s,metric_c;

// loop through all counturs   

for( ; contours != 0; contours = contours->h_next )
    {
        area=fabs( cvContourArea(contours,CV_WHOLE_SEQ ) );
        p=fabs( cvArcLength( contours, CV_WHOLE_SEQ, -1) );

        // determine metric for circle
        metric_c=area*4*3.14/(p*p);
        metric_s=area*16/(p*p);

        if(metric_c > 0.75f && metric_s > 1.0f)
            printf(" circle \n");

        else if(metric_s > 0.9f && metric_c < 0.8f )
            printf(" square \n");

        else
            printf(" nothing ");


        printf("area = %lf perimeter=%lf metric_c=%lf metric_s=%lf\n",p,area,metric_c,metric_s);



    }


     cvShowImage("win1",img);
     cvShowImage("win2",gray);

     cvWaitKey(0);
   
    cvDestroyWindow("win1");
    cvDestroyWindow("win2");

    cvReleaseImage(&img);
    cvReleaseImage(&gray);
   
   
   
   
    //printf("Hello World!\n");
    return 0;
}