"Digital Image Processing-OpenCV/Python" serial (41) Image rotation

"Digital Image Processing-OpenCV/Python" serial (41) Image rotation


This book’s JD discount purchase link: https://item.jd.com/14098452.html
This book’s CSDN exclusive serial column: https://blog.csdn.net /youcans/category_12418787.html

Insert image description here


Chapter 6 Geometric Transformation of Images


Geometric transformation is divided into isometric transformation, similarity transformation, affine transformation and projection transformation, which refers to transforming the position, size, shape and projection of the image, and projecting the image from the original plane to a new viewing plane. The geometric transformation of OpenCV images is essentially to convert a multi-dimensional array into another multi-dimensional array through a mapping relationship.


Summary of this chapter

  • Introduce affine transformation and learn to use affine transformation matrices to achieve affine transformation of images.
  • Learn to use functions to translate, scale, rotate, flip, and skew images.
  • Introduce projection transformation and learn to use the projection transformation matrix to implement the projection transformation of images.
  • Introduce image remapping and learn to use mapping functions to implement custom transformation and dynamic transformation of images.

6.1 Image rotation

Rotation transformation is an isometric transformation, and the length and area of ​​the image remain unchanged after transformation.
The image is rotated clockwise with the upper left corner (0,0) as the rotation center and the rotation angle θ. The rotation transformation matrix MAR can be constructed and the rotation transformation image is calculated through the function cv.warpAffine.

[ x ~ y ~ 1 ] = M A R [ x y 1 ] , M A R = [ cos θ − sin θ 0 sin θ cos θ 0 0 0 1 ] \begin{bmatrix} \tilde{x}\\ \tilde{y}\ \ 1 \end{bmatrix} = M_{AR} \begin{bmatrix} x\\ y\\ 1 \end{bmatrix} ,\hspace{1em} M_{AR} = \begin{bmatrix} cos \theta & -sin \theta &0\\ sin \theta &cos \theta &0\\ 0 &0 &1 \end{bmatrix} x~and~1 =MAR xand1 ,MAR= cosθsinθ0sinθcosθ0001

The image takes any point (x, y) as the rotation center and rotates clockwise according to the rotation angle. You can first translate the origin to the rotation center (x, y), then rotate the origin, and finally reversely translate back to the coordinate origin.

The function cv.getRotationMatrix2D in OpenCV can calculate the rotation transformation matrix centered on any point.

function prototype

cv.getRotationMatrix2D(center, angle, scale) → M

The function cv.getRotationMatrix2D can calculate the rotation transformation matrix M based on the rotation center and rotation angle:

M = [ α β ( 1 − α ) x − β y − β α β x + ( 1 − α ) y ] M = \begin{bmatrix} \alpha & \beta &(1-\alpha)x-\beta y\\ -\beta &\alpha &\beta x +(1-\alpha)y \end{bmatrix}M=[aβbα(1α)xβyβx+(1α)y]

Parameter Description

  • center: coordinates of the rotation center, in the format of tuple (x, y).
  • angle: rotation angle, angle system, counterclockwise rotation.
  • scale: scaling coefficient, floating point data.
  • M: Rotation transformation matrix, which is a Numpy array with shape (2,3) and type np.float32.

Pay attention to the problem

  • (1) The function can directly obtain the rotation transformation matrix centered on any point without additional translation transformation.

  • (2) If the size of the rotated image is the same as the size of the original image, the pixels in the four corners will be cut off (see Figure 6-3(2)). In order to preserve the content of the original image, the image needs to be scaled while rotating, or the rotated image should be resized to:

W r o t = w cos θ + h sin θ H r o t = h cos θ + w sin θ W_{rot} = w cos \theta+ h sin \theta \\ H_{rot} = h cos \theta+ w sin \thetaINrot=wcosθ+hsinθHrot=hcosθ+wsinθ
In the formula, w, h is the width and height of the original image respectively; , are the width and height of the rotated image respectively.

  • (3) The scaling factor scale can be scaled while rotating, but the same scaling ratio must be used in the horizontal and vertical directions.

The function cv.rotate is used for right-angle rotation, and the rotation angle is 90 degrees, 180 degrees or 270 degrees. This method is implemented by matrix transposition and runs extremely fast.

function prototype

cv.rotate(src, rotateCode[, dst]) → dst

Parameter Description

  • src: input image, which is a Numpy array.
  • dst: Output image, the type is the same as src, the image size is determined by the rotation angle.
  • rotateCode: rotation identifier.
    • ROTATE_90_CLOCKWISE: Rotate 90 degrees clockwise.
    • ROTATE_180: Rotate 180 degrees clockwise.
    • ROTATE_90_COUNTERCLOCKWISE: Rotate 270 degrees clockwise.

Pay attention to the problem

When the rotation angle is 180 degrees, the size of the output image is the same as that of the input image; when the rotation angle is 90 degrees or 180 degrees, the height and width of the output image are equal to the width and height of the input image respectively.


