Showing posts with label OpenCV. Show all posts
Showing posts with label OpenCV. Show all posts

Thursday, 5 May 2016

OpenCV C++ Code for Split and Merge -II

In the previous tutorial we split the R,G,B channels of a color image using opencv's function called split().


Refer this article:
http://opencv-code.blogspot.in/2016/12/how-to-split-color-images-merge-single-channel-images-opencv-tutorials.html


First of all why there is a need to split the channels of a color image?
As explained in the previous articles it helps us to guess the individual contribution of the respective channel in the color image.Also it has other application like object detection based on color recogntion i.e we can select a green object from the background and track it.


So the process of splitting color images without using split() function in opencv is as shown below:

// OpenCV Channel Splitting  Tutorial 
#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp> 
#include <iostream>
 
using namespace cv;
using namespace std;
 
int main()
{
 const float pi=3.14;
 Mat src1,src2,src3,src4,src5;
 src1 = imread("C:\\Users\\arjun\\Desktop\\opencv.png",CV_LOAD_IMAGE_COLOR);
 src2 = Mat::eye(src1.rows,src1.cols, CV_8UC1);
 src3 = Mat::eye(src1.rows,src1.cols, CV_8UC1);
 src4 = Mat::eye(src1.rows,src1.cols, CV_8UC1);
  
 if( !src1.data ) { printf("Error loading src1 \n"); return -1;}
 
for (int i=0; i<src1.cols ; i++){
for (int j=0 ; j<src1.rows ; j++)
 { 
Vec3b color1 = src1.at<Vec3b>(Point(i,j));
Scalar color2 = src2.at<uchar>(Point(i,j));
Scalar color3 = src3.at<uchar>(Point(i,j));
Scalar color4 = src4.at<uchar>(Point(i,j));
 
      color2.val[0]=color1.val[0]; //Blue channel
    
   color3.val[0]=color1.val[1];  //Green Channel
 
   color4.val[0]=color1.val[2];  //Red Channel
     
   src2.at<uchar>(Point(i,j)) = color2.val[0];
   src3.at<uchar>(Point(i,j)) = color3.val[0];
   src4.at<uchar>(Point(i,j)) = color4.val[0];
  }
 }
namedWindow("Original Image",CV_WINDOW_AUTOSIZE); 
imshow("Original Image", src1);
 
namedWindow("Red Channel Image",CV_WINDOW_AUTOSIZE); 
imshow("Red Channel Image", src4);
imwrite("C:\\Users\\arjun\\Desktop\\opencv-red.png",src4);
 
namedWindow("Green Channel Image",CV_WINDOW_AUTOSIZE); 
imshow("Green Channel Image", src3); 
imwrite("C:\\Users\\arjun\\Desktop\\opencv-green.png",src3);
 
namedWindow("Blue Channel Image",CV_WINDOW_AUTOSIZE); 
imshow("Blue Channel Image", src2); 
imwrite("C:\\Users\\arjun\\Desktop\\opencv-blue.png",src2);
 
 waitKey(0);
 return 0;
}



Input:


Output:
Red:

Green:

Blue:



Similarly the process of merging the channels in opencv again so that only individual color channels are displayed can be done as:
// OpenCV Channel Merging  Tutorial 
#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp> 
#include <iostream>
 
using namespace cv;
using namespace std;
 
int main()
{
 const float pi=3.14;
 Mat src1,src2,src3,src4,src5;
 src1 = imread("C:\\Users\\arjun\\Desktop\\opencv.png",CV_LOAD_IMAGE_COLOR);
 src2 = Mat::eye(src1.rows,src1.cols, CV_8UC3);
 src3 = Mat::eye(src1.rows,src1.cols, CV_8UC3);
 src4 = Mat::eye(src1.rows,src1.cols, CV_8UC3);
  
 if( !src1.data ) { printf("Error loading src1 \n"); return -1;}
 
for (int i=0; i<src1.cols ; i++){
for (int j=0 ; j<src1.rows ; j++)
 { 
Vec3b color1 = src1.at<Vec3b>(Point(i,j));
Vec3b color2 = src2.at<Vec3b>(Point(i,j));
Vec3b color3 = src3.at<Vec3b>(Point(i,j));
Vec3b color4 = src4.at<Vec3b>(Point(i,j));
 
      color2.val[0]=color1.val[0]; //Blue channel
   color2.val[1]=0;
   color2.val[2]=0;
 
   color3.val[0]=0;             //Green Channel
   color3.val[1]=color1.val[1];
   color3.val[2]=0;
 
   color4.val[0]=0;             //Red Channel
   color4.val[1]=0;
   color4.val[2]=color1.val[2];
     
   src2.at<Vec3b>(Point(i,j)) = color2;
   src3.at<Vec3b>(Point(i,j)) = color3;
   src4.at<Vec3b>(Point(i,j)) = color4;
  }
 }
namedWindow("Original Image",CV_WINDOW_AUTOSIZE); 
imshow("Original Image", src1);
 
namedWindow("Red Channel Image",CV_WINDOW_AUTOSIZE); 
imshow("Red Channel Image", src4);
imwrite("C:\\Users\\arjun\\Desktop\\opencv-red.png",src4);
 
namedWindow("Green Channel Image",CV_WINDOW_AUTOSIZE); 
imshow("Green Channel Image", src3); 
imwrite("C:\\Users\\arjun\\Desktop\\opencv-green.png",src3);
 
namedWindow("Blue Channel Image",CV_WINDOW_AUTOSIZE); 
imshow("Blue Channel Image", src2); 
imwrite("C:\\Users\\arjun\\Desktop\\opencv-blue.png",src2);
 
 waitKey(0);
 return 0;
}



