Rotate Image
Rotating images by a given angle is a common image processing task. Although it seems little bit complicated, OpenCV provides some built-in functions making it easy to do it. Here is a simple OpenCV C++ example code to rotate an image. Here I use a track bar to change the rotating angle dynamically.////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
int main( int argc, char** argv )
{
// Load the image
Mat imgOriginal = imread( "MyPic.JPG", 1 );
//show the original image
const char* pzOriginalImage = "Original Image";
namedWindow( pzOriginalImage, CV_WINDOW_AUTOSIZE );
imshow( pzOriginalImage, imgOriginal );
const char* pzRotatedImage = "Rotated Image";
namedWindow( pzRotatedImage, CV_WINDOW_AUTOSIZE );
int iAngle = 180;
createTrackbar("Angle", pzRotatedImage, &iAngle, 360);
int iImageHieght = imgOriginal.rows / 2;
int iImageWidth = imgOriginal.cols / 2;
while (true)
{
Mat matRotation = getRotationMatrix2D( Point(iImageWidth, iImageHieght), (iAngle - 180), 1 );
// Rotate the image
Mat imgRotated;
warpAffine( imgOriginal, imgRotated, matRotation, imgOriginal.size() );
imshow( pzRotatedImage, imgRotated );
int iRet = waitKey(30);
if ( iRet == 27 )
{
break;
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
You can download this visual C++ project from here.
![]() |
Original Image |
![]() |
Rotated Image |
Explanation
Here is the explanation for new OpenCV functions which are not found in previous lessons.
- Mat getRotationMatrix2D( Point2f center, double angle, double scale )
This function returns 2x3 affine transformation matrix for the 2D rotation.
Arguments -
- center - The center of the rotation of the the source image.
- angle - Angle of rotation in degrees (Positive values for counter-clockwise direction and negative values for clockwise rotation)
- scale - The scaling factor of the image. (Scaling factor of 1 means its original size)
Try different values for center, angle and scale and observe the output image.
- void warpAffine( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int bordreMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar() )
This OpenCV function applies affine transformation to an image.
Arguments -
- src - Source Image
- dst - Destination image which should have the same type as the source image(The transformed image is stored in this location)
- M - 2x3 affine transformation matrix
- dsize - Size of the destination image
- flags - Interpolation methods
- borderMode - pixel extrapolation method. (Try these values; BORDER_REPLICATE, BORDER_CONSTANT, BORDER_REFLECT, BORDER_WRAP, BORDER_REFLECT_101, BORDER_TRANSPARENT and BORDER_ISOLATED)
- borderValue - If you use BORDER_CONSTANT for borderMode, this argument define the value used for the border
Another OpenCV Example to Rotate an Image
Here is another way to rotate an image. Here I use a callback function to apply the rotation instead of using a infinite while loop. Other than the rotation, you can change the scale of the image and border extrapolation method dynamically.
Here is the OpenCV C++ code.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
int iAngle = 180;
int iScale = 50;
int iBorderMode = 0;
Mat imgOriginal ;
int iImageCenterY = 0;
int iImageCenterX = 0;
const char* pzRotatedImage = "Rotated Image";
void CallbackForTrackBar(int, void*)
{
Mat matRotation = getRotationMatrix2D( Point( iImageCenterX, iImageCenterY ), (iAngle - 180), iScale / 50.0 );
// Rotate the image
Mat imgRotated;
warpAffine( imgOriginal, imgRotated, matRotation, imgOriginal.size(), INTER_LINEAR, iBorderMode, Scalar() );
imshow( pzRotatedImage, imgRotated );
}
int main( int argc, char** argv )
{
// Load the image
imgOriginal = imread( "MyPic.JPG", 1 );
iImageCenterY = imgOriginal.rows / 2;
iImageCenterX = imgOriginal.cols / 2;
//show the original image
const char* pzOriginalImage = "Original Image";
namedWindow( pzOriginalImage, CV_WINDOW_AUTOSIZE );
imshow( pzOriginalImage, imgOriginal );
//create the "Rotated Image" window and 3 trackbars in it
namedWindow( pzRotatedImage, CV_WINDOW_AUTOSIZE );
createTrackbar("Angle", pzRotatedImage, &iAngle, 360, CallbackForTrackBar);
createTrackbar("Scale", pzRotatedImage, &iScale, 100, CallbackForTrackBar);
createTrackbar("Border Mode", pzRotatedImage, &iBorderMode, 5, CallbackForTrackBar);
int iDummy = 0;
CallbackForTrackBar(iDummy, &iDummy);
waitKey(0);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
You can download this visual C++ project from here.
![]() |
Rotated Image which is down-scaled and whose border values have been extrapolated |
All the OpenCV functions have been discussed previously.
Rotate a Video
Rotating a video is also simple. The code is just like the 1st example in this lesson. Here is the OpenCV C++ code.///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char* argv[])
{
// open the video file for reading
VideoCapture cap("C:/Users/SHERMAL/Desktop/MyVideo.mp4");
// if not success, exit program
if ( !cap.isOpened() )
{
cout << "Cannot open the video file" << endl;
return -1;
}
const char* pzOriginalWindowName = "Original Video";
namedWindow(pzOriginalWindowName, CV_WINDOW_AUTOSIZE);
const char* pzRotatingWindowName = "Rotated Video";
namedWindow( pzRotatingWindowName, CV_WINDOW_AUTOSIZE );
int iAngle = 180;
createTrackbar("Angle", pzRotatingWindowName, &iAngle, 360);
while (true)
{
Mat matOriginalFrame;
// read a new frame from video
bool bSuccess = cap.read(matOriginalFrame);
//if not success, break loop
if (!bSuccess)
{
cout << "Cannot read the frame from video file" << endl;
break;
}
imshow(pzOriginalWindowName, matOriginalFrame);
//get the affine transformation matrix
Mat matRotation = getRotationMatrix2D( Point(matOriginalFrame.cols / 2, matOriginalFrame.rows / 2), (iAngle - 180), 1 );
// Rotate the image
Mat matRotatedFrame;
warpAffine( matOriginalFrame, matRotatedFrame, matRotation, matOriginalFrame.size() );
imshow( pzRotatingWindowName, matRotatedFrame );
//wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
if (waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
You can download this visual C++ project from here.
All the OpenCV functions, found in the above example have been discussed earlier.
Next Tutorial : Object Detection & Tracking using Color
Previous Tutorial : How to Detect Mouse Clicks and Moves
I was always curious how designers do this with such mastery and quickness, and now thanks to you I can do this on my own.
ReplyDeleteGood read always prefer to read the quality content
ReplyDeletedr.web antivirus crack
ReplyDeletedaemon tools ultra serial key
screenhunter pro crack
macx video converter pro crack
goodsync crack
coolutils total pdf converter crack
goldwave crack
pgware gameswift crack
rekordbox dj crack
mindomo desktop crack
https://bluecracked.com/
ReplyDeleteVisit here
https://crackedskey.com/>
ReplyDeleteCrack Software Download Here
https://latestkeygen.com/
ReplyDeletePro Crack software Download
https://keysmod.com/
ReplyDeleteFull Version Cracked Software Download
https://pcgamespoint.com/
ReplyDeletePC Games 2021 Download here
360-total-security-crack
ReplyDeleteWe’re a group of volunteers and opening a new scheme in our community. Your web site provided us with valuable info to work on. You’ve done an impressive job and our entire community will be thankful to you.
ReplyDelete야설
바카라사이트
립카페
스포츠마사지
출장마사지
I really appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thanks again! 스포츠토토
ReplyDeleteCum să cumpărați permisul de conducere online în 5 până la 7 zile fără examene
ReplyDeletecumpăra permis de conducere
cumpărați permisul conducere online
cumpara permis conducere romanesc
cumpăra permis conducere înregistrat
cumpăra permis conducere România
Comprar carnet de conducir en nuestra web inscrito en el Dgt en un plazo de 5 a 7 días hábiles sin exámenes y podrá conducir libremente en España y otros países sin ningún problema señor
ReplyDeleteComprar Licencia de Conducir
Comprar Carnet de Conducir
Comprar Licencia Conducir Legal
Comprar carnet de conducir
comprar licencias de conducir
comprar carnet conducir dgt
comprar licencia de conducir
Acquista la patente di guida sul nostro sito Web valida nel sistema di database senza esami entro 5-7 giorni lavorativi
ReplyDeletecomprare patente
acquisti la patente guida
come acquistare patente guida
kup prawo jazdy
Comprar Carta de Condução
acheter permis de conduire
köp körkort
acquiste patente di guida
Führerschein in Deutschland im Datenbanksystem registriert ohne Prüfungen innerhalb von 5 bis 7 Werktagen kaufen
ReplyDeleteFührerschein kaufen
eu führerschein kaufen
registrierten Führerschein kaufen
echten führerschein kaufen
deutschen Führerschein kaufen
führerschein kaufen legal
Comprar carta conducao online sem exames no prazo de 5 a 7 dias úteis válido no imt de portugal
ReplyDeleteComprar Carta Condução
carta condução mota
kjøpe førerkort
buy UK driver's license
Comprar Carta de Condução
Carta de Condução Preços
Comprar Carta Condução Verdadeira
Comprar Carta de Mota
oncasino
ReplyDeleteAn intriguing discussion may be worth comment. I’m sure you should write much more about this topic, may well be described as a taboo subject but generally folks are too little to chat on such topics. An additional. Cheers 토토사이트
ReplyDeleteoncasino
ReplyDeleteI like the helpful info you provide in your articles. I’ll bookmark your blog and check again here frequently. I’m quite sure I’ll learn plenty of new stuff right here! Good luck for the next. 스포츠토토
ReplyDeleteIt's a really interesting topic and it has helped me a lot. In fact, I also run a website with similar content to your posting. Please visit once 바카라검증사이트
ReplyDelete