Life2Coding
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 picturen"<<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:
 
Straightening%2Bthe%2Bimage Straight the Disoriented Image using OpenCV
life2coding_icon [] Straight the Disoriented Image using OpenCV

One thought on “Straight the Disoriented Image using OpenCV

  1. Pragati

    I want to straightening the picture without mouse. In my case i want to straighten image automatically…….specially want to straighten rectangle is that possible…..i am new to opencv cpp any help will be appreciate thanks in advance.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.