Input:

Output:
Red:

Green:

Blue:



Note the difference between the two codes:
In channel splitting we have taken 8UC1 i.e a 8 bit unsigned single channel image.
In channel merging we have taken 8UC3 i.e a 8 bit unsigned three channel image.

Tuesday, 5 April 2016

Modifying a particular pixel value of an Image

In the previous tutorials we learnt how to access a pixel value of a particular co-ordinate,
Refer :
http://opencv-code.blogspot.in/2016/12/how-to-access-extract-pixel-value-particular-location-image.html

This,

OpenCV C++ tutorial

is about accessing and changing the pixel value at a particular co-ordinate of an Image.
Here is the code below:
/*Displaying the Pixel value of the whole Image using Loops*/
 
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <iostream> 
 
  using namespace std;  
  using namespace cv;  
 
int main() 
  {  
    Mat image1,image2; 
    //Reading the color image 
    image1 = imread("C:\\Users\\arjun\\Desktop\\image003.png", CV_LOAD_IMAGE_COLOR);  
 
    //If image1 not found 
    if (!image1.data)                                                                          
    {  
     cout << "No image data \n";  
     return -1;  
    } 
 
    //Display the original image
    namedWindow("Original Image");               
    imshow("Original Image", image1);
 
    //Changing the pixel value at just a particular point(100,200)
     Vec3b color = image1.at<Vec3b>(Point(100,200));
      color.val[0] = 100;
      color.val[1] = 0;
      color.val[2] = 0;
    image1.at<Vec3b>(Point(100,200)) = color;
 
    //Save the modified image
    imwrite("C:\\Users\\arjun\\Desktop\\mod_image.png",image1);
    //Reading the modifed image
    image2 = imread("C:\\Users\\arjun\\Desktop\\mod_image.png", CV_LOAD_IMAGE_COLOR);  
 
   //If image2 not found 
     if (!image2.data)                                                                          
       {  
        cout << "No image data \n";  
        return -1;  
       } 
 
    //Display the modified image
    namedWindow("Modified Image");               
    imshow("Modified Image", image2); 
    waitKey(0);
    return 0;
   }

Input:


Modified Image:


Wednesday, 30 March 2016

Accessing Pixel Value at a Location(x,y)

Let us consider a 3 channel image of BGR color ordering
(The BGR color ordering is the default order returned  by imread)
Here the order of the channel is reverse

(We generally use RGB color model while describing about an image.In BGR the color model is same except the order of the channel is reverse)


We use :
Vec3b imagepixel = image.at(x,y);


/*Reading the pixel value of an image at a particular location*/
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <iostream> 
 
  using namespace std;  
  using namespace cv;  
 
  int main() 
  {  
    Mat image; 
    //Reading the color image 
    image = imread("C:\\Users\\arjun\\Desktop\\image003.png", CV_LOAD_IMAGE_COLOR);  
 
    //If image not found
     if (!image.data)                                                                          
     {  
      cout << "No image data \n";  
      return -1;  
     } 
    
     
     //Reading pixel value at location (i,j)
     Vec3b imagepixel = image.at<Vec3b>(250,500);

     //Displaying the pixel value  
     cout<<"imagepixel(BGR)="<<imagepixel<<"\n" ;  
        
     //Display the original image
     namedWindow("Display Image");               
     imshow("Display Image", image);  
  
     waitKey(0);
     return 0;
   }



Input:


Output:





/*Reading the pixel value of an image at a particular location*/
 
 
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <iostream> 
 
  using namespace std;  
  using namespace cv;  
 
int main() 
  {  
    Mat image; 
    //Reading the color image 
    image = imread("C:\\Users\\arjun\\Desktop\\image003.png", CV_LOAD_IMAGE_COLOR);  
 
     //If image not found  
       if (!image.data)                                                             
     {  
      cout << "No image data \n";  
      return -1;  
     } 
 
 
    while(1)
    {
     //Taking inputs from the user for the co-ordinates of the image 
      int i,j;
      cout<<"Enter the co-ordinates of the image where you want to find the pixel value (i,j): \n";
      cout<<"i<"<<image.rows<<"\t"<<"&"<<"\t"<<"j<"<<image.cols<<"\n";
      
     cout<<"i= ";  cin>>i;
     cout<<"j= ";  cin>>j;
     
     if(i < image.rows) 
      { 
        if(j < image.cols)
          {
           //Reading pixel value at location (i,j)
            Vec3b imagepixel = image.at<Vec3b>(i,j); 
           //Displaying the pixel value                                                        
           cout<<"imagepixel(BGR)="<<imagepixel<<"\n" ;
          }  
        }
      else
        { 
           cout<<"Image Co-ordinates value out of range \n"; 
        }
 
     }
        return 0; 
  }


Input:


Output:



Friday, 25 March 2016

OpenCV C++ Code for Drawing a Chessboard Pattern

This OpenCV Tutorial is about drawing a Chess Board Pattern.
Refer the Code Below:



//Opencv Example of Drawing a Chess Board Pattern
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
  
