一、Rotate方法概述
在計算機視覺領域,圖像的旋轉是一個非常基本而重要的操作。OpenCV Rotate方法是用於圖像旋轉的函數。這個函數能夠將一個圖像對象沿著指定的角度旋轉。這個方法非常靈活,允許開發人員指定圖像旋轉中心、旋轉角度及旋轉後的尺寸。
二、調用Rotate方法實現圖像旋轉
調用OpenCV Rotate方法時需要提供以下參數:
- 源圖像:要進行旋轉的原始圖像。
- 旋轉中心:旋轉中心點坐標(可以是二元組)。
- 旋轉角度:逆時針旋轉角度。
- 縮放因子:表示旋轉後圖像的比例。
三、旋轉中心的選擇
在選擇旋轉中心時需要特別注意,這個點決定了圖像旋轉的基準。旋轉中心可以位於圖像的中心、左上、左下等位置。對於圖像旋轉後的效果影響非常大。在一些特定的場景下,比如目標檢測等需要準確位置信息的場景,正確選擇旋轉中心是非常關鍵的。
# 示例代碼:Configuring the rotation center
import cv2
import numpy as np
# 載入圖像
img = cv2.imread('image.jpg')
# 獲取圖像尺寸
(rows, cols) = img.shape[:2]
# 指定旋轉中心
center = (cols / 2, rows / 2)
# 旋轉配置:90度的逆時針旋轉、尺寸不變
M = cv2.getRotationMatrix2D(center, 90, 1.0)
# 應用變換
rotated = cv2.warpAffine(img, M, (cols, rows))
# 顯示變換前後的圖像
cv2.imshow("Original Image", img)
cv2.imshow("Rotated Image", rotated)
cv2.waitKey(0)
四、指定旋轉角度及旋轉後的尺寸
當對圖像進行旋轉時,需要指定旋轉角度和旋轉後的尺寸。旋轉角度可以是任意值,但旋轉後的尺寸是需要進行指定的。如果不指定尺寸,則會出現黑色邊框或者不完整的圖像。指定旋轉後的尺寸相當於是對原始圖像進行剪切。旋轉後的圖像尺寸將決定整個旋轉的實際效果。
# 示例代碼:Specifying the rotation angle and size
import cv2
import numpy as np
# 載入圖像
img = cv2.imread('image.jpg')
# 獲取圖像尺寸
(rows, cols) = img.shape[:2]
# 指定旋轉中心
center = (cols / 2, rows / 2)
# 指定旋轉角度
angle90 = 90
angle180 = 180
angle270 = 270
# 指定旋轉後的尺寸
scale = 1.0
# 旋轉配置:90度、180度、270度的逆時針旋轉、尺寸不變
M1 = cv2.getRotationMatrix2D(center, angle90, scale)
M2 = cv2.getRotationMatrix2D(center, angle180, scale)
M3 = cv2.getRotationMatrix2D(center, angle270, scale)
# 應用變換
rotated1 = cv2.warpAffine(img, M1, (cols, rows))
rotated2 = cv2.warpAffine(img, M2, (cols, rows))
rotated3 = cv2.warpAffine(img, M3, (cols, rows))
# 顯示變換前後的圖像
cv2.imshow("Original Image", img)
cv2.imshow("Rotated Image - 90 degrees", rotated1)
cv2.imshow("Rotated Image - 180 degrees", rotated2)
cv2.imshow("Rotated Image - 270 degrees", rotated3)
cv2.waitKey(0)
五、結論
本文主要介紹了OpenCV Rotate方法的使用方式及其相關參數。在實際開發中,要注意選擇正確的旋轉中心及合適的旋轉角度和尺寸,以達到最好的旋轉效果。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/279972.html
微信掃一掃
支付寶掃一掃