Please generate C++ code that will rotate an input image by 90 degrees clockwise.
Please generate C++ code that will rotate an input image by 90 degrees clockwise.
Rotating an image by 90 degrees clockwise typically involves swapping pixels' positions within the image matrix. Here's a C++ code snippet using the OpenCV library to achieve this. Ensure you have OpenCV installed and properly configured in your C++ environment for this code to work.
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Load the input image
Mat inputImage = imread("input_image.jpg");
// Check if the image was loaded successfully
if (inputImage.empty()) {
cout << "Error: Unable to load the input image!" << endl;
return -1;
}
// Rotate the image 90 degrees clockwise
Mat rotatedImage;
transpose(inputImage, rotatedImage);
flip(rotatedImage, rotatedImage, 1);
// Display and save the rotated image
imshow("Rotated Image", rotatedImage);
imwrite("rotated_image.jpg", rotatedImage);
// Wait for a key press and close the OpenCV window
waitKey(0);
destroyAllWindows();
return 0;
}
Explanation of the code:
We include the necessary OpenCV headers for image manipulation and IO.
Load the input image using the
imread
function. Replace"input_image.jpg"
with the path to your input image.Check if the image was loaded successfully. If not, display an error message and exit.
Rotate the image 90 degrees clockwise using the
transpose
andflip
functions. Thetranspose
function swaps rows and columns, and theflip
function flips the image horizontally (1 indicates horizontal flip).Display the rotated image using
imshow
.Save the rotated image using
imwrite
.Wait for a key press and close the OpenCV window using
waitKey
anddestroyAllWindows
.
Make sure to adjust the input and output image paths as needed and ensure that OpenCV is properly set up in your development environment for this code to work.