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

Index 目录索引

写在前面

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

解决思路

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

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

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实现扫描文本矫正应用与实现详解(附源码) ↩︎

  • 9
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值