int main( )
{ 
 int a=400/8;
  // Create black empty images
  Mat image = Mat::zeros( 400, 400, CV_8UC3 );
    
  // Draw a rectangle ( 5th argument is not -ve)  
  for(int y=0;y<=3;y++)
  for(int x=0;x<=3;x++)
  {
  rectangle( image, Point( x*a*2, y*a*2), Point( a*(2*x+1), a*(2*y+1)), Scalar( 255, 255, 255 ), -1, 4 );
  imshow("Image1",image);
  waitKey( 250 );
  }
  for(int y=0;y<=3;y++)
  for(int x=0;x<=3;x++){
  rectangle( image, Point( a*(2*x+1), a*(2*y+1)), Point( (x+1)*a*2, (y+1)*a*2), Scalar( 255, 255,255 ), -1, 4 );
  imshow("Image1",image);
  waitKey( 250 );
  }
  waitKey( 0 );
  return(0);
}



Output:

Sunday, 20 March 2016

Opencv C++ Code for drawing Rectangle

Draws a simple, thick, or filled up-right rectangle.

Syntax:
C++ :void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)

Parameters:
img – Image.
pt1 – Vertex of the rectangle.
pt2 – Vertex of the rectangle opposite to pt1.
rec – Alternative specification of the drawn rectangle.
color – Rectangle color or brightness (grayscale image).
thickness – Thickness of lines that make up the rectangle. Negative values, like CV_FILLED , mean that the function has to draw a filled rectangle.
lineType – Type of the line. See the line() description.
shift – Number of fractional bits in the point coordinates.



#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
  
int main( )
{    
  // Create black empty images
  Mat image = Mat::zeros( 400, 400, CV_8UC3 );
    
  // Draw a rectangle 
  rectangle(image , Point (100,100), Point (300,300), Scalar( 0, 0, 255 ), 1, 8);
  imshow("Image",image);
  
  waitKey( 0 );
  return(0);
}

Tuesday, 15 March 2016

OpenCV C++ Code for Drawing a Semi-Circle

This Opencv Tutorial is about drawing a Semi-Circle

You might have wondered that how to draw a Semi-Circle in Opencv when we have no direct syntax available for it.
Even in the Syntax of drawing a circle in Opencv, we dont have any such parameters which can be modified for drawing a semicircle.


C++ :void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int shift=0)

But, we know that a circle is a special case of an ellipse whose eccentricity is 1. And in the Opencv Ellipse Syntax:

C++ :void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness=1, int lineType=8, int shift=0)

We can find the parameters like "Start Angle" and "End Angle".
And if we want to draw an Circle From an Ellipse we just need to mention the size of both the axes as same.
Thus,Here is the Opencv Code for drawing a Semi-Circle:



//Opencv C++ Tutorial for drawing a Semi-Circle
#include <opencv2 core.hpp="" core="">
#include <opencv2 highgui.hpp="" highgui="">
using namespace cv;
int main( )
{
 // Create black empty images
 Mat image = Mat::zeros( 500, 500, CV_8UC3 );
 // Draw a ellipse
 for(int i=10;i<=250;i=i+10)
 {
 ellipse( image, Point( 250, 250 ), Size( i, i ), 0, 0, 180, Scalar( 255, 255, 0 ), 2, 8 );
 imshow("Image",image);
 waitKey( 250 );
 }
 waitKey( 0 );
 
 return(0);
}


Output:

Thursday, 10 March 2016

OpenCV C++ Code for drawing a Square Spiral

In the previous tutorial we learn about drawing an Line.
http://opencv-code.blogspot.in/2016/12/how-to-draw-line-opencv-cplusplus-example.html
Thus this opencv tutorial will be an extension of that tutorial with some added mathematical logic for drawing a square spiral.



Here is the Opencv Code Below:
//Drawing a Square Spiral
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
  
int main( )
{   
  int count=0,a,b=250,i,j;
  // Create black empty images
  Mat image = Mat::zeros( 500, 500, CV_8UC3 );
  int p=0;int q=1;
  for(a=250;a<500 && a>0;)
  {
     
   count++;
   if(count%2!=0)
   { 
      p++;
    j=b;
    if(p%2!=0) 
    {i=a+5*count;}
    else
    {i=a-5*count;}
 }
   else
  {
     
      q++;
    i=a;
    if(q%2==0 )
    {j=b+5*count;}
    else
    {j=b-5*count;}
 
    }
    // Draw a line 
  line( image, Point( a, b ), Point( i, j), Scalar( 255, 255, 0 ), 2, 8 );
   
     imshow("Image",image);
     waitKey( 100 );
  a=i;
  b=j;
  
  }
  waitKey( 0 );
  return(0);
}

Output:-

Saturday, 5 March 2016

OpenCV C++ Tutorial for drawing a Star

In the previous tutorial we learnt about drawing a LINE:
http://opencv-code.blogspot.in/2016/12/how-to-draw-line-opencv-cplusplus-example.html

Thus this opencv tutorial will be an extension of that tutorial with some added mathematical logic for drawing a star.

To begin with we first start by drawing a pentagon:
And name the vertex as a ,b ,c ,d, e.
The co-ordinates of which can be obtained by mathematical rules as explained before:

a=( 2*r*cos(36)*cos(72) , x )
b=( x-2*r*cos(36)*cos(72) , x )
c=( x , 2*r*cos(36)*sin(72) )
d=( x/2 , 0 )
e=( 0 , 2*r*cos(36)*sin(72) )




