不知道是不是因为太简单,OpenCV不屑于去封装还是怎么回事,OpenCV中并没有一个API是专门用于实现图像任意角度的旋转的。我最近由于想要实现一下带旋转的模板匹配,因而必须对图像进行旋转。因此自己写了一个函数。下面是Python版的实现:
import cv2
import matplotlib.pyplot as plt
import numpy as np
def rot_degree(img, degree):
rows, cols = img.shape
center = (cols / 2, rows / 2)
mask = img.copy()
mask[:, :] = 255
M = cv2.getRotationMatrix2D(center, degree, 1)
top_right = np.array((cols - 1, 0)) - np.array(center)
bottom_right = np.array((cols - 1, rows - 1)) - np.array(center)
top_right_after_rot = M[0:2, 0:2].dot(top_right)
bottom_right_after_rot = M[0:2, 0:2].dot(bottom_right)
new_width = max(int(abs(bottom_right_after_rot[0] * 2) + 0.5), int(abs(top_right_after_rot[0] * 2) + 0.5))
new_height = max(int(abs(top_right_after_rot[1] * 2) + 0.5), int(abs(bottom_right_after_rot[1] * 2) + 0.5))
offset_x = (new_width - cols) / 2
offset_y = (new_height - rows) / 2
M[0, 2] += offset_x
M[1, 2] += offset_y
dst = cv2.warpAffine(img, M, (new_width, new_height))
mask = cv2.warpAffine(mask, M, (new_width, new_height))
_, mask = cv2.threshold(mask, 128, 255, cv2.THRESH_BINARY)
return dst, mask
if __name__ == '__main__':
img = cv2.imread('messi5.jpg', cv2.IMREAD_GRAYSCALE)
plt.imshow(img, cmap='gray')
plt.show()
dst, mask = rot_degree(img, 30)
plt.imshow(dst, cmap='gray')
plt.show()
plt.imshow(mask, cmap='gray')
plt.show()
看到代码其实就能了解到,OpenCV其实是可以实现旋转的。最关键的两个OpenCV的函数就是cv2.getRotationMatrix2D
和cv2.warpAffine
。只是如果要考虑旋转之后画布的大小会发生变化,就还有好多小细节要考虑到。看了代码自然知道,我就不在这里一一说明了。
网友评论