OpenCV中的圖像旋轉
OpenCV主要使用getRotationMatrix2D()來得到變換矩陣(getRotationMatrix2D的計算方式與上一節的推導一致,大家可以參看函數解釋推導一下),再使用warpAffine()來實現圖像旋轉。代碼如下
def rotate(image, angle, center=None, scale=1.0): # grab the dimensions of the image (h, w) = image.shape[:2] # if the center is None, initialize it as the center of # the image 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 the rotated image return rotated
現在我們來旋轉一只小鳥。
使用OpenCV的方法旋轉結果如下所示:
可以看到當旋轉矩形塗向師,旋轉后原圖大量信息丟失了。在有些時候我們並不想要這種信息的丟失(比如在深度學習數據增強的時候)。
現在我改寫一下上面的代碼,來使矩形圖片可以正確的旋轉,不丟失信息。代碼如下:
def rotate_bound(image, angle): # grab the dimensions of the image and then determine the # center (h, w) = image.shape[:2] (cX, cY) = (w / 2, h / 2) # grab the rotation matrix (applying the negative of the # angle to rotate clockwise), then grab the sine and cosine # (i.e., the rotation components of the matrix) M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0) cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) # compute the new bounding dimensions of the image nW = int((h * sin) + (w * cos)) nH = int((h * cos) + (w * sin)) # adjust the rotation matrix to take into account translation M[0, 2] += (nW / 2) - cX M[1, 2] += (nH / 2) - cY # perform the actual rotation and return the image return cv2.warpAffine(image, M, (nW, nH))
在計算出旋轉變換矩陣M后,計算一下可以正常包含旋轉后圖像的外接矩形框的長和寬,然后計算外接矩形框的中心和原矩形框中心的距離,最后將旋轉后的圖像中心移到新的外接矩形框的中心。
結果如下: