Mik*_*ike 44 python opencv rotation
我很难找到使用OpenCV在Python中以特定(通常非常小)的角度围绕特定点旋转图像的示例.
这是我到目前为止所做的,但它会产生一个非常奇怪的结果图像,但它有点旋转:
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
Run Code Online (Sandbox Code Playgroud)
小智 51
import numpy as np
def rotateImage(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
Run Code Online (Sandbox Code Playgroud)
假设您使用的是cv2版本,该代码会找到您要旋转的图像的中心,计算变换矩阵并应用于图像.
fiv*_*vef 33
或者更容易使用 SciPy
from scipy import ndimage
#rotation angle in degree
rotated = ndimage.rotate(image_to_rotate, 45)
Run Code Online (Sandbox Code Playgroud)
请参阅 此处 以获取更多用法信息
Omn*_*ent 10
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
Run Code Online (Sandbox Code Playgroud)
cv2.warpAffine函数以相反的顺序获取shape参数:(col,row),上面的答案没有提及.这对我有用:
import numpy as np
def rotateImage(image, angle):
row,col = image.shape
center=tuple(np.array([row,col])/2)
rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
new_image = cv2.warpAffine(image, rot_mat, (col,row))
return new_image
Run Code Online (Sandbox Code Playgroud)
小智 6
import imutils
vs = VideoStream(src=0).start()
...
while (1):
frame = vs.read()
...
frame = imutils.rotate(frame, 45)
Run Code Online (Sandbox Code Playgroud)
更多:https : //github.com/jrosebr1/imutils
我遇到了上述某些解决方案的问题,无法获得正确的“ bounding_box”或新的图像尺寸。所以这是我的版本
def rotation(image, angleInDegrees):
h, w = image.shape[:2]
img_c = (w / 2, h / 2)
rot = cv2.getRotationMatrix2D(img_c, angleInDegrees, 1)
rad = math.radians(angleInDegrees)
sin = math.sin(rad)
cos = math.cos(rad)
b_w = int((h * abs(sin)) + (w * abs(cos)))
b_h = int((h * abs(cos)) + (w * abs(sin)))
rot[0, 2] += ((b_w / 2) - img_c[0])
rot[1, 2] += ((b_h / 2) - img_c[1])
outImg = cv2.warpAffine(image, rot, (b_w, b_h), flags=cv2.INTER_LINEAR)
return outImg
Run Code Online (Sandbox Code Playgroud)
您可以简单地使用 imutils 包进行轮换。它有两种方法
您可以在此博客上获得更多信息:https : //www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/