栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

opencv+python 图像矫正

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

opencv+python 图像矫正

需求:将斜着拍摄的文本图像进行矫正

python代码
import numpy as np
import cv2 as cv


def shape_correction(img):
    (height, width) = img.shape[:2]
    print(img.shape)

    img_gau = cv.GaussianBlur(img, (5, 5), 0)
    canny = cv.Canny(img_gau, 60, 200)
    # cv.imshow("g-canny", canny)
    
    kernel = cv.getStructuringElement(cv.MORPH_CROSS, (4,3)) 
    
    dilated = cv.dilate(canny, kernel, iterations=8)  
    # cv.imshow('img_dilated', dilated)

    # 寻找轮廓
    contours, hierarchy = cv.findContours(dilated, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    # print(len(contours), hierarchy, sep='n')

    # 找到最外层面积最大的轮廓

    area = 0
    # print("area:{}".format(area))

    index = 0
    for i in range(len(contours)):
        x, y, w, h = cv.boundingRect(contours[i])
        # 排除非文本区域
        if w < 35 and h < 35:
            continue
        # 防止矩形区域过大不精准    
        if h > 0.99 * height or w > 0.99 * width:
            continue
        # draw rectangle around contour on original image
        # cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)
        tmpArea = w * h
        if tmpArea >= area:
            area = tmpArea
            index = i

    # 得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度)
    rect = cv.minAreaRect(contours[index])
    # 画出矩形框
    # box = cv.boxPoints(rect)
    # box = np.int0(box)
    # cv.drawContours(img, [box], 0, (0, 0, 255), 2)

    # cv.imshow('img', img)
    print("rect:{}".format(rect))
    angle = rect[-1]
    # print(angle)

    # 角度大于85度或小于5度不矫正
    if angle > 85 or angle < 5:
        angle = 0
    elif angle < 45:
        angle = angle - 0
    else:
        angle = angle - 90

    M = cv.getRotationMatrix2D(rect[0], angle, 1)
    rotated = cv.warpAffine(img, M, (width, height), flags=cv.INTER_CUBIC, borderValue=(255, 255, 255))
    
    cv.imshow('Rotated', rotated)
    return rotated


src = cv.imread('/res-normal.png', 0)
rotated = shape_correction(src)
cv.waitKey(0)
算法流程


算法核心思想:
获取图像中的文本区域矩形轮廓,找到其中面积最大的,对其进行最小外接矩形计算,得到最小外接矩形的旋转角度,再根据旋转角度进行仿射变换。

测试效果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/833704.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号