備忘録

弱小院生のメモ

画像傾きの補正

文字認識その他色々な処理の前に画像の傾き(回転)を自動補正したいのでやった。

方法

cv2.Canny() でエッジ検出

→  cv2.HoughLinesP()で直線検出

→ 水平方向の直線の平均角度を取る

→ 直線が水平になるように画像全体を回転

# 画像の傾き検出
# @return 水平からの傾き角度
def get_degree(img):
    l_img = img.copy()
    gray_image = cv2.cvtColor(l_img, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray_image,50,150,apertureSize = 3)
    minLineLength = 200
    maxLineGap = 30
    lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)

    sum_arg = 0;
    count = 0;
    for line in lines:
        for x1,y1,x2,y2 in line:
            arg = math.degrees(math.atan2((y2-y1), (x2-x1)))
            HORIZONTAL = 0
            DIFF = 20 # 許容誤差 -> -20 - +20 を本来の水平線と考える
            if arg > HORIZONTAL - DIFF and arg < HORIZONTAL + DIFF : 
                sum_arg += arg;
                count += 1

    if count == 0:
        return HORIZONTAL
    else:
        return (sum_arg / count) - HORIZONTAL;
arg = get_degree(img)
rotate_img = ndimage.rotate(img, arg)

結果

f:id:reverent_f:20170124190820p:plain:w250

f:id:reverent_f:20170124190823p:plain:w250

f:id:reverent_f:20170124190825p:plain:w250

f:id:reverent_f:20170124190853p:plain:w250

見た目上あまり変化がないように見えるが、後続の処理の精度は向上した