OpenCV 透视变换
生活随笔
收集整理的這篇文章主要介紹了
OpenCV 透视变换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
計算透視變換所需的參數矩陣:
def cal_perspective_params(img, points):# 設置偏移點。如果設置為(0,0),表示透視結果只顯示變換的部分(也就是畫框的部分)offset_x = 350offset_y = 0img_size = (img.shape[1], img.shape[0])src = np.float32(points)# 俯視圖中四點的位置dst = np.float32([[offset_x, offset_y], [img_size[0] - offset_x, offset_y],[offset_x, img_size[1] - offset_y],[img_size[0] - offset_x, img_size[1] - offset_y]])# 從原始圖像轉換為俯視圖的透視變換的參數矩陣M = cv2.getPerspectiveTransform(src, dst)# 從俯視圖轉換為原始圖像的透視變換參數矩陣M_inverse = cv2.getPerspectiveTransform(dst, src)return M, M_inverse透視變換:
def img_perspect_transform(img, M):img_size = (img.shape[1], img.shape[0])return cv2.warpPerspective(img, M, img_size)調用以上兩個函數的示例代碼:
# -*- coding: UTF-8 -*- import cv2 import numpy as np import matplotlib.pyplot as plt# 計算透視變換所需的參數矩陣: def cal_perspective_params(img, points):# 設置偏移點。如果設置為(0,0),表示透視結果只顯示變換的部分(也就是畫框的部分)offset_x = 350offset_y = 0img_size = (img.shape[1], img.shape[0])src = np.float32(points)# 俯視圖中四點的位置dst = np.float32([[offset_x, offset_y], [img_size[0] - offset_x, offset_y],[offset_x, img_size[1] - offset_y],[img_size[0] - offset_x, img_size[1] - offset_y]])# 從原始圖像轉換為俯視圖的透視變換的參數矩陣M = cv2.getPerspectiveTransform(src, dst)# 從俯視圖轉換為原始圖像的透視變換參數矩陣M_inverse = cv2.getPerspectiveTransform(dst, src)return M, M_inverse# 透視變換: def img_perspect_transform(img, M):img_size = (img.shape[1], img.shape[0])return cv2.warpPerspective(img, M, img_size)# 在原始圖像中我們繪制道路檢測的結果,然后通過透視變換轉換為俯視圖。 if __name__ == '__main__':img = cv2.imread("./test/img.png")img = cv2.line(img, (680, 448), (930, 448), (0, 0, 255), 3) # 橫線img = cv2.line(img, (930, 448), (1610, 717), (0, 0, 255), 3) # 右斜線img = cv2.line(img, (0, 790), (1700, 790), (0, 0, 255), 3) # 橫線img = cv2.line(img, (0, 760), (680, 448), (0, 0, 255), 3) # 左斜線points = [[680, 448], [930, 448], [0, 760], [1700, 790]]M, M_inverse = cal_perspective_params(img, points)transform_img = img_perspect_transform(img, M)plt.figure(figsize=(20, 8))plt.subplot(1, 2, 1)plt.title('原始圖像')plt.imshow(img[:, :, ::-1])plt.subplot(1, 2, 2)plt.title('俯視圖')plt.imshow(transform_img[:, :, ::-1])plt.show()執行代碼:
總結
以上是生活随笔為你收集整理的OpenCV 透视变换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenCV 相机校正
- 下一篇: Tensorflow 2.3 GPU安装