基于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实现扫描文本矫正应用与实现详解(附源码) ↩︎
相关推荐
HAPPY酷13 分钟前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
gpfyyds6661 小时前
Python代码练习
开发语言·python
aiguangyuan2 小时前
使用LSTM进行情感分类:原理与实现剖析
人工智能·python·nlp
小小张说故事2 小时前
BeautifulSoup:Python网页解析的优雅利器
后端·爬虫·python
luoluoal2 小时前
基于python的医疗领域用户问答的意图识别算法研究(源码+文档)
python
Shi_haoliu2 小时前
python安装操作流程-FastAPI + PostgreSQL简单流程
python·postgresql·fastapi
ZH15455891312 小时前
Flutter for OpenHarmony Python学习助手实战:API接口开发的实现
python·学习·flutter
小宋10213 小时前
Java 项目结构 vs Python 项目结构:如何快速搭一个可跑项目
java·开发语言·python
一晌小贪欢3 小时前
Python 爬虫进阶:如何利用反射机制破解常见反爬策略
开发语言·爬虫·python·python爬虫·数据爬虫·爬虫python