一、通過minAreaRect方法獲得斜率
參考資料
:
【1】有關角度的說明,可供參考
【2】https://blog.csdn.net/qq_24237837/article/details/77850496
主要步驟
:
1、輸入圖片
2、灰度化
3、圖像取非
4、二值化
5、獲得有文本區域的點集
6、求點集的最小外接矩形框,并返回旋轉角度
7、仿射變換,將原圖校正
參考代碼 :
import numpy as np
import os
import cv2
import math
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 getCorrect():
#讀取圖片,灰度化
src = cv2.imread("D:\\MyData\\tiltData\\neg.png")
cv2.imshow("src",src)
cv2.waitKey()
gray = cv2.imread("D:\\MyData\\tiltData\\neg.png",cv2.IMREAD_GRAYSCALE)
cv2.imshow("gray",gray)
cv2.waitKey()
#圖像取非
grayNot = cv2.bitwise_not(gray)
cv2.imshow("grayNot",grayNot)
cv2.waitKey()
#二值化
threImg = cv2.threshold(grayNot,100,255,cv2.THRESH_BINARY,)[1]
cv2.imshow("threImg",threImg)
cv2.waitKey()
#獲得有文本區域的點集,求點集的最小外接矩形框,并返回旋轉角度
coords = np.column_stack(np.where(threImg>0))
angle = cv2.minAreaRect(coords)[-1]
if angle < -45:
angle = -(angle + 90)
else:
angle = -angle
#仿射變換,將原圖校正
dst = rotate(src,angle)
cv2.imshow("dst",dst)
cv2.waitKey()
print(angle)
if __name__ == "__main__":
getCorrect()
二、通過霍夫變換、反三角函數獲得斜率
參考資料
:
【1】https://www.jianshu.com/p/34d6dc466e81
【2】該博主有傾斜圖片數據可供下載,對我的測試有很大幫助,非常感謝
主要步驟
:
1、輸入圖片
2、灰度化
3、腐蝕、膨脹
4、邊緣檢測
5、霍夫變換得到線條并畫出
6、計算角度
7、仿射變換,將原圖校正
參考代碼 :
import numpy as np
import os
import cv2
import math
from scipy import misc,ndimage
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("D:\\MyData\\tiltData\\neg.png",cv2.IMREAD_COLOR)
showAndWaitKey("src",src)
gray = cv2.imread("D:\\MyData\\tiltData\\neg.png",cv2.IMREAD_GRAYSCALE)
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)
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)
"""
計算角度,因為x軸向右,y軸向下,所有計算的斜率是常規下斜率的相反數,我們就用這個斜率(旋轉角度)進行旋轉
"""
k = float(y1-y2)/(x1-x2)
thera = np.degrees(math.atan(k))
"""
旋轉角度大于0,則逆時針旋轉,否則順時針旋轉
"""
rotateImg = rotate(src,thera)
cv2.imshow("rotateImg",rotateImg)
cv2.waitKey()
def showAndWaitKey(winName,img):
cv2.imshow(winName,img)
cv2.waitKey()
if __name__ == "__main__":
getCorrect()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
