Saturday, June 27, 2015

Simple Canny Edge Detection with Trackbar

Canny Edge Detection in OpenCV:

In this tutorial you will learn how to use the OpenCV function Canny to implement the Canny Edge Detector.

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

 using namespace cv;
 int thresh=10;
 Mat gray_image, canny_image;

 void trackChange(int, void*);
int main()
{
    Mat img_rgb = imread( "c:/apple.jpg" );

    cvtColor( img_rgb, gray_image, CV_BGR2GRAY);
    namedWindow( "Gray Window", CV_WINDOW_AUTOSIZE );
    namedWindow( "Canny Window", CV_WINDOW_AUTOSIZE );

    createTrackbar("Threshold","Canny Window",&thresh,255,trackChange);
    trackChange(0,0);
    imshow( "Gray Window", gray_image ); //ksjdhfklashdfklhaskldhfklahskldfhkladshklfhsklahdfklhaskldhfklashdklfhsklafhklahfklhaklfhlkahfklhaklfhklahfklhaklfhlkashdflahs

    waitKey(0);
    return 0;
}

void trackChange(int, void*)
{
    Canny( gray_image, canny_image, 10, thresh, 3, true );
    imshow( "Canny Window", canny_image );
}
Output: 
Canny edge detection


OpenCV Simple Motion Detection

Basic motion detection in OpenCV:

Suppose there are 2 images and the images are in a linear subsequence with some delay t between them. If we would compare every pixel of the 2 images, and we notice they’re all the same, we can conclude the 2 images are identical. But if they don't match with each other, then we could say that there happened something between the time interval.This reveals the idea of motion detection in OpenCV.

Code:
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;
int main()
{
    int erosion_size=5;
    Mat frame1,frame2;
    Mat grayImage1,grayImage2;
    Mat differnceImage;
    Mat thresholdImage;
    namedWindow("Webcam Video");
   //default webcam device id=0;

    //check if the webcam was opened properly
    Mat element = getStructuringElement( MORPH_RECT,Size( 2*erosion_size + 1, 2*erosion_size+1 ),Point( erosion_size, erosion_size ) );

    VideoCapture cap(0);

    while (1)
    {
        //  cap.open(0);
         if(!cap.isOpened())
         {
             cout<<"Webcam can't be opened"<<endl;
             getchar();
             return -1;
         }

            cap.read(frame1);
            cvtColor(frame1,grayImage1,CV_RGB2GRAY);

            cap.read(frame2);
            cvtColor(frame2,grayImage2,CV_RGB2GRAY);

           absdiff(grayImage1,grayImage2,differnceImage);
           threshold(differnceImage,thresholdImage,5,255,CV_THRESH_BINARY);
            blur(thresholdImage,thresholdImage,Size(30,30));
             threshold(differnceImage,thresholdImage,5,255,CV_THRESH_BINARY);
            erode(thresholdImage,thresholdImage,element,Point(-1,-1));
             imshow("Theshold",thresholdImage);

           imshow("Webcam Video",frame1);

           switch(waitKey(10))
           {
           case 27:
               return -1;
               break;

           }


   }
}
Output:

Simple motion detection in opencv
 

Monday, June 15, 2015

OpenCV Extract Contour for Using with The Desired Image

Find biggest contour using Opencv:

An example to find largest contour from the input image. A contour can be considered as a sequence of points that define a specific object in an image. To get the contours from image we have to convert it to gray scale and then apply the findContours() funcion. After finding the required contours extra coding is required to get the largest contour. The code given below will do the job.

Code:

/*
 * extract the largest contour and use a background
 */

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include "iostream"
using namespace cv;

int main()
{
    Mat img1;
    namedWindow("Detected");
    double largest_area=0;
    int contour_index=0;
    Rect bounding_rect;
    Mat img = imread("c:/open/ok.jpg");

    if ( img.empty() )
    {
       return -1;
    }
    cvtColor(img,img1,CV_RGB2GRAY);
    Canny(img1,img1,200,255);
    namedWindow("Canny");
    imshow("Canny",img1);


    std::vector< std::vector<cv::Point> > contours;
    std::vector<cv::Vec4i>hierarcy;

    findContours(img1,contours,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);

    //  Mat mask=Mat::zeros(img.cols,img.rows,CV_8UC1);  //alternative way: below line
    Mat mask(img.cols,img.rows,CV_8UC1,Scalar::all(0));

    for(int i=0;i<contours.size();i++)
    {
        double area=contourArea(contours[i],false);

        //finding out the largest area
        if(area>largest_area)
        {
            largest_area=area;
            contour_index=i;
           bounding_rect= boundingRect(contours[i]); //the largest contour rectangle
        }
    }
    drawContours(mask,contours,contour_index,Scalar(255),CV_FILLED);

    namedWindow("Mask");
    imshow("Mask",mask);

   //Mat newimg( img.cols,img.rows,CV_8UC3,Scalar(30,29,140));
   Mat newimg=imread("c:/open/me2.jpg"); //use your own pic of the same size as the source image
    img.copyTo(newimg,mask);
     normalize(mask.clone(), mask, 0.0, 255.0, CV_MINMAX, CV_8UC1);

    rectangle(img,bounding_rect,Scalar(244,33,54),2);
    imshow("Detected",img);
    namedWindow("Output");
    imshow("Output",newimg);
    waitKey(0);
    return 0;
}

