0
点赞
收藏
分享

微信扫一扫

【千律】OpenCV基础:图像的旋转变换

凯约 2022-03-20 阅读 58
pythonopencv

环境:Python3.8 和 OpenCV

内容:图像的旋转变换

旋转变换公式如下:

 \large \begin{bmatrix} x \\ y \\ 1 \end{bmatrix} = \begin{bmatrix} \cos \alpha & \sin \alpha & 0 \\ - \sin \alpha & \cos \alpha & 0 \\ 0 & 0 & 1 \\ \end{bmatrix} \begin{bmatrix} x_0 \\ y_0 \\ 1 \end{bmatrix}

上述公式为坐标原点旋转变换,若为图像中心旋转则应加入平移变换。

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt


# 封装图片显示函数
def image_show(image):
    if image.ndim == 2:
        plt.imshow(image, cmap='gray')
    else:
        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
        plt.imshow(image)
    plt.show()


if __name__ == '__main__':

    # 读取图像
    img_lenna = cv.imread('lenna.png')

    # 得到图像的大小
    [r, c, h] = img_lenna.shape
    # r: 图像的宽度(行)
    # c: 图像的长度(列)

    # 定义旋转变换矩阵
    alpha = np.pi / 24
    M1 = np.array([[np.cos(alpha), np.sin(alpha), 0],
                   [-np.sin(alpha), np.cos(alpha), 0]], dtype=np.float32)

    # 图像的旋转变换(坐标零点为中心)
    img_rotate1 = cv.warpAffine(img_lenna, M1, (r, c))
    image_show(img_rotate1)

    # 定义中心旋转变换矩阵
    para = 20    # 旋转角度
    M2 = cv.getRotationMatrix2D((c//2, r//2), para, 1)

    # 图像的中心旋转变换(图像中心旋转)
    img_rotate2 = cv.warpAffine(img_lenna, M2, (r, c))
    image_show(img_rotate2)

    # 图像逆时针旋转90度(图像中心旋转)
    img_rotate3 = cv.rotate(img_lenna, cv.ROTATE_90_COUNTERCLOCKWISE)
    image_show(img_rotate3)
举报

相关推荐

0 条评论