opencv之旋转图像

opencv中旋转图像一般采用仿射变换来实现.有下面两种旋转的方式:
1.旋转后图像尺寸变大,原来的图像能完整的显示.

#include 
#include 
#include 

using namespace cv;
using namespace std;

Mat rotateImage1(const Mat &img, int degree) {

    degree = -degree;
    double angle = degree * CV_PI / 180.; // 弧度
    double a = sin(angle), b = cos(angle);
    int width = img.cols;
    int height = img.rows;
    int width_rotate = int(height * fabs(a) + width * fabs(b));   //旋转后的长宽
    int height_rotate = int(width * fabs(a) + height * fabs(b));

    //旋转数组map
    // [ m0  m1  m2 ] ===>  [ A11  A12   b1 ]
    // [ m3  m4  m5 ] ===>  [ A21  A22   b2 ]
    float map[6];
    Mat map_matrix = Mat(2, 3, CV_32F, map);

    // 旋转中心  CvPoint2D32f 结构体 表示32位的浮点类型数据,(x,y)
    CvPoint2D32f center = cvPoint2D32f(width / 2, height / 2);
    CvMat map_matrix2 = map_matrix;                              //CvMat是一个结构体
    cv2DRotationMatrix(center, degree, 1.0, &map_matrix2);       //Computes rotation_matrix matrix
    map[2] += (width_rotate - width) / 2;
    map[5] += (height_rotate - height) / 2;
    Mat img_rotate;

    //对图像做仿射变换
    //CV_WARP_FILL_OUTLIERS - 填充所有输出图像的象素。
    //如果部分像素落在输入图像的边界外,那么它们的值设定为 fillval.
    //CV_WARP_INVERSE_MAP - 指定 map_matrix 是输出图像到输入图像的反变换,
    warpAffine(img, img_rotate, map_matrix, Size(width_rotate, height_rotate), 1, 0, 0);  //仿射变换,旋转图像
    return img_rotate;
}

int main(int argc, char *argv[]) {
    Mat m_SrcImg;
    m_SrcImg = imread("/home/fuhong/code/cpp/opencv_learning/src/小案例/imgs/case1.png");
    namedWindow("原图像", 1);
    imshow("原图像", m_SrcImg);
    double degree = 45;
    Mat m_ResImg = rotateImage1(m_SrcImg, degree);
    namedWindow("旋转后图像", 1);
    imshow("旋转后图像", m_ResImg);
    imwrite("/home/fuhong/code/cpp/opencv_learning/src/小案例/imgs/case1_3.png", m_ResImg);

    waitKey(0);

}

左边是原图,右边是旋转后的效果:
opencv之旋转图像_第1张图片
2.旋转后图像尺寸不变,原来的图像只能显示一部分.

#include 
#include 

using namespace cv;

// 图像旋转
///@ angle 要旋转的角度
void Rotate(const Mat &srcImage, Mat &destImage, double angle) {
    Point2f center(srcImage.cols / 2, srcImage.rows / 2);//中心
    Mat M = getRotationMatrix2D(center, angle, 1);//计算旋转的仿射变换矩阵
    warpAffine(srcImage, destImage, M, Size(srcImage.cols, srcImage.rows));//仿射变换
    circle(destImage, center, 2, Scalar(255, 0, 0));
}

int main() {
    //读入图像,并判断图像是否读入正确
    cv::Mat srcImage = imread("/home/fuhong/code/cpp/opencv_learning/src/小案例/imgs/case1.png");
    if (!srcImage.data)
        return -1;
    imshow("srcImage", srcImage);
    //将图片按比例缩放至宽为250像素的大小
    Mat destImage;
    double angle = 45;//角度
    Rotate(srcImage, destImage, angle);
    imshow("dst", destImage);
    imwrite("/home/fuhong/code/cpp/opencv_learning/src/小案例/imgs/case1_333.png", destImage);
    waitKey(0);
    return 0;
}

左边是原图,右边是旋转后的效果:
opencv之旋转图像_第2张图片
可以根据需要选取合适的方法来对图像进行旋转操作.

你可能感兴趣的:(opencv,opencv,计算机视觉,cv,图像识别)