天天看點

OpenCV 透視變換

計算透視變換所需的參數矩陣:

def cal_perspective_params(img, points):
    # 設定偏移點。如果設定為(0,0),表示透視結果隻顯示變換的部分(也就是畫框的部分)
    offset_x = 350
    offset_y = 0
    img_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 = 350
    offset_y = 0
    img_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()      

繼續閱讀