图像中某点绕点旋转后的坐标,图像旋转坐标位置

图像中某点绕点旋转后的坐标,图像旋转坐标位置

    在平面坐标上,任意点P(x1,y1),绕一个坐标点Q(x2,y2)旋转θ角度后,新的坐标设为(x, y)的计算公式:
  1. x= (x1 - x2)*cos(θ) - (y1 - y2)*sin(θ) + x2 ;
  2. y= (x1 - x2)*sin(θ) + (y1 - y2)*cos(θ) + y2 ;
这是在平面上的坐标旋转公式,但在图像中某个像素点旋转一个角度后的坐标不能用上述公式直接求出,因为图像(0,0)点的坐标的原点是在图像的左上角。
    假设图像的宽度x高度为col x row,图像中某个像素P(x1,y1),绕某个像素点Q(x2,y2)旋转θ角度后,则该像素点的新坐标位置为(x, y),其计算公式为:
  1. x1 = x1;
  2. y1 = row - y1;
  3. x2 = x2;
  4. y2 = row - y2;
  5. x = (x1 - x2)*cos(pi / 180.0 * θ) - (y1 - y2)*sin(pi / 180.0 * θ) + x2;
  6. y = (x1 - x2)*sin(pi / 180.0 * θ) + (y1 - y2)*cos(pi / 180.0 * θ) + y2;
  7. x=x;
  8. y = row - y;
下面给出OpenCV的实现代码:原图像的大小500x577,像素点P(100,100),绕图像中心Q(250,288.5)旋转θ角度后,则该像素点的新坐标位置为(173, 60)
   关于OpenCV实现图像旋转的方法,可参考本人的博客:《OpenCV图像旋转,指定填充背景颜色边界颜色》 http://blog.csdn.net/guyuealian/article/details/77993410
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include<vector>
  4. #include<algorithm>
  5. #include <opencv2\opencv.hpp>
  6. #include <opencv2\highgui\highgui.hpp>
  7. using namespace std;
  8. using namespace cv;
  9. #define pi 3.1415926
  10. vector<cv::Point2i> getRotatePoint(cv::Mat srcImage, vector<cv::Point2i> Points, const cv::Point rotate_center, const double angle) {
  11. vector<cv::Point2i> dstPoints;
  12. int x1 = 0, y1 = 0;
  13. int row = srcImage.rows;
  14. for (size_t i = 0; i < Points.size(); i++)
  15. {
  16. x1 = Points.at(i).x;
  17. y1 = row - Points.at(i).y;
  18. int x2 = rotate_center.x;
  19. int y2 = row - rotate_center.y;
  20. int x = cvRound((x1 - x2)*cos(pi / 180.0 * angle) - (y1 - y2)*sin(pi / 180.0 * angle) + x2);
  21. int y = cvRound((x1 - x2)*sin(pi / 180.0 * angle) + (y1 - y2)*cos(pi / 180.0 * angle) + y2);
  22. y = row - y;
  23. dstPoints.push_back(Point2i(x, y));
  24. }
  25. return dstPoints;
  26. }
  27. int main() {
  28. Mat src = imread("D:\\OpencvTest\\16.jpg");
  29. Point2i point(100, 100);
  30. vector<cv::Point2i> Points;
  31. Points.push_back(point);
  32. cv::circle(src, point, 2, cv::Scalar(255, 0, 0),2);
  33. cv::imshow("src image ", src);
  34. cv::Mat dst;
  35. //旋转角度-20度
  36. double angle =- 20;
  37. //输出图像的尺寸与原图一样
  38. cv::Size dst_sz(src.cols, src.rows);
  39. //指定旋转中心
  40. cv::Point2f center(src.cols / 2., src.rows / 2.);
  41. //获取旋转矩阵(2x3矩阵)
  42. cv::Mat rot_mat = cv::getRotationMatrix2D(center, angle, 1.0);
  43. //设置选择背景边界颜色:绿色
  44. cv::Scalar borderColor = Scalar(0, 238, 0);
  45. cv::warpAffine(src, dst, rot_mat, dst_sz, INTER_LINEAR, BORDER_CONSTANT, borderColor);
  46. //cv::warpAffine(src, dst, rot_mat, dst_sz, INTER_LINEAR, BORDER_REPLICATE);
  47. vector<cv::Point2i> dstPoints = getRotatePoint(dst, Points, center, angle);
  48. cv::circle(dst, dstPoints.at(0), 5, cv::Scalar(0, 0, 255), 2);
  49. cv::imshow("Rotation Image", dst);
  50. waitKey(0);
  51. return 0;
  52. }
展开阅读全文

没有更多推荐了,返回首页