Now, The magic begins. 1. Join vertex a with d. 2. Join vertex d with b. 3. Join vertex b with e. 4. Join vertex e with c. 5. Join vertex c with a.



Here is the opencv code for drawing a Star:
//Opencv Example of drawing a Star 
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
  
int main( )
{    
  double pi=3.14;
  int a=500/(1+cos(pi*54/180));
  
  // Create black empty images
  Mat image = Mat::zeros( 500, 500, CV_8UC3 );
   
  line( image, Point((a*cos(pi*72/180)), 500),  Point(250, 0), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );
 
  line( image, Point(250, 0), Point(500-(a*cos(pi*72/180)),500), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 ); 
 
  line( image, Point(500-(a*cos(pi*72/180)),500), Point(0, 500-(a*sin(pi*72/180))), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );
 
  line( image, Point(0, 500-(a*sin(pi*72/180))), Point( 500, 500-(a*sin(pi*72/180)) ), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );
 
  line( image, Point( 500, 500-(a*sin(pi*72/180)) ), Point((a*cos(pi*72/180)), 500), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 0 );
  return(0);
}




Output:-

Tuesday, 1 March 2016

OpenCV C++ Code for Drawing a Pentagon

This Opencv C++ Tutorial is about drawing a Pentagon.

In the previous tutorials we learn about drawing a Rectangle and a Line.
To draw the Square we obtained the Co-ordinates of the vertices of the square and then joined those vertices with a Line.

Similarly in order to draw the Pentagon we first need to obtain the Co-ordinates of its Vertices.



Refer the Figure Below:



Ï´=72º (∵ Ï´ = 360º/5)
Now, In ∆OBC,
Seg OB=Seg OC;
Thus, m∠OBC=m∠OCB=x;
x+x+72º=180º ( Since Sum of All angles of a Triangle is 180º )
2x=180º - 72º ;
x=54º
i.e. m∠OBC=m∠OCB=54º;
Also,
m∠ABC=108º;
Thus, m∠ABQ=72º; & Seg BC=a;
Seg QB=a*Cos(72º);
∴ QR=QB + BC + CR;
& QB=CR;
Thus, 2*a*Cos(72º) + a =QR
where QR is the Length of the Side of the window.
Here QR=500
Thus a=500/(1+2*Cos(72º));



//Opencv C++ Example for drawing a Pentagon 
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
  
int main( )
{    double pi=3.14;
 
  //Length of a Side of Regular Pentagon
  int a=500/(1+2*cos(pi*72/180));
  
  // Create black empty images
  Mat image = Mat::zeros( 500, 500, CV_8UC3 );
   
  line( image, Point((a*cos(pi*72/180)), 500), Point(500-(a*cos(pi*72/180)),500), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );
  line( image, Point(500-(a*cos(pi*72/180)),500), Point( 500, 500-(a*sin(pi*72/180)) ), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );
  line( image, Point(500, 500-(a*sin(pi*72/180))), Point(250, 0), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );
  line( image, Point(250, 0), Point(0, 500-(a*sin(pi*72/180))), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 ); 
  line( image, Point(0, 500-(a*sin(pi*72/180))), Point((a*cos(pi*72/180)), 500), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 0 );
  return(0);
}


Output:-


Monday, 15 February 2016

OpenCV C++ Code for drawing a Line

Syntax:
C++:void line(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)

Parameters:
img – Image.
pt1 – First point of the line segment.
pt2 – Second point of the line segment.
color – Line color.
thickness – Line thickness.
lineType – Type of the line:
                 8 (or omitted) - 8-connected line.
                 4 - 4-connected line.
                 CV_AA - antialiased line.
shift – Number of fractional bits in the point coordinates.



//Opencv Code for drawing a Line
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
  
int main( )
{    
  // Create black empty images
  Mat image = Mat::zeros( 400, 400, CV_8UC3 );
    
  // Draw a line 
  line( image, Point( 15, 20 ), Point( 70, 50), Scalar( 110, 220, 0 ),  2, 8 );
  imshow("Image",image);
  
  waitKey( 0 );
  return(0);
}

Wednesday, 10 February 2016

Zeros,Ones and Eyes in OpenCV


Matlab style Initializers
Mat::zeroes
Each element of the matrix is zero of the specified size.
Mat A;
A = Mat::zeros(3, 3, CV_32F);


Mat::ones
Each element of the matrix is one of the specified size
Mat A;
A = Mat::ones(3, 3, CV_32F);


Mat::eyes
It returns an identity matrix of the specified size.
Mat A;
A = Mat::eyes(3, 3, CV_32F);


Note:
We can also mention the scale factor of the matrix.
e.g:
A = Mat::ones(3, 3, CV_32F)* 5;
Here each element of the matrix is 5, because each element of the uniy matrix is multiplied by 5.


#include <opencv2/core/core.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp> 
 
using namespace cv;
using namespace std;
 
int main()
{
    Mat imgA = Mat::eye(5, 5, CV_8UC1);
cout << "imgA = \n " << imgA << "\n\n";
 
Mat imgB = Mat::ones(4, 4, CV_8UC1);
cout << "imgB = \n " << imgB << "\n\n";
 
Mat imgC = Mat::zeros(3,3, CV_8UC1);
cout << "imgC = \n " << imgC << "\n\n";
 
return 0;
}

Output:



Note:
Here we have selected the single channel matrix.(CV_8UC1)
For 3 channel matrices:


