python如何批量将文档照片校正后保存为干净的图片?
就是没有周围的背景环境
网友回复
方法思路
边缘检测:使用Canny算法检测文档边缘轮廓识别:找到最大四边形轮廓(假定文档是最大的四边形)透视变换:将倾斜的四边形转换为矩形图像增强:二值化处理增强可读性批量处理:遍历文件夹处理所有图片实现代码import cv2 import numpy as np import glob import os 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 # 计算新宽度 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.get...
点击查看剩余70%