在 OpenCV 中,可以通過 warpAffine 函數來實現圖像的旋轉。以下是一個簡單的 Python 代碼示例,演示了如何使用 OpenCV 對圖像進行旋轉:
import cv2
import numpy as np
# 讀取圖像
image = cv2.imread('input_image.jpg')
# 獲取圖像寬度和高度
height, width = image.shape[:2]
# 定義旋轉角度
angle = 45
# 計算旋轉中心
center = (width // 2, height // 2)
# 生成旋轉矩陣
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
# 執(zhí)行仿射變換
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))
# 顯示原始圖像和旋轉后的圖像
cv2.imshow('Original Image', image)
cv2.imshow('Rotated Image', rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
在這個示例中,我們首先讀取一張輸入圖像,然后定義旋轉角度并計算旋轉中心。接下來,使用cv2.getRotationMatrix2D函數生成旋轉矩陣,其中參數包括旋轉中心、旋轉角度和縮放因子。最后,通過cv2.warpAffine函數對圖像執(zhí)行仿射變換,得到旋轉后的圖像。
你可以根據具體需求修改旋轉角度和旋轉中心,以及根據實際情況進行其他調整。