Python 実践 データ加工/可視化 100本ノック に挑戦 ノック67

ノック67 :画像を回転させてみよう

 

sample.jpg画像を回転させます。

cv2.rotateで画像を回転させます。ROTATE_90_CLOCKWISEは90度右周りに回転します。

 

import cv2
img = cv2.imread('data/sample.jpg')
img_resized = cv2.resize(img, (500, 300))

img_rotated = cv2.rotate(img_resized,cv2.ROTATE_90_CLOCKWISE)
cv2.imshow('resized 500x300',img_rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

実行結果

rotated 90

 

 

次に45度回転を行います。45度回転するための引数はなく、アフィン変換という変換方法で実現します。

まず画像の中心点を求めます。shapeの戻り値は縦、横、色情報の3つですが、縦と横の情報だけでいいのでおしりに[:2]を付加しています。

height,width = img_resized.shape[:2]
center = (int(width/2),int(height/2))

 

cv2.getRotationMatrix2Dで45度回転させます。

中心点、回転角度、スケールサイズを引数で指定します。

rot = cv2.getRotationMatrix2D(center,45,1)

 

最後にアフィン変換という変換方式を使って45度の画像に変換します。

img_rotated = cv2.warpAffine(img_resized,rot,(width,height))
cv2.imshow('rotated_45',img_rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

実行結果

rotated 45

 

反転画像を作成する場合は、cv2.flipを使用します。第2引数0で上下反転、1で左右反転となります。

img_reverse = cv2.flip(img_resized,0)

cv2.imshow('reverse 0',img_reverse)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

 

実行結果

reverse 0

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

/* -----codeの行番号----- */