Python OpenCV3で画像のアフィン変換(中心を指定した回転)

Posted on


前回の方法とは異なり、画像の中心を指定して回転する方法を紹介。

前提

ディレクトリ構成などはこことかこことか。

&nbsp

元画像

この画像(slack_botter.png)を使う。
以前の例だとsource/imageディレクトリ配下に設置する。

slack_botter

 

getRotationMatrix2Dメソッドの解説

getRotationMatrix2Dメソッドの引数は次の通り

cv2.getRotationMatrix2D(画像の中心の座標,回転させたい角度,拡大比率)

 

実際に回転してみる

getRotationMatrix2Dメソッドで回転行列を生成し、アフィン変換を行う。

sourceディレクトリにrotation.pyを作成する。

# -*- coding: utf-8 -*-

import cv2
import numpy as np

if __name__ == '__main__':

    # 画像読み込み
    img_src = cv2.imread("./image/slack_botter.png", 1)

    # 画像の中心位置
    # 今回は画像サイズの中心をとっている
    center = tuple(np.array([img_src.shape[1] * 0.5, img_src.shape[0] + 0.5]))

    # 画像サイズの取得(横, 縦)
    size = tuple(np.array([img_src.shape[1], img_src.shape[0]]))

    # 回転させたい角度
    # ラジアンではなく角度(°)
    angle = 45.0

    # 拡大比率
    scale = 1.0

    # 回転変換行列の算出
    rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)

    # アフィン変換
    img_rot = cv2.warpAffine(img_src, rotation_matrix, size, flags=cv2.INTER_CUBIC)

    # 表示
    cv2.imshow("Show ROTATION Image", img_rot)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

実行してみる。

(opencv_python)$ python rotation.py

スクリーンショット 2015-06-25 22.19.12

 

この間と違う感じで回転した。

 

Tags: , , , ,


コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">