import numpy as np import cv2

加载图片

img = cv2.imread('skew_text.png')

灰度化

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

二值化

thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

膨胀操作

kernel = np.ones((3, 3), np.uint8) dilate = cv2.dilate(thresh, kernel, iterations=1)

找到图片轮廓

cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1]

根据轮廓获取最小外接矩形

min_rect = cv2.minAreaRect(cnts[0])

获取最小外接矩形的四个角

box = cv2.boxPoints(min_rect) box = np.int0(box)

计算外接矩形的宽度和高度

width = abs(box[0][0] - box[2][0]) height = abs(box[0][1] - box[2][1])

根据外接矩形的宽度和高度,分别计算需要设定的目标宽度和高度

dst_width = int(max(width, height) * 1.3) dst_height = int(min(width, height) * 1.3)

构建目标图像的尺寸

dst = np.array([ [0, 0], [dst_width - 1, 0], [dst_width - 1, dst_height - 1], [0, dst_height - 1]], dtype='float32')

计算仿射变换矩阵

m = cv2.getPerspectiveTransform(box, dst)

仿射变换

warp = cv2.warpPerspective(img, m, (dst_width, dst_height))

输出图片

cv2.imshow('img', warp) cv2.waitKey(0) cv2.destroyAllWindows()

Python 代码自动校正歪斜图片

原文地址: https://www.cveoy.top/t/topic/lkq7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录