s1093705 作業1

圖像旋轉(Image Rotation)


題目說明:

撰寫一個程式將一張圖像的(a)整張圖像,(b)中心內切圓區域,旋轉一個角度(逆時針旋轉0 度至359 度):利用一個滑動條(trackbar)控制旋轉角度。 

開發環境:

  • Windows 11 
  • Visual Studio Code
  • Python 3.11.2 
  • Opencv 4.7.0

實作結果:


程式說明:

首先在 terminal 輸入以下指令,來安裝 openCV 的電腦視覺庫。
pip install opencv-python



引入 OpenCV 的函式庫:
import cv2



讀取路徑中的照片:
image_all = cv2.imread(path)



(a) 旋轉整張圖像:

用 createTrackerbar 建立拖拉工具,讓使用者可以控制旋轉的角度:
cv2.createTrackbar(bar_name, window_name_1, bar_beg, bar_end, rotate_all)

使用者控制旋轉角度後,將照片旋轉,並且更新顯示的影像;
  • getTrackerPos: 取得使用者輸入的值。
  • getRotationMatrix2D: 可以產生旋轉指定角度影像的仿射矩陣。
  • warpAffine: 利用旋轉矩陣產生旋轉後的影像。
  • imshow: 顯示影像在新的視窗。
def rotate_all(value):
    degree = cv2.getTrackbarPos(bar_name, window_name_1)
    rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
    rotated_image = cv2.warpAffine(image_all, rotation_matrix, (width, height))
    cv2.imshow(window_name_1, rotated_image)



(b) 旋轉中心內切圓圖像:

建立圓形的遮罩,以及其反轉遮罩;用來取出要旋轉的區域,以及固定不動的區域:
mask_circle = np.zeros(image_all.shape[:2], dtype="uint8")
cv2.circle(mask_circle, center_coor, radius, color, thickness)
mask_not_circle = cv2.bitwise_not(mask_circle)





將遮罩套用到照片上:
image_circle = cv2.bitwise_and(image_all, image_all, mask=mask_circle)
image_not_circle = cv2.bitwise_and(image_all, image_all, mask=mask_not_circle)





用 createTrackerbar 建立拖拉工具,讓使用者可以控制旋轉的角度:
cv2.createTrackbar(bar_name, window_name_2, bar_beg, bar_end, rotate_circle)

使用者控制旋轉角度後,負責更新顯示的圖形,
旋轉圓形遮罩後的照片,並與另外一半的照片的照片合併:
def rotate_circle(value):
    degree = cv2.getTrackbarPos(bar_name, window_name_2)
    rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
    circle_rotated_image = cv2.warpAffine(image_circle, rotation_matrix, (width, height))
    combined_rotated_image = cv2.bitwise_or(circle_rotated_image, image_not_circle)
    cv2.imshow(window_name_2, combined_rotated_image)





























留言

這個網誌中的熱門文章

rzwang Homework #1

s1093350 Homework #2

s1091537 Homework #1