Code:
#include <opencv2/core/core.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp> 
 
using namespace cv;
using namespace std;
 
int main()
{
    Mat imgA = Mat::eye(5, 5, CV_8UC3);
cout << "imgA = \n " << imgA << "\n\n";
 
Mat imgB = Mat::ones(4, 4, CV_8UC3);
cout << "imgB = \n " << imgB << "\n\n";
 
Mat imgC = Mat::zeros(3,3, CV_8UC3);
cout << "imgC = \n " << imgC << "\n\n";
 
return 0;
}





See the difference in the output.Here the zeros,ones and eyes operator is applied only to 1 channel of the matrix.Rest of the other channel elements are taken 0.Thus two columns of 0 can be seen in between.

Also we doesn't mention the no. of channels by default it takes 1.
ie. CV_8U is equivalent to CV_8UC1.

Saturday, 30 January 2016

Capturing a Video from a File/Webcam

Video is a series of images displayed sequentially in quick succession.
Thus in other words we can say that a video is a continuous frame of images.Here by continuous we mean that each image frame is played in a rapid succession such that it appears continuous frames to our eyes.
(Due to persistence of vision)

Thus processing a video is analogous to processing each frame of still images.
There are two ways to process a video:
1. Load it from a file
2. Capture it from a webcam i.e real time recording of video.

Thus if we need to capture a video from a webcam we need to just replace the line of the code by
VideoCapture capture(0);
where the parameter 0 indicates that we are using the default camera for capturing the video.

Thus if attach external camera other than the one which we have with our laptop we need to give that index as our parameter.

e.g VideoCapture capture(1);

Reading from a File:


//OpenCv C++ Code for reading video from a File
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
  using namespace std;
  using namespace cv;
 
  int main()
  {
       //Capturing the Video
       VideoCapture capture("D:\\MyVideo.avi");

       
       //Check whether video is Opening
       if (!capture.isOpened())
       throw "Error when reading file";

       namedWindow("window", 1);
       
       //Reading frames of Video
       for (;;)
     {
            Mat frame;
            capture >> frame;
            if (frame.empty())
              break;
            imshow("window", frame);
            waitKey(1);
       }
   }  


Reading from a Webcam:


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
  using namespace std;
  using namespace cv;
 
  int main()
  {
       //Capturing the Video
       VideoCapture capture(0);

       
       //Check whether video is Opening
       if (!capture.isOpened())
       throw "Error when reading file";

       namedWindow("window", 1);
       
       //Reading frames of Video
       for (;;)
     {
            Mat frame;
            capture >> frame;
            if (frame.empty())
              break;
            imshow("window", frame);
            waitKey(1);
       }
   }  

Monday, 25 January 2016

RGB to Other Color Space Conversion

cvtcolor() converts an image from one color space to another.



Syntax :
C++:void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0 )

Parameter:
src   :– input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point.
dst    :– output image of the same size and depth as src.
code  :– color space conversion code (see the description below).
dstCn :– number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code.



As it has already been mentioned that the functions converts an image form one color space to another, there are various types of conversion possible.

Transformation Syntax
RGB to YCrCb CV_RGB2YCrCb
BGR to YCrCb CV_BGR2YCrCb
YCrCb to RGB CV_YCrCb2RGB
YCrCb to BGR CV_YCrCb2BGR

Transformation Syntax
RGB to HSV CV_RGB2HSV
BGR to HSV CV_BGR2HSV
HSV to RGB CV_HSV2RGB
HSV to BGR CV_HSV2BGR

Transformation Syntax
RGB to CIE L*a*b* CV_RGB2Lab
BGR to CIE L*a*b* CV_BGR2Lab
CIE L*a*b* to RGB CV_Lab2RGB
CIE L*a*b* to BGR CV_Lab2BGR

Transformation Syntax
RGB to CIE L*u*v* CV_RGB2Luv
BGR to CIE L*u*v* CV_BGR2Luv
CIE L*u*v* to RGB CV_Luv2RGB
CIE L*u*v* to BGR CV_Luv2BGR

Transformation Syntax
RGB to CIE XYZ CV_RGB2XYZ
BGR to CIE XYZ CV_BGR2XYZ
CIE XYZ to RGB CV_XYZ2RGB
CIE XYZ to BGR CV_XYZ2BGR


//OpenCV C++ Code for ColorSpace Conversion
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "iostream"
 
using namespace cv;
 