Output: 

 

Sunday, June 14, 2015

Working with Trackbar in OpenCV

Thresholding of image using trackbar:

In this example, we will learn the usage of trackbar in opencv. We can implement any type of value change functionality with this code.

Code:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
int value;
 Mat src;
const int max_Value=255;

void on_trackbar(int p,void*)
{
    Mat gray,thresh;
    cvtColor(src,gray,CV_BGR2GRAY);
    threshold(gray,thresh,p,max_Value,CV_THRESH_BINARY);
    namedWindow("Thresh");
    imshow("Thresh",thresh);

}

int main( int argc, char** argv )
{



    src = imread("c:/me1.jpg", CV_LOAD_IMAGE_COLOR);   // open colour image

    if(! src.data )                              // Check input image
    {
        std::cout <<  "No image found" << std::endl ;
        return -1;
    }


    namedWindow( "Window", WINDOW_AUTOSIZE );// Create a window for display.
    imshow( "Window", src );                   // Show our image inside it.
    createTrackbar("Threshold","Window",&value,max_Value,on_trackbar);
    waitKey(0);                                          // Waiting for a keystroke to keep the screen visible
    return 0;
}

Output:
Thresholding of image using trackbar

Straight the Disoriented Image using OpenCV

Straightening the picture with mouse :
 
Sometime it requires to rotate the image by some angle and this could be done in OpenCV. In this example, we illustrate the straightening of image using the wrapAffine function of openCV.


Code:
 
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cmath>
#include <iostream>

using namespace cv;

Mat originalImage, sourceImage;
std::vector<Point> pt;

void straighten_image(std::vector<Point> pt)
{
    double angle = std::atan((double)(pt[0].y - pt[1].y) /
                                     (pt[0].x - pt[1].x)) *
                                     (180 / CV_PI);

    Point2f center(originalImage.cols/2., originalImage.rows/2.);
    Mat destinationImage, element = getRotationMatrix2D(center, angle, 1.0);
    warpAffine(originalImage, destinationImage,element, originalImage.size());
    imshow("Destination", destinationImage);
    imwrite("Source.jpg", sourceImage);
    imwrite("destination.jpg", destinationImage);
}

void on_mouseClick(int event, int x, int y, int flags, void* param)
{
    if (event == CV_EVENT_LBUTTONDOWN)
    {
        switch (pt.size())
        {
            case 0:
                pt.push_back(Point(x,y));
                break;
            case 1:
                pt.push_back(Point(x,y));
                straighten_image(pt);
                break;
            case 2:
                sourceImage = originalImage.clone();
                pt.clear();
                break;
        }
    }
    else if (event == CV_EVENT_MOUSEMOVE && pt.size() == 1)
    {
        sourceImage = originalImage.clone();
        line(sourceImage, pt[0], Point(x,y), CV_RGB(0,0,255), 2);
    }

    if (sourceImage.data)
        imshow("Source", sourceImage);
}

int main()
{
    originalImage = imread("c:/me.jpg");
    if (!originalImage.data)
    {
        std::cout << "Error loading the image!" << std::endl;
        return -1;
    }
    std::cout<<"Draw a line to straighten the picture\n"<<std::endl;
    std::cout <<"Presh 'q' to quit"<<std::endl;
    namedWindow("Source", CV_WINDOW_AUTOSIZE);
    setMouseCallback("Source", on_mouseClick, 0);
    putText(originalImage, "Click on the picture to straight it", Point(10,45), CV_FONT_HERSHEY_COMPLEX_SMALL,1, CV_RGB(000,250,0));
    imshow("Source", originalImage);

    //press 'q' to quit

    while(1)
    {
        if (char(waitKey(10))=='q')
        break;
    }

    return 0;
}

Output:
 

Thursday, June 11, 2015

Save Webcam Video to a File

Write webcam video to file:

In this example a VideoCapture object is used to capture the webcam video to frames then a VideoWriter object is used to write frames to file. The constructor of this class requires output filename, codecs, frames per second, size of frames.

Code:

#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

