基于OpenCV的图像处理案例之图像矫正(Python)

Index 目录索引

写在前面

本文通过一个案例介绍如何使用OpenCV将倾斜的扫描文档图像进行水平矫正。

解决思路

因为扫描图像中的大部分文字倾斜后,同一行文字也在同一条直线,所以可以通过拟合直线来计算文本倾斜角度,接着对这些倾斜角度进行排序,选择其中值作为最终的旋转角度,通过旋转来实现倾斜图像的水平矫正[1](#1)。本文在参考文档的基础上,进行了中值筛选,从而更好地对倾斜图像进行矫正。

废话不多说,直接上代码:

python 复制代码
import numpy as np
import os
import cv2
import math
from scipy import misc, ndimage


def getMedianAngle(lines):
    angles = []
    for line in lines:
        x1, y1, x2, y2 = line[0]
        # 计算直线的斜率
        if x1 != x2:  # 避免除以零错误
            slope = (y2 - y1) / (x2 - x1)
            # 计算斜率对应的角度
            angle = np.degrees(math.atan(slope))
            angles.append(angle)
    # 计算角度的中位数
    median_angle = np.median(angles)
    return median_angle


def rotate(image, angle, center=None, scale=1.0):
    (w, h) = image.shape[0:2]
    if center is None:
        center = (w // 2, h // 2)
    wrapMat = cv2.getRotationMatrix2D(center, angle, scale)
    return cv2.warpAffine(image, wrapMat, (h, w))


# 使用霍夫变换
def getCorrect2():
    # 读取图片,灰度化
    src = cv2.imread('./text_correct/640.png')
    showAndWaitKey("src", src)
    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    showAndWaitKey("gray", gray)
    # 腐蚀、膨胀
    kernel = np.ones((5, 5), np.uint8)
    erode_Img = cv2.erode(gray, kernel)
    eroDil = cv2.dilate(erode_Img, kernel)
    showAndWaitKey("eroDil", eroDil)
    # 边缘检测
    canny = cv2.Canny(eroDil, 50, 150)
    showAndWaitKey("canny", canny)
    # 霍夫变换得到线条
    lines = cv2.HoughLinesP(canny, 0.8, np.pi / 180, 90, minLineLength=100, maxLineGap=10)

	# 求得拟合图像倾斜角度的中位数
    median_angle = getMedianAngle(lines)
    print("Median Angle:", median_angle)

    drawing = np.zeros(src.shape[:], dtype=np.uint8)
    # 画出线条
    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(drawing, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA)

    showAndWaitKey("houghP", drawing)
    """
    旋转角度大于0,则逆时针旋转,否则顺时针旋转
    """
    rotateImg = rotate(src, median_angle)
    cv2.imshow("rotateImg", rotateImg)
    cv2.waitKey()
    cv2.destroyAllWindows()
    cv2.imwrite('./text_correct/result.jpg', rotateImg)


def showAndWaitKey(winName, img):
    cv2.imshow(winName, img)
    cv2.waitKey()


if __name__ == "__main__":
    getCorrect2()

原图和结果图分别如下:

原图

矫正后的图像


如果我的这篇文章帮助到了你,那我也会感到很高兴,一个人能走多远,在于与谁同行


参考


  1. 实战 | OpenCV实现扫描文本矫正应用与实现详解(附源码) ↩︎
相关推荐
昵称是6硬币1 小时前
YOLOv11: AN OVERVIEW OF THE KEY ARCHITECTURAL ENHANCEMENTS目标检测论文精读(逐段解析)
图像处理·人工智能·深度学习·yolo·目标检测·计算机视觉
费弗里2 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(1)
python·dash
云天徽上9 天前
【目标检测】图像处理基础:像素、分辨率与图像格式解析
图像处理·人工智能·目标检测·计算机视觉·数据可视化
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
学Linux的语莫9 天前
python基础语法
开发语言·python
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python
Ven%9 天前
PyTorch 张量(Tensors)全面指南:从基础到实战
人工智能·pytorch·python
mahuifa9 天前
PySide环境配置及工具使用
python·qt·环境配置·开发经验·pyside