int main( )
{
// char* imageName = argv[1];
 
 Mat image;
 image = imread( "C:\\Users\\arjun\\Desktop\\color-image.png", 1 );
 
 Mat RGB2GRAY_image;
 cvtColor( image, RGB2GRAY_image, CV_RGB2GRAY );
 
 Mat BGR2GRAY_image;
 cvtColor( image, BGR2GRAY_image, CV_BGR2GRAY );
 
 Mat RGB2YCrCb_image;
 cvtColor( image, RGB2YCrCb_image, CV_RGB2YCrCb );
 
 Mat BGR2YCrCb_image;
 cvtColor( image, BGR2YCrCb_image, CV_BGR2YCrCb );
 
 Mat RGB2HSV_image;
 cvtColor( image, RGB2HSV_image, CV_RGB2HSV );
 
 Mat BGR2HSV_image;
 cvtColor( image, BGR2HSV_image, CV_BGR2HSV );
 
 Mat RGB2Lab_image;
 cvtColor( image, RGB2Lab_image, CV_RGB2Lab );
 
 Mat BGR2Lab_image;
 cvtColor( image, BGR2Lab_image, CV_BGR2Lab );
 
 Mat RGB2Luv_image;
 cvtColor( image, RGB2Luv_image, CV_RGB2Luv );
 
  Mat BGR2Luv_image;
 cvtColor( image, BGR2Luv_image, CV_BGR2Luv );
 
 Mat RGB2XYZ_image;
 cvtColor( image, RGB2XYZ_image, CV_RGB2XYZ );
 
 Mat BGR2XYZ_image;
 cvtColor( image, BGR2XYZ_image, CV_BGR2XYZ );
 
 namedWindow( "original image", CV_WINDOW_AUTOSIZE );
imshow( "original image", image );
 
namedWindow( "RGB2GRAY image", CV_WINDOW_AUTOSIZE );
imshow( "RGB2GRAY image",RGB2GRAY_image );
imwrite( "C:\\Users\\arjun\\Desktop\\RGB2GRAY.jpg", RGB2GRAY_image );
 
namedWindow( "BGR2GRAY image", CV_WINDOW_AUTOSIZE );
imshow( "BGR2GRAY image", BGR2GRAY_image );
imwrite( "C:\\Users\\arjun\\Desktop\\BGR2GRAY.jpg", BGR2GRAY_image );
 
namedWindow( "RGB2YCrCb image", CV_WINDOW_AUTOSIZE );
imshow( "RGB2YCrCb image", RGB2YCrCb_image );
imwrite( "C:\\Users\\arjun\\Desktop\\RGB2YCrCb.jpg", RGB2YCrCb_image );
 
 
namedWindow( "BGR2YCrCb image", CV_WINDOW_AUTOSIZE );
imshow( "BGR2YCrCb image", BGR2YCrCb_image );
imwrite( "C:\\Users\\arjun\\Desktop\\BGR2YCrCb.jpg", BGR2YCrCb_image );
 
namedWindow( "RGB2HSV image", CV_WINDOW_AUTOSIZE );
imshow( "RGB2HSV image", RGB2HSV_image );
imwrite( "C:\\Users\\arjun\\Desktop\\RGB2HSV.jpg", RGB2HSV_image );
 
namedWindow( "BGR2HSV image", CV_WINDOW_AUTOSIZE );
imshow( "BGR2HSV image", BGR2HSV_image );
imwrite( "C:\\Users\\arjun\\Desktop\\BGR2HSV.jpg", BGR2HSV_image );
 
namedWindow( "RGB2Lab image", CV_WINDOW_AUTOSIZE );
imshow( "RGB2Lab image", RGB2Lab_image );
imwrite( "C:\\Users\\arjun\\Desktop\\RGB2Lab.jpg", RGB2Lab_image );
 
namedWindow( "BGR2Lab image", CV_WINDOW_AUTOSIZE );
imshow( "BGR2Lab image", BGR2Lab_image );
imwrite( "C:\\Users\\arjun\\Desktop\\BGR2Lab.jpg", BGR2Lab_image );
 
namedWindow( "RGB2Luv image", CV_WINDOW_AUTOSIZE );
imshow( "RGB2Luv image", RGB2Luv_image );
imwrite( "C:\\Users\\arjun\\Desktop\\RGB2Luv.jpg", RGB2Luv_image );
 
namedWindow( "BGR2Luv image", CV_WINDOW_AUTOSIZE );
imshow( "BGR2Luv image", BGR2Luv_image );
imwrite( "C:\\Users\\arjun\\Desktop\\BGR2Luv.jpg", BGR2Luv_image );
 
namedWindow( "RGB2XYZ image", CV_WINDOW_AUTOSIZE );
imshow( "RGB2XYZ image", RGB2XYZ_image );
imwrite( "C:\\Users\\arjun\\Desktop\\RGB2XYZ.jpg", RGB2XYZ_image );
 
namedWindow( "BGR2XYZ image", CV_WINDOW_AUTOSIZE );
imshow( "BGR2XYZ image", BGR2XYZ_image );
imwrite( "C:\\Users\\arjun\\Desktop\\BGR2XYZ.jpg", BGR2XYZ_image );
 
 waitKey(0);
 
 return 0;
}


Original Image:



RGB to Grey Image:



BGR to Grey Image:



RGB to YCrCb Image:



BGR to YCrCb Image:



RGB to HSV Image:



BGR to HSV Image:



RGB to Lab Image:



BGR to Lab Image:



RGB to Luv Image:



BGR to Luv Image:



RGB to XYZ Image:



BGR to XYZ Image:



Wednesday, 20 January 2016

RGB to GrayScale Conversion

In OpenCV we can convert an RGB image into Grayscale by two ways:
1.  By using cvtColor function.

2.  By using imread function, where the first parameter specifies the image name while the second parameter specifies the format in which we need to add the image.
Thus there can be various formats like:
a. CV_LOAD_IMAGE_UNCHANGED (<0) :loads the image as is (including the alpha channel if present).
b. CV_LOAD_IMAGE_GRAYSCALE ( 0) :loads the image as an intensity one.
c. CV_LOAD_IMAGE_COLOR (>0) :loads the image in the RGB format.



