2012-01-27 54 views
20

我有一個很難找到實例由特定旋轉圍繞一個特定的點的圖像。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 

回答

23
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 

假設你正在使用的版本CV2,該代碼查找要旋轉的圖像的中心,計算變換矩陣並應用於圖像。

+0

感謝您的幫助,但我使用了 「CV」 模塊,並且使用 「CV2」,所以它抱怨具體關於「image.shape」不存在。到目前爲止,我只使用「cv」模塊,所以我還沒有完全使用「cv2」進行所有更改。我知道我的圖像是(140,140),所以我試圖用硬編碼來代替image.shape,但它根本不喜歡這樣的圖像。 – Mike 2012-01-28 05:06:20

+1

我想我可能已經取得了一些進展,但仍然遇到問題。下面是最新的代碼: 結果= cv2.warpAffine(圖像,rot_mat,cv.GetSize(圖像),旗幟= cv2.INTER_LINEAR) 回溯(最近通話最後一個): 結果= cv2.warpAffine(圖像,rot_mat,cv.GetSize(圖像),標記= cv2.INTER_LINEAR) 類型錯誤:不是numpy的陣列 – Mike 2012-01-28 05:26:04

+14

我有運行 cv2.getRotationMatrix2D(中心= image_center,角=角度,標度= 1) 一個問題TypeError:函數只需要2個參數(3給出) – Hani 2012-03-08 18:44:41

2

快速的調整,以@亞歷克斯 - 羅德里格斯回答......與形狀交易,包括信道的數量。

import cv2 
import numpy as np 

def rotateImage(image, angle): 
    center=tuple(np.array(image.shape[0:2])/2) 
    rot_mat = cv2.getRotationMatrix2D(center,angle,1.0) 
    return cv2.warpAffine(image, rot_mat, image.shape[0:2],flags=cv2.INTER_LINEAR) 
18

或者更容易使用 SciPy

from scipy import ndimage 

#rotation angle in degree 
rotated = ndimage.rotate(image_to_rotate, 45) 

看到 here 更多的使用信息。

+0

我正在通過一個png目錄循環,這樣做,但我得到一個RuntimeError:指定了無效的旋轉平面。任何修復? – 2017-02-06 17:49:19

+0

你傳遞一個開放的CV鏡像嗎?像這樣:img = cv2.imread('messi5.jpg',0) – fivef 2017-02-07 18:58:59

+3

這對我來說是相當慢的 – 2017-07-15 13:20:15

4

的cv2.warpAffine函數需要以相反的順序形狀參數:(COL,行),其答案上面沒有提及。這裏是我工作:

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 
7
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 
1
import imutils 

vs = VideoStream(src=0).start() 
... 

while (1): 
    frame = vs.read() 
    ... 

    frame = imutils.rotate(frame, 45) 

更多:https://github.com/jrosebr1/imutils

+0

這個不會削減任何圖像:'imutils.rotate_bound(frame,90)' – 2017-07-15 13:22:37