Sunday, June 14, 2015

Straight the Disoriented Image using OpenCV

Posted by Md.Hanif Ali on Sunday, June 14, 2015 in | No comments
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:
 

0 comments:

Post a Comment