//Opencv C++ Code for RGB to GreyScale Conversion
#include "opencv2/core/core.hpp"  
#include "opencv2/highgui/highgui.hpp"  
#include "iostream"  
 
  using namespace std;  
  using namespace cv;  
 
  int main() 
  {  
   Mat image;  
   //Reading the color image  
   image = imread("C:\\Users\\arjun\\Desktop\\image003.png", CV_LOAD_IMAGE_COLOR); 
 
   //If image not found  
   if (!image.data) 
     {  
      cout << "No image data \n";  
      return -1;  
     }  
 
   //Converting the Image into GrayScale and Storing it in a Matrix 'img_gray'
   Mat img_gray;
   img_gray = imread("C:\\Users\\arjun\\Desktop\\image003.png",CV_LOAD_IMAGE_GRAYSCALE);
    
    
   //Display the original image  
   namedWindow("Display Original Image",CV_WINDOW_AUTOSIZE);  
   imshow("Display Original Image", image);  
 
   //Display the grayscale image 
   namedWindow("Display Grayscale Image",CV_WINDOW_AUTOSIZE); 
   imshow("Display Grayscale Image", img_gray);  
 
   //Save the grayscale image with a name 'gray.jpg'
   imwrite("C:\\Users\\arjun\\Desktop\\gray.jpg",img_gray);
 
   waitKey(0);  
   return 0;  
  } 


Input:



Output:


Friday, 15 January 2016

Reason for increase in the size of the image

In the previous tutorial we learnt how to save images in OpenCV, Refer:
http://opencv-code.blogspot.in/2016/12/how-to-write-and-dispay-image-in-opencv.html

This tutorial explains the reason behind increase in size of image in OpenCV.



Why does the size of the image increases when i save the same image again with a different name in OpenCV?
Solution:
There exists various methods of compression in JPEG.
So your OpenCV used a different compression technique for jpeg image than that used by an original image.
By Default OPENCV uses the compression number of 95 while dealing with JPEG images.
The higher the number , lesser compression we would obtain.


To manually pass the compression factor refer the code below:
Note: Here i have used the compression number of 25 and 100 as the compression number for JPEG image
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
 
 
int main(int argc, char **argv)
{
     Mat image1;
     const int JPEG_QUALITY = 25;
     const int JPEG_QUALITY2 = 25;

    // Read the file
    image1 = imread("C:\\Users\\arjun\\Desktop\\opencv-logo.jpg",CV_LOAD_IMAGE_COLOR);

    // Check for invalid input
    if(! image1.data )                              
    {
        cout << "Could not open or find the image" << std::endl ;
        return -1;
    } 

    vector<int> params;
    params.push_back(CV_IMWRITE_JPEG_QUALITY);
    params.push_back(JPEG_QUALITY);

    //Write the File
    imwrite( "C:\\Users\\arjun\\Desktop\\opencvlogo-new1.jpg",image1, params);

    vector<int> params2;
    params2.push_back(CV_IMWRITE_JPEG_QUALITY);
    params2.push_back(JPEG_QUALITY2);

    //Write the File
    imwrite( "C:\\Users\\arjun\\Desktop\\opencvlogo-new2.jpg",image1, params2);
  
    //Dispay the Image in the window 
    namedWindow("Image1");
    imshow("Image1",image1);
 
 waitKey(0);
}

Note:- Now compare the size of the original image and the two new images.

Sunday, 10 January 2016

Write and Dispay Image in OpenCV

In my previous tutorial i have explained how to read images in OpenCV.
Refer : http://opencv-code.blogspot.in/2016/12/how-to-read-and-display-image-in-opencv.html

This tutorial is about how to read, write and display images in Opencv.



Syntax:
C++:bool imwrite(const string& filename, InputArray img, const vector<int>& params=vector<int>() )
Saves an image to a specified file.

Parameters:           
filename – Name of file to be loaded.
image – Image to be saved.
params –
CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one
CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one

>0 Return a 3-channel color image.
=0 Return a grayscale image.
<0 Return the loaded image as is (with alpha channel).




//OpenCV C++ code for reading, writing and displaying image
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "iostream"
 
using namespace cv;
using namespace std;
 
int main( int argc, char** argv )
{
 Mat image1,image2;
 
// Read the file
image1 = imread("C:\\Users\\arjun\\Desktop\\opencv-logo.jpg",CV_LOAD_IMAGE_COLOR);

// Check for invalid input
 if(! image1.data )                              
    {
        cout << "Could not open or find the image" << std::endl ;
        return -1;
    } 
 
//Write the File
imwrite( "C:\\Users\\arjun\\Desktop\\opencv-logo-new.jpg",image1);
 
// Read the Writen File
image2 =imread("C:\\Users\\arjun\\Desktop\\opencv-logo-new.jpg",CV_LOAD_IMAGE_COLOR);  
    
//Window for displaying both the images
 namedWindow("Image1");
 imshow("Image1",image1);
 
 namedWindow("Image2");
 imshow("Image2",image2);

 waitKey(0);
 
}
Note:- Compare the size of the two images.(opencv-logo.jpg & opencv-logo-new.jpg).
To know the reason about the increase in size of the image refer:
http://opencv-code.blogspot.in/2016/12/why-does-size-of-images-increases-opencv-imwrite.html

Read and Display Image in OpenCV

Syntax:
C++: Mat imread(const string& filename, int flags=1 )

Parameters:           
filename – Name of file to be loaded.
flags –Flags specifying the color type of a loaded image:-

CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one
CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one

