Python opencv 圖像矯正——透視變換

基於透視的圖像矯正

  1. 獲取圖像四個頂點
  2. 形成變換矩陣
  3. 透視變換
from imutils.perspective import four_point_transform
import imutils
import cv2


def Get_Outline(input_dir):
    image = cv2.imread(input_dir)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edged = cv2.Canny(blurred, 75, 200)
    return image, gray, edged


def Get_cnt(edged):  # 輪廓檢測 獲取四角點
    cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]
    docCnt = None

    if len(cnts) > 0:
        cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
        for c in cnts:
            peri = cv2.arcLength(c, True)  # 輪廓按大小降序排序
            approx = cv2.approxPolyDP(c, 0.02 * peri, True)  # 獲取近似的輪廓
            if len(approx) == 4:  # 近似輪廓有四個頂點
                docCnt = approx
                break
    return docCnt


if __name__ == "__main__":
    input_dir = "21.png"
    image, gray, edged = Get_Outline(input_dir)
    docCnt = Get_cnt(edged)  # 四角點
    result_img = four_point_transform(image, docCnt.reshape(4, 2))  # 對原始圖像進行四點透視變換
    print(docCnt)
    # 圈出四角點
    for peak in docCnt:
        peak = peak[0]
        cv2.circle(image, tuple(peak), 10, (255, 0, 0))
        
    cv2.imshow("original", image)
    cv2.imshow("gray", gray)
    cv2.imshow("edged", edged)
    cv2.imshow("result_img", result_img)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

在這裏插入圖片描述

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章