opencv+python實現(xiàn)圖像矯正
更新時間:2022年08月01日 09:44:41 作者:椰樹林YSL
這篇文章主要為大家詳細介紹了opencv+python實現(xiàn)圖像矯正,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了opencv+python實現(xiàn)圖像矯正的具體代碼,供大家參考,具體內容如下
需求:將斜著拍攝的文本圖像進行矯正
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])
? ? ? ? # 排除非文本區(qū)域
? ? ? ? if w < 35 and h < 35:
? ? ? ? ? ? continue
? ? ? ? # 防止矩形區(qū)域過大不精準 ? ?
? ? ? ? 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)算法流程

算法核心思想:
獲取圖像中的文本區(qū)域矩形輪廓,找到其中面積最大的,對其進行最小外接矩形計算,得到最小外接矩形的旋轉角度,再根據旋轉角度進行仿射變換。
測試效果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)將MySQL數據庫表中的數據導出生成csv格式文件的方法
這篇文章主要介紹了Python實現(xiàn)將MySQL數據庫表中的數據導出生成csv格式文件的方法,涉及Python針對mysql數據庫的連接、查詢、csv格式數據文件的生成等相關操作技巧,需要的朋友可以參考下2018-01-01
python selenium 查找隱藏元素 自動播放視頻功能
這篇文章主要介紹了python selenium 查找隱藏元素 自動播放視頻功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
Windows下Anaconda和PyCharm的安裝與使用詳解
這篇文章主要介紹了Windows下Anaconda和PyCharm的安裝與使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04

