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

Index 目录索引

写在前面

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

解决思路

因为扫描图像中的大部分文字倾斜后,同一行文字也在同一条直线,所以可以通过拟合直线来计算文本倾斜角度,接着对这些倾斜角度进行排序,选择其中值作为最终的旋转角度,通过旋转来实现倾斜图像的水平矫正^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实现扫描文本矫正应用与实现详解(附源码) ↩︎
相关推荐
呱牛do it13 分钟前
Python Matplotlib图形美化指南
开发语言·python·matplotlib
pianmian116 分钟前
python制图之小提琴图
开发语言·python·信息可视化
橙子小哥的代码世界19 分钟前
【机器学习】【KMeans聚类分析实战】用户分群聚类详解——SSE、CH 指数、SC全解析,实战电信客户分群案例
人工智能·python·机器学习·kmeans·数据科学·聚类算法·肘部法
计算机徐师兄19 分钟前
Python基于Flask的豆瓣Top250电影数据可视化分析与评分预测系统(附源码,技术说明)
python·flask·豆瓣top250电影数据可视化·豆瓣top250电影评分预测·豆瓣电影数据可视化分析系统·豆瓣电影评分预测系统·豆瓣电影数据
k layc23 分钟前
【论文解读】《Training Large Language Models to Reason in a Continuous Latent Space》
人工智能·python·机器学习·语言模型·自然语言处理·大模型推理
阿正的梦工坊37 分钟前
Sliding Window Attention(滑动窗口注意力)解析: Pytorch实现并结合全局注意力(Global Attention )
人工智能·pytorch·python
喜-喜1 小时前
Python pip 缓存清理:全面方法与操作指南
python·缓存·pip
rgb2gray1 小时前
GeoHD - 一种用于智慧城市热点探测的Python工具箱
人工智能·python·智慧城市
MZWeiei2 小时前
Matplotlib,Streamlit,Django大致介绍
python·django·matplotlib
游客5202 小时前
自动化办公|xlwings生成图表
python·自动化