Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

傾き補正

文書のスキャン時に少し傾けてスキャンしてしまった画像があるとする。

画像の分析の前処理として、画像の傾きを水平に直してから処理したい…という状況を想定する

サンプル画像

Source
<PIL.Image.Image image mode=RGB size=400x600>
Source
<PIL.Image.Image image mode=RGB size=400x600>

ライブラリを使う場合

https://github.com/sbrunner/deskew

angle=-2.0
<Figure size 640x480 with 1 Axes>

表など、まっすぐな直線の要素がある場合

スキャンした画像が会計の資料などで表が中心の画像だと、表の直線を検知して傾きを計算するのがよさそう

手順:

  1. 線の検出

    1. 例:Canny法でエッジを推定→ハフ変換で表の直線を推定

    2. 例:FastLineDetection

  2. 直線の角度を計算

  3. 補正すべき角度を計算

  4. 回転して補正

Canny法によるEdge Detection

OpenCV: Canny Edge Detection

傾かせる

<Figure size 640x480 with 1 Axes>

1. ハフ変換による線検出

Canny法によるエッジ検出

今回の表については不要かも…?

<Figure size 800x600 with 2 Axes>

ハフ変換

HoughLinesとHoughLinesPの違い:

  • HoughLinesはすべての点の線を取る

  • HoughLinesPは確率的で、ランダムサンプリングした点だけ計算するので効率がいい

<Figure size 800x600 with 1 Axes>

角度の算出

0.9514779758679796

回転

getRotationMatrix2D

OpenCV: Geometric Image Transformations

affine matrix

[αβ(1−α)⋅center.x−β⋅center.y−βαβ⋅center.x+(1−α)⋅center.y]\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}
α=scale⋅cos⁡angle,β=scale⋅sin⁡angle\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle},\\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}

を取得する

<Figure size 800x600 with 1 Axes>

2. FastLineDetectorによる線検出

pylsdパッケージのLSDを使ったほうがもっといいかも?

32 lines are detected
<Figure size 640x480 with 1 Axes>

角度の算出

1.6194360861896437

回転

getRotationMatrix2D

OpenCV: Geometric Image Transformations

affine matrix

[αβ(1−α)⋅center.x−β⋅center.y−βαβ⋅center.x+(1−α)⋅center.y]\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}
α=scale⋅cos⁡angle,β=scale⋅sin⁡angle\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle},\\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}

を取得する

<Figure size 800x600 with 1 Axes>