OpenCV-based image rotation --------- achieve

This code is the use of the nearest neighbor algorithm based on OpenCV (OpenCV3.4.0 with vs2017) to achieve image rotation, image rotation using the nearest neighbor algorithm to achieve the effect is not very good, but the use of the basic idea is to do it, and I use the photos are classic photos of digital image processing (baby.bmp), inability to upload to the internet, you can also use .jpg picture, but the effect is not very good. Here is a concrete realization of the process, and the results map:

#include<iostream>
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
using namespace cv;
using namespace std;
int main()
{
	  //read image
		Mat input_img = imread("C:\\Users\\ASUS\\Pictures\\Camera Roll\\baby.bmp");
		double angle = 0.0;
		cout << "please input angle:" << endl;
		cin >> angle;
		double image_high = input_img.rows;		//图像宽度
		double image_width = input_img.cols * input_img.channels();	//图像高度
		int Nrows = input_img.rows;					//图像行数
		int Ncols = input_img.cols * input_img.channels();			//图像列数
        Mat output_img(Nrows, Ncols , CV_64FC3);
		if (!input_img.data)
		{
			cout << "There is no data!" << endl;
		}
		uchar *data1;	//指向图像矩阵的指针
		uchar *data2;
		Mat Dst_img(input_img.rows, input_img.cols, input_img.type(), Scalar::all(0));	//旋转后图像存储地址

	double Xvar = -0.5*image_high*cos(angle) + 0.5*image_width*sin(angle) + 0.5*image_high;	//X轴
	double Yvar = -0.5*image_high*sin(angle) - 0.5*image_width*cos(angle) + 0.5*image_width;	//Y轴

	int i = 0, j = 0;						
	for (i = 0; i < Nrows; i++)
	{
		data1 = input_img.ptr<uchar>(i);
		data2 = Dst_img.ptr<uchar>(i);
		for (j = 0; j < Ncols; j++)
		{
			//最近邻插值算法
			int X1 = static_cast<int>((double)i*cos(angle) - (double)j*sin(angle) + Xvar + 0.5);
			int Y1 = static_cast<int>((double)i*sin(angle) + (double)j*cos(angle) + Yvar + 0.5);
			if ((X1 >= 0) && (X1 < Nrows) && (Y1 >= 0) && (Y1 < Ncols))
			{
				data2 = Dst_img.ptr<uchar>(X1);
				data2[Y1] = data1[j];
			}
		}
	}
	Dst_img.copyTo(output_img);
	//创建一个显示窗口	
    namedWindow("原图");
	imshow("原图", input_img);
     namedWindow("结果图");
	imshow("结果图", output_img);
	waitKey(0);
return 0;

}
Run Results:
Here Insert Picture Description

Published 16 original articles · won praise 18 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_37554556/article/details/88900494