>0 Return a 3-channel color image.
=0 Return a grayscale image.
<0 Return the loaded image as is (with alpha channel).




//OpenCv C++ Example of Reading Image
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "iostream"
 
using namespace cv;
using namespace std;
 
int main( int argc, char** argv )
{
 Mat image1;
 
// Read the file
image1 = imread("C:\\Users\\arjun\\Desktop\\opencv-logo.jpg",CV_LOAD_IMAGE_COLOR);
// Check for invalid input
 if(! image1.data )                              
    {
        cout << "Could not open or find the image" << std::endl ;
        return -1;
    } 
 
//Dispay the Image in the window 
namedWindow("Image1");
 imshow("Image1",image1);

 waitKey(0);
}

Note the Location of the image is:
C:\Users\arjun\Desktop\a.jpg where "opencv-logo.jpg" .
( Here we append additional "\" after each file or folder name.)


Image Formats supported by OpenCV:
Windows bitmaps *.bmp, *.dib
JPEG files *.jpeg, *.jpg, *.jpe
JPEG 2000 files *.jp2
Portable Network Graphics *.png
Portable image format *.pbm, *.pgm, *.ppm
Sun rasters *.sr, *.ras
TIFF files *.tiff, *.tif

Tuesday, 5 January 2016

OpenCV vs Matlab vs Scilab vs Aforge

OpenCV stands for Open Source Computer Vision. It contains a library of programming functions for real time computer vision applications.Originally developed by Intel and now supported by Willow Garage.

MATLAB, short for MATrix LABoratory is a high level language and programming package specifically designed for quick and easy scientific calculations and I/O.

Scilab is a freely distributed open source scientific software package, released as open source under the CeCILL license (GPL compatible) firstly developed by researchers from INRIA and ENPC, and now by the Scilab Consortium. It is similar to that of Matlab.

AForge.NET is an open source C# framework designed for developers and researchers in the fields of Computer Vision and Artificial Intelligence - image processing, neural networks, genetic algorithms, fuzzy logic, machine learning, robotics, etc.

Out of these OpenCv and Matlab are the most widely used tools for image processing.

Advantages of OpenCv over Matlab are:
  1. Cost:
  2. OpenCv is OpenSource (released under BSD license) thus it doesn’t require any license to buy it.
    While Matlab (commercial single user) costs around USD $2150.
  3. Speed:
  4. OpenCv is built on C/C++
    While matlab is built on Java.
    Thus while compiling the code written in Matlab , your computer is busy trying to interpret the code of Matlab then turn it into Java and then to C/C++.
    Hence programs written in OpenCv tends to run faster than that compared to similar program written in Matlab.
    In Computer vision we are normally dealing with real time applications, speed is a major concern in such cases.
  5. Resources needed:
  6. Due to the high level nature of Matlab it occupies a lot of your computer resources(about 1 GB of RAM) as compared to that of OpenCv(about 70MB of RAM) for real time computer vision applications.
  7. Portability:
  8. Almost any device which can run C can run OpenCv programs.
Inspite of all these amazing features OpenCv loses on Matlab on the below mentioned feature:

Advantages of Matlab over OpenCv are:
  1. Ease of Access:
  2.  Matlab is a pretty high-level scripting language, meaning that you don’t have to worry about libraries, declaring variables, memory management or other lower-level programming issues. As such, it can be very easy to throw together some code to prototype your image processing idea.

    Say for example I want to read in an image from file and display it. In Matlab, you could write this as:
    I = imread('someImage.jpg');
    imshow(I);
    

    This seems to be quite easy.The same thing when it is done with OpenCv would look like this:
    //OpenCv C++ Example of Reading Image
    #include "opencv2/core/core.hpp"
    #include "opencv2/highgui/highgui.hpp"
    #include "iostream"
     
    using namespace cv;
    using namespace std;
     
    int main( int argc, char** argv )
    {
     Mat image1;
     
    // Read the file
    image1 = imread("C:\\Users\\arjun\\Desktop\\opencv-logo.jpg",CV_LOAD_IMAGE_COLOR);
    // Check for invalid input
     if(! image1.data )                              
        {
            cout << "Could not open or find the image" << std::endl ;
            return -1;
        } 
     
     namedWindow("Image1");
     imshow("Image1",image1);
    
     waitKey(0);
    }
    
  3. Memory Management:
  4. OpenCV is based on C. As such, every time you allocate a chunk of memory you will have to release it again. If you have a loop in your code where you allocate a chunk of memory in that loop and forget release it afterwards, you will get what is called a “leak”. This is where the program will use a growing amount of memory until it crashes from no remaining memory. Due to the high-level nature of Matlab, it is “smart” enough to automatically allocate and release memory in the background.

Sunday, 3 January 2016

Introduction to OpenCV

OpenCV stands for Open Source Computer Vision. It contains a library of programming functions for real time computer vision applications.Originally developed by Intel and now supported by Willow Garage.


It has C++, C, Python and Java interfaces and supports Windows, Linux, Mac OS, iOS and Android.

Goal : To provide a simple-to-use computer vision infrastructure that helps people build fairly sophisticated vision applications quickly.

Since its alpha release in January 1999, OpenCV has been used in many applications,products, and research efforts. These applications include stitching images together in satellite and web maps, medical image noise reduction, objectanalysis, security and intrusion detection systems, automatic monitoring and safety systems etc.

For more information refer : http://opencv.org/