文章目录
1、需求描述
输入图片
扫描得到如下的结果
用OpenCV构建文档扫描仪只需三个简单步骤:
1.边缘检测
2.使用图像中的边缘来找到代表被扫描纸张的轮廓。
3.应用透视变换来获得文档的自顶向下视图。
2、代码实现
导入必要的包
from skimage.filters import threshold_local
import numpy as np
import argparse
import cv2
import imutils
初始化一个坐标列表,该列表中的第一个元素是左上,第二个元素是右上,第三个元素是右下,第四个元素是左下
该坐标排序方法有缺陷,具体可参考 【python】OpenCV—Coordinates Sorted Clockwise
def order_points(pts):
rect = np.zeros((4, 2), dtype = "float32")
# 左上角点的和最小,然而右下角的点的和最大
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
# 计算新图像的宽度,这将是右下角和左下角x坐标或右上角和左上角x坐标之间的最大距离
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))
# 计算新图像的高度,这将是右上角和右下角y坐标或左上角和左下角y坐标之间的最大距离
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.