• OpenCV入门(C++/Python)- 使用OpenCV进行图像旋转和转换(五)


    近年来,随着手机具有这种内置功能,图像编辑变得越来越流行,它可以让您裁剪、旋转图像并对图像进行更多处理。

    在这篇文章中,我们将探索和学习这些图像编辑技术。具体来说,我们将学习如何:

    • 旋转图像
    • 转换或移动图像内容

    基本图像转换操作

    图像的旋转和平移是图像编辑中最基本的操作之一。两者都属于更广泛的仿射变换类别。因此,在研究更复杂的转换之前,您应该首先学习使用OpenCV中可用的函数旋转和平移图像。查看下面的图片,我们将在这里的所有转换示例中使用它。


    先看看下面的代码,这些代码将用于使用OpenCV执行图像旋转

    Python

    import cv2
     
    # Reading the image
    image = cv2.imread('image.jpg')
     
    # dividing height and width by 2 to get the center of the image
    height, width = image.shape[:2]
    # get the center coordinates of the image to create the 2D rotation matrix
    center = (width/2, height/2)
     
    # using cv2.getRotationMatrix2D() to get the rotation matrix
    rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=45, scale=1)
     
    # rotate the image using cv2.warpAffine
    rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(width, height))
     
    cv2.imshow('Original image', image)
    cv2.imshow('Rotated image', rotated_image)
    # wait indefinitely, press any key on keyboard to exit
    cv2.waitKey(0)
    # save the rotated image to disk
    cv2.imwrite('rotated_image.jpg', rotated_image)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    C++

    #include 
    #include
    using namespace cv;
     
    int main(int, char**) 
    {
        Mat image = imread("image.jpg");
        imshow("image", image);
        waitKey(0);
        double angle = 45;
     
        // get the center coordinates of the image to create the 2D rotation matrix
        Point2f center((image.cols - 1) / 2.0, (image.rows - 1) / 2.0);
        // using getRotationMatrix2D() to get the rotation matrix
        Mat rotation_matix = getRotationMatrix2D(center, angle, 1.0);
     
        // we will save the resulting image in rotated_image matrix
        Mat rotated_image;
        // rotate the image using warpAffine
        warpAffine(image, rotated_image, rotation_matix, image.size());
        imshow("Rotated image", rotated_image);
        // wait indefinitely, press any key on keyboard to exit
        waitKey(0);
        // save the rotated image to disk
        imwrite("rotated_im.jpg", rotated_image);
     
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    使用OpenCV的图像旋转

    通过定义变换矩阵 M M M,可以将图像旋转一定角度 θ \theta θ。该矩阵通常为:

    M = [ cos ⁡ θ − sin ⁡ θ sin ⁡ θ cos ⁡ θ ] (1) M=\left[ cosθsinθsinθcosθ \right] \tag{1} M=[cosθsinθsinθcosθ](1)
    OpenCV提供了可以自定义图像旋转的中心,以及调整图像大小的比例因子。在这种情况下,变换矩阵会被修改如下。

    M = [ α β ( 1 − α ) ∗ c x − β ∗ c y − β α β ∗ c x + ( 1 − α ) ∗ c y ] (2) M=\left[ αβ1α)cxβcyβαβcx+(1α)cy \right] \tag{2} M=[αββα1α)cxβcyβcx+(1α)cy](2)
    在上述矩阵中
    α = s c a l e ∗ cos ⁡ θ \alpha = scale*\cos\theta α=scalecosθ β = s c a l e ∗ sin ⁡ θ \beta = scale*\sin\theta β=scalesinθ

    其中 c x c_x cx c y c_y cy是图像旋转所沿的坐标。
    OpenCV提供getRotationMatrix2D()函数来创建上述转换矩阵。
    以下是创建二维旋转矩阵的语法:

    getRotationMatrix2D(center, angle, scale)
    
    • 1

    getRotationMatrix2D()函数接受以下参数:

    • center:输入图像的旋转中心
    • angle:以度为单位的旋转角度
    • scale:各向同性比例因子,根据提供的值向上或向下缩放图像

    如果角度为正,图像将沿逆时针方向旋转。如果要将图像顺时针旋转相同的角度,则角度需要为负值。

    旋转图像的三步操作:

    1. 首先,得到旋转中心。及旋转的图像的中心。
    2. 接下来,创建二维旋转矩阵。OpenCV提供了上面讨论的getRotationMatrix2D()函数。
    3. 最后,使用在上一步中创建的旋转矩阵将仿射变换应用于图像。OpenCV中的warpAffine()函数完成此任务。

    warpAffine()函数对图像应用仿射变换。在应用仿射变换之后,原始图像中的所有平行线也将在输出图像中保持平行。

    warpAffine()的完整语法如下:

    warpAffine(src, M, dsize[, dst[, flags[,borderMode[,borderValue]]]])
    
    • 1

    以下是函数的参数:

    • src:源图像
    • M: 变换矩阵
    • dsize:输出图像的大小 d
    • dst:输出图像
    • flags:插值方法的组合,如INTER_LINEAR或INTER_NEAREST
    • borderMode:像素外推方法
      borderValue:在常量边框的情况下使用的值,默认值为0

    下面举一个具体的例子,并尝试使用OpenCV来实现它

    Python

    import cv2
     
    # Reading the image
    image = cv2.imread('image.jpg')
    
    # Dividing height and width by 2 to get the center of the image
    height, width = image.shape[:2]
    center = (width/2, height/2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    C++

    #include "opencv2/opencv.hpp"
    using namespace cv;
     
    # Reading the image
    Mat image = imread("image.jpg");
    
    // get the center coordinates of the image to create the 2D rotation matrix
    Point2f center((image.cols - 1) / 2.0, (image.rows - 1) / 2.0);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    获得图像中心的像素坐标后,使用函数getRotationMatrix2D()计算旋转矩阵,如下所示。此函数将以下内容作为输入:

    • 旋转所围绕的中心点
    • 旋转角度,以度为单位(正值,对应于逆时针旋转)
    • 调整图像大小的各向同性比例因子。这可以是一个浮点值。例如,值1.0将保持输出图像与源图像的大小相同。值为2.0将使生成的图像的大小是源图像的两倍

    该函数返回2D旋转矩阵,该矩阵将在下一步中用于旋转图像。

    Python

    # the above center is the center of rotation axis
    # use cv2.getRotationMatrix2D() to get the rotation matrix
    rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=45, scale=1)
    
    • 1
    • 2
    • 3

    C++

    // create the rotation matrix using the image center
    Mat rotation_matix = getRotationMatrix2D(center, angle=45, 1.0);
    
    • 1
    • 2

    现在,使用warpAffine()函数将计算的旋转矩阵应用于图像。它需要三个输入:

    • 源图像
    • 旋转矩阵
    • 输出图像的大小

    Python

    # Rotate the image using cv2.warpAffine
    rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(width, height))
    
    • 1
    • 2

    C++

    // we will save the resulting image in rotated_image matrix
    Mat rotated_image;
    // apply affine transformation to the original image using the 2D rotation matrix
    warpAffine(image, rotated_image, rotation_matix, image.size());
    
    • 1
    • 2
    • 3
    • 4

    现在,使用imshow()函数显示旋转后的图像。
    Python

    # visualize the original and the rotated image
    cv2.imshow('Original image', image)
    cv2.imshow('Rotated image', rotated_image)
    # wait indefinitely, press any key on keyboard to exit
    cv2.waitKey(0)
    # write the output, the rotated image to disk
    cv2.imwrite('rotated_image.jpg', rotated_image)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    C++

    imshow("Rotated image", rotated_image);
    waitKey(0);
    // save the rotated image to disk
    imwrite("rotated_im.jpg", rotated_image);
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    使用OpenCV转换图像

    在计算机视觉中,图像的平移意味着沿x轴和y轴将其移动指定数量的像素。让图像需要移动的像素为 t x t_x tx t y t_y ty

    定义平移矩阵M:

    M = [ 1 0 t x 0 1 t y ] (3) M=\left[ 10tx01ty \right] \tag{3} M=[1001txty](3)

    现在,在按 t x t_x tx t y t_y ty值移动图像时。

    • t x t_x tx提供正值将使图像向右移动,负值将使图像向左移动。
    • 类似地, t y t_y ty的正值将向下移动图像,而负值将向上移动图像。

    按照以下步骤使用OpenCV转换图像:

    • 首先,读取图像并获得其宽度和高度。
    • 接下来,像旋转一样,创建一个变换矩阵,这是一个2D阵列。该矩阵包含沿x和y轴移动图像所需的信息。
    • 同样,在旋转中,在最后一步中使用warpAffine()函数应用仿射变换。

    代码如下:
    Python

    import cv2 
    import numpy as np
     
    # read the image 
    image = cv2.imread('image.jpg')
    # get the width and height of the image
    height, width = image.shape[:2]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    C++

    #include "opencv2/opencv.hpp"
    using namespace cv
    // read the image 
    Mat image = imread("image.jpg");
    // get the height and width of the image
    int height = image.cols;
    int width = image.rows;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    创建转换矩阵

    Python

    # get tx and ty values for translation
    # you can specify any value of your choice
    tx, ty = width / 4, height / 4
     
    # create the translation matrix using tx and ty, it is a NumPy array 
    translation_matrix = np.array([
        [1, 0, tx],
        [0, 1, ty]
    ], dtype=np.float32)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    C++

    // get tx and ty values for translation
    float tx = float(width) / 4;
    float ty = float(height) / 4;
    // create the translation matrix using tx and ty
    float warp_values[] = { 1.0, 0.0, tx, 0.0, 1.0, ty };
    Mat translation_matrix = Mat(2, 3, CV_32F, warp_values);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在本例中,您将宽度和高度的四分之一作为转换值。
    使用warpAffine()函数将平移矩阵应用于图像,与旋转原理相同。

    Python

    # apply the translation to the image
    translated_image = cv2.warpAffine(src=image, M=translation_matrix, dsize=(width, height))
    
    • 1
    • 2

    C++

    // save the resulting image in translated_image matrix
    Mat translated_image;
    // apply affine transformation to the original image using the translation matrix
    warpAffine(image, translated_image, translation_matrix, image.size());
    
    • 1
    • 2
    • 3
    • 4

    注意:warpAffine()是一个通用函数,可用于对图像应用任何类型的仿射变换。只需适当地定义矩阵M。

    最后,使用imshow()函数显示旋转后的图像。
    Python

    # display the original and the Translated images
    cv2.imshow('Translated image', translated_image)
    cv2.imshow('Original image', image)
    cv2.waitKey(0)
    # save the translated image to disk
    cv2.imwrite('translated_image.jpg', translated_image)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    C++

    //display the original and the Translated images
    imshow("Translated image", translated_image);
    imshow("Original image", image);
    waitKey(0);
    // save the translated image to disk
    imwrite("translated_image.jpg", translated_image);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

  • 相关阅读:
    互联网真实赚钱平台有哪些?分享六大类正规靠谱的线上平台
    Burp Suite Extension Development Guide
    leetcode 3074. 重新分装苹果 【Java】
    【C语言】深入浅出理解指针及内存与指针的关系(详细讲解+代码展示)
    java面试题(十五道)
    C++ 静态断言 static_assert
    torch.cuda.is_available() 在有的项目中返回True有的返回Flase
    【岛屿问题】递归
    leetcode-15.三数之和-20220821
    从零开始构建基于YOLOv5的目标检测系统
  • 原文地址:https://blog.csdn.net/weixin_42010722/article/details/128185688