【python】opencv透视变换

透视变换
图片内的点也映射过去
sudoku.jpg

# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np


def perspective_transformation(Image, total_points_list):
    '''透视变换'''
    pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
    pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
    # 获得透视变换矩阵
    M = cv.getPerspectiveTransform(pts1, pts2)
    dst = cv.warpPerspective(Image, M, (300, 300))

    back_points = get_points_tran(total_points_list, M)
    return dst, back_points


def get_points_tran(points_list, M):
    '''透视变换坐标转换'''
    back_list = []
    for i in points_list:
        x,y = cvt_pos([i[0],i[1]],M)
        back_list += [(x,y)]
    return back_list


def cvt_pos(pos,cvt_mat_t):
    u = pos[0]
    v = pos[1]
    x = (cvt_mat_t[0][0]*u+cvt_mat_t[0][1]*v+cvt_mat_t[0][2])/(cvt_mat_t[2][0]*u+cvt_mat_t[2][1]*v+cvt_mat_t[2][2])
    y = (cvt_mat_t[1][0]*u+cvt_mat_t[1][1]*v+cvt_mat_t[1][2])/(cvt_mat_t[2][0]*u+cvt_mat_t[2][1]*v+cvt_mat_t[2][2])
    return (int(x),int(y))


if __name__ == '__main__':

    image = cv.imread('sudoku.jpg')
    h,w,c = image.shape

    # 多边形
    points_list = [[154,159],[266,161], [269,268],[152,268]]
    mask_list = np.array(points_list, np.int32)
    mask_list.reshape((-1, 1, 2))

    pts1 = np.float32([[56, 65], [368, 52], [389, 390], [28, 387]])
    pts1 = np.array(pts1, np.int32)
    pts1.reshape((-1,1,2))

    cv.polylines(image, [pts1], True, (255, 0, 0))
    cv.polylines(image, [mask_list], True, (255, 0, 0))
    cv.imshow("orginal", image)

    # 调用透视变换函数
    new_image,back_points = perspective_transformation(image,points_list)

    back_points = np.array(back_points, np.int32)
    back_points.reshape((-1,1,2))

    cv.polylines(new_image, [back_points], True, (0, 0, 255))
    cv.imshow("dst", new_image)

    cv.waitKey(0)
    cv.destroyAllWindows()

你可能感兴趣的:(python,opencv,python,计算机视觉)