在C ++中的OpenCV中旋转图像而不裁剪 [英] Rotate an image without cropping in OpenCV in C++

查看:1723
本文介绍了在C ++中的OpenCV中旋转图像而不裁剪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想旋转图片,但无法裁剪图片。

I'd like to rotate an image, but I can't obtain the rotated image without cropping

我的原始图片:

>

现在我使用这个代码:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

// Compile with g++ code.cpp -lopencv_core -lopencv_highgui -lopencv_imgproc

int main()
{
    cv::Mat src = cv::imread("im.png", CV_LOAD_IMAGE_UNCHANGED);
    cv::Mat dst;

    cv::Point2f pc(src.cols/2., src.rows/2.);
    cv::Mat r = cv::getRotationMatrix2D(pc, -45, 1.0);

    cv::warpAffine(src, dst, r, src.size()); // what size I should use?

    cv::imwrite("rotated_im.png", dst);

    return 0;
}

并获取以下图片:

>

但我想获得此

非常感谢您的帮助!

推荐答案

我的答案受以下帖子/博客条目的启发:

My answer is inspired by the following posts / blog entries:

  • Rotate cv::Mat using cv::warpAffine offsets destination image
  • http://john.freml.in/opencv-rotation

主要想法:


  • 调整旋转矩阵通过向新图像中心添加翻译

  • 使用 cv :: RotatedRect 尽可能依靠现有的opencv功能

  • Adjusting the rotation matrix by adding a translation to the new image center
  • Using cv::RotatedRect to rely on existing opencv functionality as much as possible

使用opencv 2.4.8测试的代码:

Code tested with opencv 2.4.8:

#include "opencv2/opencv.hpp"

int main()
{
    cv::Mat src = cv::imread("im.png", CV_LOAD_IMAGE_UNCHANGED);
    double angle = -45;

    // get rotation matrix for rotating the image around its center
    cv::Point2f center(src.cols/2.0, src.rows/2.0);
    cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
    // determine bounding rectangle
    cv::Rect bbox = cv::RotatedRect(center,src.size(), angle).boundingRect();
    // adjust transformation matrix
    rot.at<double>(0,2) += bbox.width/2.0 - center.x;
    rot.at<double>(1,2) += bbox.height/2.0 - center.y;

    cv::Mat dst;
    cv::warpAffine(src, dst, rot, bbox.size());
    cv::imwrite("rotated_im.png", dst);

    return 0;
}

这篇关于在C ++中的OpenCV中旋转图像而不裁剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