利用OpenCV的透视变换校正倾斜物体
读入图像——>预处理(灰度化,高斯滤波、边缘检测)———>轮廓检测(获取到最大轮廓)———>所需轮廓坐标点排序——>得到变换矩阵————>透视变换
校对效果如下所示:
# 导入工具包
import numpy as np
import argparse
import cv2
# 设置参数
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image",default="./images/page.jpg",
help = "Path to the image to be scanned")
args = vars(ap.parse_args())
def order_points(pts):
# 一共4个坐标点
rect = np.zeros((4, 2), dtype = "float32")
# 按顺序找到对应坐标0123分别是 左上,右上,右下,左下
# 计算左上,右下
s = pts.sum(axis = 1) # 通过对数组纵向求和,得到最大与最小值对应的索引
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
# 计算右上和左下
diff = np.diff(pts, axis = 1)
rect[1] = pts[np.argmin(diff)] # 通过对数组纵向做差,得到对大值与最小值对应的索引
rect[3] = pts[np.argmax(diff)]
return rect
def four_point_transform(image, pts):
# 获取输入坐标点
rect = order_points(pts)
(tl, tr, br, bl) = rect
# 计算输入的w和h值
widthA = np.sqrt(((br[0] - bl[0