[Routine 0603] Image rotation

This routine introduces the rotation of the image using the origin as the rotation center, using any point as the rotation center, and the right-angle rotation of the image.


# 【0603】图像的旋转
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

if __name__ == '__main__':
    img = cv.imread("../images/Fig0301.png")  # 读取彩色图像(BGR)
    height, width = img.shape[:2]  # 图像的高度和宽度

    # (1) 以原点为旋转中心
    x0, y0 = 0, 0  # 以左上角顶点 (0,0) 作为旋转中心
    theta, scale = 30, 1.0  # 逆时针旋转 30 度,缩放系数 1.0
    MAR0 = cv.getRotationMatrix2D((x0,y0), theta, scale)  # 旋转变换矩阵
    imgRot1 = cv.warpAffine(img, MAR0, (width, height))  

    # (2) 以任意点为旋转中心
    x0, y0 = width//2, height//2  # 以图像中心作为旋转中心
    angle = theta * np.pi/180  # 弧度->角度
    wRot = int(width * np.cos(angle) + height * np.sin(angle))  # 调整宽度
    hRot = int(height * np.cos(angle) + width * np.sin(angle))  # 调整高度
    scale = width/wRot  # 根据 wRot 调整缩放系数
    MAR1 = cv.getRotationMatrix2D((x0,y0), theta, 1.0)  # 逆时针旋转 30 度,缩放系数 1.0
    MAR2 = cv.getRotationMatrix2D((x0,y0), theta, scale)  # 逆时针旋转 30 度,缩放比例 scale
    imgRot2 = cv.warpAffine(img, MAR1, (height, width), borderValue=(255,255,255))  # 白色填充
    imgRot3 = cv.warpAffine(img, MAR2, (height, width))  # 调整缩放系数,以保留原始图像的内容
    print(img.shape, imgRot2.shape, imgRot3.shape, scale)

    # (3) 图像的直角旋转
    imgRot90 = cv.rotate(img, cv.ROTATE_90_CLOCKWISE)  # 顺时针旋转 90度
    imgRot180 = cv.rotate(img, cv.ROTATE_180)  # 顺时针旋转 180度
    imgRot270 = cv.rotate(img, cv.ROTATE_90_COUNTERCLOCKWISE)  # 顺时针旋转 270度

    plt.figure(figsize=(9, 6))
    plt.subplot(231), plt.title("1.Rotate around the origin"), plt.axis('off')
    plt.imshow(cv.cvtColor(imgRot1, cv.COLOR_BGR2RGB))
    plt.subplot(232), plt.title("2.Rotate around the center"), plt.axis('off')
    plt.imshow(cv.cvtColor(imgRot2, cv.COLOR_BGR2RGB))
    plt.subplot(233), plt.title("3.Rotate and resize"), plt.axis('off')
    plt.imshow(cv.cvtColor(imgRot3, cv.COLOR_BGR2RGB))
    plt.subplot(234), plt.title("4.Rotate 90 degrees"), plt.axis('off')
    plt.imshow(cv.cvtColor(imgRot90, cv.COLOR_BGR2RGB))
    plt.subplot(235), plt.title("5.Rotate 180 degrees"), plt.axis('off')
    plt.imshow(cv.cvtColor(imgRot180, cv.COLOR_BGR2RGB))
    plt.subplot(236), plt.title("6.Rotate 270 degrees"), plt.axis('off')
    plt.imshow(cv.cvtColor(imgRot270, cv.COLOR_BGR2RGB))
    plt.tight_layout()
    plt.show()


Program description:
The running results and image rotation are shown in Figure 6-3.
(1) Figure 6-3(1)~(3) After using the function cv.getRotationMatrix2D to calculate the rotation transformation matrix, the function cv.warpAffine is used to calculate the rotation transformation image. Figure 6-3(1) rotates around the origin of the image, that is, the upper left corner, and Figure 6-3(2) and Figure 6-3(3) rotate around the center point of the image.
(2) The image size remains unchanged, and the four corner pixels are cut off after the center is rotated (see Figure 6-3(2)). The scaling factor is used when calculating the rotation transformation matrix, so that the rotated image retains the content of the original image (see Figure 6-3(3)).
(3) Figure 6-3 (4) ~ (6) are all right-angle rotations, which are realized by matrix transposition using the function cv.rotate.


Insert image description here

*Figure 6-3 Image rotation


Copyright statement:
youcans@xupt original work, reprints must be marked with the original link: (https://blog.csdn.net/youcans/article/details/134317103) Crated:2023-11-11
Copyright 2023 youcans, XUPT

Welcome to follow this book’s CSDN exclusive serialization column
"Digital Image Processing-OpenCV/Python" serialization: https://blog.csdn.net/youcans/category_12418787.html

Guess you like

Origin blog.csdn.net/youcans/article/details/134317103