对于扫描仪扫面图像可能出现略微倾斜或二值化A3试卷照片后,对倾斜文档图像进行旋转矫正~
原图:
代码:
import cv2
import numpy as npdef show(img):cv2.namedWindow('img', 0)cv2.imshow('img', img)cv2.waitKey(0)def binary_(img):gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)return binary# 旋转angle角度,缺失背景白色(255, 255, 255)填充
def rotate_bound_white_bg(image, angle):# grab the dimensions of the image and then determine the# center(h, w) = image.shape[:2](cX, cY) = (w // 2, h // 2)# grab the rotation matrix (applying the negative of the# angle to rotate clockwise), then grab the sine and cosine# (i.e., the rotation components of the matrix)# -angle位置参数为角度参数负值表示顺时针旋转; 1.0位置参数scale是调整尺寸比例(图像缩放参数),建议0.75M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)cos = np.abs(M[0, 0])sin = np.abs(M[0, 1])# compute the new bounding dimensions of the imagenW = int((h * sin) + (w * cos))nH = int((h * cos) + (w * sin))# adjust the rotation matrix to take into account translationM[0, 2] += (nW / 2) - cXM[1, 2] += (nH / 2) - cY# perform the actual rotation and return the image# borderValue 缺失背景填充色彩,此处为白色,可自定义return cv2.warpAffine(image, M, (nW, nH), borderValue=(255, 255, 255))def paper_rotate(img):# 扫描机————A3样式纸张角度矫正# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)binary = binary_(img)# rotate_img = Transformation(binary, img)coords = np.column_stack(np.where(binary > 0))angle = cv2.minAreaRect(coords)[-1] # 最小外接矩形print(angle)if angle < -45:angle = 88 + angleelse:angle = angle - 2rotate_img = rotate_bound_white_bg(img,angle)return rotate_imgif __name__ == '__main__':import timepath = '../ImgTest/4.jpg'img = cv2.imread(path)print(img.shape)s = time.time()rotate_img = paper_rotate(img)e = time.time()print(rotate_img.shape)print(f"耗时{e - s}")show(rotate_img)
效果:
边缘填充的白色像素去除就很容易了,图像旋转后属于无损图像,不用担心图像出模糊情况,就是图像会变大,哈哈哈~