Monday 18 January 2016

Opencv C++ Code for Rotating an Image with the help of a Trackbar

This OpenCV tutorial is about rotating an Image about its centre by varying the slider position on the Trackbar.
Refer the Opencv C++ Code below:

// OpenCV C++ Tutorial of Rotating an Image with the help of Trackbar
#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp> 
#include <iostream>

using namespace cv;
using namespace std;

//Global Variables
const int rotation_slider_max=360;
const float pi=3.14;
float x,y;
int slider_value=0;

/// Matrices to store images
Mat src1,src2;

void on_trackbar( int, void* )
{
 src2 = Mat::zeros(src1.rows,src1.cols, CV_8UC3);
 for (float i=0; i<src1.cols ; i++){
 for (float j=0 ; j<src1.rows ; j++)
 {
   x=((i-src1.cols/2)*cos(slider_value*pi/180)-(j-src1.rows/2)*sin(slider_value*pi/180)+src1.cols/2);
   y=((i-src1.cols/2)*sin(slider_value*pi/180)+(j-src1.rows/2)*cos(slider_value*pi/180)+src1.rows/2);

   if((x>=0 && x<src1.cols) && (y>=0 && y<src1.rows)){
        Vec3b color1 = src1.at<Vec3b>(Point(i,j));
        Vec3b color2 = src2.at<Vec3b>(Point(i,j));
      color2.val[0] = color1.val[0];
      color2.val[1] = color1.val[1];
      color2.val[2] = color1.val[2];
      src2.at<Vec3b>(Point(x,y)) = color2;
   }
    }
 }
 imshow("Rotated Image", src2); 
}

int main()
{
 src1 = imread("C:\\Users\\arjun\\Desktop\\opencv-logo.png",CV_LOAD_IMAGE_COLOR);
 if( !src1.data ) { printf("Error loading src1 \n"); return -1;}

 namedWindow("Rotated Image",CV_WINDOW_AUTOSIZE); 
    namedWindow("Original Image",CV_WINDOW_AUTOSIZE); 
    imshow("Original Image", src1);

 createTrackbar( "Rotation", "Rotated Image", &slider_value, rotation_slider_max, on_trackbar );
 on_trackbar( slider_value, 0 );
 waitKey(0);
 return 0;
}

No comments:

Post a Comment