用OpenCV Python围绕特定点旋转图像X度
我在用Python和OpenCV旋转图像时遇到了一些困难,特别是想围绕一个特定的点旋转一个特定的(通常是很小的)角度,但找不到相关的例子。
这是我目前的代码,但它生成的图像看起来很奇怪,虽然确实有旋转:
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
12 个回答
23
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则被满足时,程序才会按照我们的要求去做事情。
例如,假设你在写一个游戏,想要让角色在分数达到一定值时才能升级。你可以设置一个条件,只有当分数大于某个数字时,角色才会升级。这样,程序就会检查这个条件,如果满足了,就执行升级的操作。
这种方式可以帮助我们控制程序的行为,让它更智能、更灵活。通过设置条件,我们可以让程序根据不同的情况做出不同的反应。
def rotate(image, angle, center = None, scale = 1.0):
(h, w) = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
# Perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
172
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这个版本,这段代码的作用是找到你想要旋转的图像的中心,然后计算出一个变换矩阵,并把这个矩阵应用到图像上。