In this tutorial, we will rotate an Image at 45, 90 & 180 degrees using OpenCV in C++. Opencv is a library that contains multiple computer-vision libraries, used for real-time computer vision.
Requirements:
To get started you need to install OpenCV in your system. You can follow the OpenCV documentation to install it into your system.
Code:
To rotate the image at 45 degrees:
#include <opencv2/opencv.hpp>
int main() {
// Read the image
cv::Mat image = cv::imread("image.jpg");
// Check if the image is loaded successfully
if(image.empty()) {
std::cerr << "Error: Could not read the image." << std::endl;
return -1;
}
// Define rotation angle (in degrees)
double angle = 45.0;
// Get rotation matrix
cv::Point2f center(static_cast<float>(image.cols) / 2, static_cast<float>(image.rows) / 2);
cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, angle, 1.0);
// Rotate the image
cv::Mat rotatedImage;
cv::warpAffine(image, rotatedImage, rotationMatrix, image.size());
// Display the rotated images
cv::imshow("Rotated Image", rotatedImage);
cv::waitKey(0);
return 0;
}
To rotate the image at 90 degrees:
#include <opencv2/opencv.hpp>
int main() {
// Read the image
cv::Mat image = cv::imread("image.jpg");
// Check if the image is loaded successfully
if(image.empty()) {
std::cerr << "Error: Could not read the image." << std::endl;
return -1;
}
cv::Mat rotated;
cv::rotate(image, rotated, cv::ROTATE_90_CLOCKWISE);
// Display the original and rotated images
cv::imshow("Rotated Image", rotated);
cv::waitKey(0);
return 0;
}
To rotate the image at 180 degrees:
#include <opencv2/opencv.hpp>
int main() {
// Read the image
cv::Mat image = cv::imread("image.jpg");
// Check if the image is loaded successfully
if(image.empty()) {
std::cerr << "Error: Could not read the image." << std::endl;
return -1;
}
cv::Mat rotated;
cv::rotate(image, rotated, cv::ROTATE_180);
// Display the original and rotated images
cv::imshow("Rotated Image", rotated);
cv::waitKey(0);
return 0;
}
Output:
Original Image:

Rotated at 45 degrees:

Rotated at 90 degrees:

Rotated at 180 degrees:
