文本图像中的倾斜检测和校正
项目描述
Deskew
注意:倾斜以度为单位测量。去斜是通过对图像旋转与其倾斜相同的量但方向相反的过程来去除倾斜的过程。这导致图像水平和垂直对齐,文本横跨页面而不是以角度运行。
返回角度在-45和45度之间,以避免任意更改图像方向。
使用库时,您可以设置参数angle_pm_90
为True
以获得-90到90度的角度。
文本图像中的倾斜检测和校正
倾斜图像 | 去斜后的图像 |
---|---|
安装
您可以使用以下命令直接从pypi安装deskew
python3 -m pip install deskew
或升级到新版本
python3 -m pip install -U deskew
Cli用法
获取倾斜角度
deskew input.png
去斜图像
deskew --output output.png input.png
库用法
使用scikit-image
import numpy as np
from skimage import io
from skimage.color import rgb2gray
from skimage.transform import rotate
from deskew import determine_skew
image = io.imread('input.png')
grayscale = rgb2gray(image)
angle = determine_skew(grayscale)
rotated = rotate(image, angle, resize=True) * 255
io.imsave('output.png', rotated.astype(np.uint8))
使用OpenCV
import math
from typing import Tuple, Union
import cv2
import numpy as np
from deskew import determine_skew
def rotate(
image: np.ndarray, angle: float, background: Union[int, Tuple[int, int, int]]
) -> np.ndarray:
old_width, old_height = image.shape[:2]
angle_radian = math.radians(angle)
width = abs(np.sin(angle_radian) * old_height) + abs(np.cos(angle_radian) * old_width)
height = abs(np.sin(angle_radian) * old_width) + abs(np.cos(angle_radian) * old_height)
image_center = tuple(np.array(image.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
rot_mat[1, 2] += (width - old_width) / 2
rot_mat[0, 2] += (height - old_height) / 2
return cv2.warpAffine(image, rot_mat, (int(round(height)), int(round(width))), borderValue=background)
image = cv2.imread('input.png')
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
angle = determine_skew(grayscale)
rotated = rotate(image, angle, (0, 0, 0))
cv2.imwrite('output.png', rotated)
调试图像
如果您得到错误的倾斜角度,您可以生成调试图像,这可以帮助您调整倾斜检测。
如果您使用pip install deskew[debug_images]
安装deskew,您可以使用函数determine_skew_debug_images
获取用于倾斜检测的一些调试图像。
要开始调查,您应该首先增加num_peaks
(默认20
)并使用determine_skew_debug_images
函数。
然后您可以尝试调整以下参数:num_peaks
、angle_pm_90
、min_angle
、max_angle
、min_deviation
和最终sigma
。
受Alyn的启发: https://github.com/kakul/Alyn
贡献
安装预提交钩子
pip install pre-commit
pre-commit install --allow-missing-config
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。
源分发
deskew-1.5.1.tar.gz (7.1 kB 查看哈希)
构建分发
deskew-1.5.1-py3-none-any.whl (7.7 kB 查看哈希)
关闭
deskew-1.5.1.tar.gz 的哈希
算法 | 哈希摘要 | |
---|---|---|
SHA256 | b27d910da9ec34fa9abf867e3aed19dda87ab12529fc51124d38b7299ffaa387 |
|
MD5 | 2b1b139555a930929e1cf60b32fa4a62 |
|
BLAKE2b-256 | 2fdddc20f529fc1246e52e851a79ae718951134dda366c070e48c08c03654c3c |
关闭
deskew-1.5.1-py3-none-any.whl 的哈希
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 4759427758c6a754077eed306c5ef22ebc9644d557748763f968cfd242ead18f |
|
MD5 | 903430a5f9bef400e2684d48de2e0c21 |
|
BLAKE2b-256 | 4bb70dd282f6e83759939cd0ea78920cc67c7d57503f9ba2f51deaf05ecb1f20 |