透视变换通用的变换公式:
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
- orig是原始图象
- screenCnt是检测图象的外轮廓(四个点组成)
- ratio是为了放大到原图的比例关系
其中four_point_transform定义:
def four_point_transform(image, pts):
# 获取输入坐标点
rect = order_points(pts)
(tl, tr, br, bl) = rect
# 计算输入的w和h值
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
maxWidth = max(int(widthA), int(widthB))
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
maxHeight = max(int(heightA), int(heightB))
# 变换后对应坐标位置
dst = np.array([
[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]], dtype = "float32")
# 计算变换矩阵
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
# 返回变换后结果
return warped
cv2.warpPerspective
就是透视变换函数
因此需要计算变换矩阵W和变换后的宽,高,做为warpPerspective函数的输入参数。
其中,使用order_points排序后的外轮廓四个坐标为:
cv2.getPerspectiveTransform
就是计算变换矩阵的函数
输入参数是变换前四个点的坐标,变换后四个点的坐标