## Friday, December 21, 2007

### OpenCV: image rotate and zoom (rotation, zoom in and zoom out)

#include "cv.h"#include "highgui.h"#include "math.h"int main( int argc, char** argv ){    IplImage* src = cvLoadImage("lena.jpg", 1);        IplImage* dst = cvCloneImage( src );    int delta = 1;    int angle = 0;    int opt = 1;   // 1： rotate & zoom                   // 0:  rotate only    double factor;    cvNamedWindow("src", 1);    cvShowImage("src", src);    for(;;)    {        float m[6];        CvMat M = cvMat(2, 3, CV_32F, m);        int w = src->width;        int h = src->height;        if(opt)              factor = (cos(angle*CV_PI/180.) + 1.05) * 2;        else             factor = 1;        m[0] = (float)(factor*cos(-angle*2*CV_PI/180.));        m[1] = (float)(factor*sin(-angle*2*CV_PI/180.));        m[3] = -m[1];        m[4] = m[0];        m[2] = w*0.5f;          m[5] = h*0.5f;                  cvGetQuadrangleSubPix( src, dst, &M);        cvNamedWindow("dst", 1);        cvShowImage("dst", dst);        if( cvWaitKey(1) == 27 )            break;        angle =(int)(angle + delta) % 360;    }         return 0;}

1. interesting psychedelic zoom.

2. Anonymous10:27 AM

hey,

i want to rotate a square ... similar to it ... how can i do that in opencv, do you have any idea? so write it down here ...
thanks a lot

3. I really like the code.But I just need the code for simple rotation.It will be very kind if you can also explain the code.
Regards. :D

4. No sure why angle is timed with 2*PI
Shouldn't it be PI? (if you mean angle is the angle in degree for the rotation).

5. Anonymous9:04 AM

Kun is right, I tested the code using 'angle times PI' and got the expected result!

6. Anonymous1:00 PM

The factor that multiplies PI just adjusts the speed of the rotation

7. This is a nice tutorial... however the cvQuadrangleSubPix interpolates the outlier pixels too... If you want to leave any outliers black, you can consider using the cvRemap function

8. Anonymous9:50 AM

void rotationImg()
{
CvMat* rot_mat = cvCreateMat(2,3,CV_32FC1);

IplImage* dst = cvCreateImage(cvSize(src->width,src->height), src->depth, src->nChannels);
CvPoint2D32f center = cvPoint2D32f(
src->width/2,
src->height/2
);
double angle = -50.0;
double scale = 0.6;
cv2DRotationMatrix( center, angle, scale, rot_mat );

cvWarpAffine( src, dst, rot_mat );
cvNamedWindow( "Affine_Transform", 1 );
cvShowImage( "Affine_Transform", dst );
cvWaitKey();