int main (int argc, char *argv[])
{
    // Open the default camera
    VideoCapture capture(0);

    // Check if the camera was opened
    if(!capture.isOpened())
    {
        cerr << "Could not open camera";
        return -1;
    }

    // Get the properties from the camera
    double width = capture.get(CV_CAP_PROP_FRAME_WIDTH);
    double height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);

    cout << "width = " << width << endl <<"height = "<< height << endl;

    // Create a matrix to keep the retrieved frame
    Mat frame;

    // Create a window to show the image
    namedWindow ("Window", CV_WINDOW_AUTOSIZE);

    //  -1 specify as the FourCC code, and a window will pop up displaying all of the available video codecs that are on your computer.


    // Create the video writer

    VideoWriter video("c:/capture.avi",-1, 30, Size((int)width,(int)height) );

  //  VideoWriter video("c:/capture.avi",CV_FOURCC('I','Y','U','V'), 30, Size((int)width,(int)height) );

    // Check if the video was opened
    if(!video.isOpened())
    {
        cerr << "Could not create video.";
        return -1;
    }

    cout << "Press 'q' stop recording." << endl;

    // Get the next frame until the user presses the escape key
    while(char(waitKey(1))!='q')
    {
        // Get frame from capture
        capture >> frame;

        // Check if the frame was retrieved
        if(!frame.data)
        {
            cerr << "Could not retrieve frame.";
            return -1;
        }

        // Save frame to video
        video << frame;

        // Show image
        imshow("Window", frame);


    }

    // Exit
    return 0;
}

Output:

Write webcam video to file

 

Displaying Webcam Video

Displaying the frames of webcame using videocapture:

In this tutorial, I am going to take video output from the webcam. The opencv handles it quite easily with FFMPEG support. The code shown below will take the videos directly from the webcam and display it in the window.

Code:


#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;
int main()
{
    namedWindow("Webcam Video");
   VideoCapture cap(0); //default webcam device id=0;

    //check if the webcam was opened properly
    if(!cap.isOpened())
    {
        cout<<"Webcam can't be opened"<<endl;
    }
    while(cap.isOpened())
    {
        Mat frame;
        cap>>frame;
        imshow("Webcam Video",frame);
        //if q is pressed then it will stop
        if(char (waitKey(1))=='q')
        {
            break;
        }
    }
}

Output:

Displaying webcam video using Opencv

 

Cropping the Image using Mouse

Selecting a region of interest of an image with mouse:

A region of interest is a region of the image where we are interested and the processing is done on that region. We can easily take the small portion of the image and do the processing in that part instead of processing the whole image. It is used mainly in cases in which the image is too large and all parts of it.
          Usually a ROI is specified as a rectangle. In OpenCV a rectangular ROI is specified using a rectstructure.

Code:

 

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>


using namespace cv;
using namespace std;

bool leftDown=false,leftup=false;
Mat img;
Point cor1,cor2;
Rect box;



void mouse_call(int event,int x,int y,int,void*)
{
    if(event==EVENT_LBUTTONDOWN)
    {
        leftDown=true;
        cor1.x=x;
        cor1.y=y;
       cout <<"Corner 1: "<<cor1<<endl;

    }
    if(event==EVENT_LBUTTONUP)
    {
        if(abs(x-cor1.x)>20&&abs(y-cor1.y)>20) //checking whether the region is too small
        {
            leftup=true;
            cor2.x=x;
            cor2.y=y;
            cout<<"Corner 2: "<<cor2<<endl;
        }
        else
        {
            cout<<"Select a region more than 20 pixels"<<endl;
        }
    }

    if(leftDown==true&&leftup==false) //when the left button is down
    {
        Point pt;
        pt.x=x;
        pt.y=y;
        Mat temp_img=img.clone();
        rectangle(temp_img,cor1,pt,Scalar(0,0,255)); //drawing a rectangle continuously
        imshow("Original",temp_img);

    }
    if(leftDown==true&&leftup==true) //when the selection is done
    {

        box.width=abs(cor1.x-cor2.x);
        box.height=abs(cor1.y-cor2.y);
        box.x=min(cor1.x,cor2.x);
        box.y=min(cor1.y,cor2.y);
        Mat crop(img,box);   //Selecting a ROI(region of interest) from the original pic
        namedWindow("Cropped Image");
        imshow("Cropped Image",crop); //showing the cropped image
        leftDown=false;
        leftup=false;

    }


}

int main()
{
   img=imread("c:/open/me.jpg");
   namedWindow("Original");
   imshow("Original",img);

   setMouseCallback("Original",mouse_call); //setting the mouse callback for selecting the region with mouse

   while(char(waitKey(1)!='q')) //waiting for the 'q' key to finish the execution
   {

   }
   return 0;
} 

Output:

Selecting region of interest with mouse

 

Thursday, June 04, 2015

Loading and Displaying Images using OpenCV

Read image file and display

The code shows the procedures to import an image from file using the Opencv library.For this, open the C++ IDE ( like Qt Creator, Visual Studio C++, Codeblocks etc) and create a new project. The IDE has to be configured for running the opencv functions. 

Code:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
int main( int argc, char** argv )
{
    Mat src;
    src = imread("c:/open/me.jpg", CV_LOAD_IMAGE_COLOR);   // open colour image

    if(! src.data )                              // Check input image
    {
        std::cout <<  "No image found" << std::endl ;
        return -1;
    }

    namedWindow( "Window", WINDOW_AUTOSIZE );// Create a window for display.
    imshow( "Window", src );                   // Show our image inside it.

    waitKey(0);                                          // Waiting for a keystroke to keep the screen visible
    return 0;
}

Output:

Read image file and display