跳转到主要内容

文本图像中的倾斜检测和校正

项目描述

Deskew

注意:倾斜以度为单位测量。去斜是通过对图像旋转与其倾斜相同的量但方向相反的过程来去除倾斜的过程。这导致图像水平和垂直对齐,文本横跨页面而不是以角度运行。

返回角度在-45和45度之间,以避免任意更改图像方向。

使用库时,您可以设置参数angle_pm_90True以获得-90到90度的角度。

文本图像中的倾斜检测和校正

倾斜图像 去斜后的图像
Image with skew Image after deskew

安装

您可以使用以下命令直接从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_peaksangle_pm_90min_anglemax_anglemin_deviation和最终sigma

受Alyn的启发: https://github.com/kakul/Alyn

贡献

安装预提交钩子

pip install pre-commit
pre-commit install --allow-missing-config

项目详情


发布历史 发布通知 | RSS订阅

下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

deskew-1.5.1.tar.gz (7.1 kB 查看哈希)

上传时间

构建分发

deskew-1.5.1-py3-none-any.whl (7.7 kB 查看哈希)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面