OpenCV Python围绕特定点将图像旋转X度

2022-01-16 00:00:00 python opencv rotation

问题描述

我很难找到使用 OpenCV 在 Python 中将图像围绕特定点旋转特定(通常非常小)角度的示例.

I'm having a hard time finding examples for rotating an image around a specific point by a specific (often very small) angle in Python using OpenCV.

这是我目前所拥有的,但它产生了一个非常奇怪的结果图像,但它有点旋转:

This is what I have so far, but it produces a very strange resulting image, but it is rotated somewhat:

def rotateImage( image, angle ):
    if image != None:
        dst_image = cv.CloneImage( image )

        rotate_around = (0,0)
        transl = cv.CreateMat(2, 3, cv.CV_32FC1 )

        matrix = cv.GetRotationMatrix2D( rotate_around, angle, 1.0, transl )
        cv.GetQuadrangleSubPix( image, dst_image, transl )
        cv.GetRectSubPix( dst_image, image, rotate_around )

    return dst_image


解决方案

import numpy as np
import cv2

def rotate_image(image, angle):
  image_center = tuple(np.array(image.shape[1::-1]) / 2)
  rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
  result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)
  return result

假设您使用的是 cv2 版本,该代码会找到您要旋转的图像的中心,计算变换矩阵并应用于图像.

Assuming you're using the cv2 version, that code finds the center of the image you want to rotate, calculates the transformation matrix and applies to the image.

相关文章