実行環境
Google Colaboratoryで画像を読み込む為の準備
from google.colab import files
from google.colab import drive
drive.mount('/content/drive')
img = cv2.imread("/content/drive/My Drive/Colab Notebooks/img/Lenna.bmp")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #matplot用に変換
必要なライブラリの読み込み
import cv2 #opencv
import matplotlib.pyplot as plt
%matplotlib inline
フリップ変換
# 新規ウインドウ作成
fig = plt.figure()
# オリジナル画像
ax1 = fig.add_subplot(2, 1, 1)
ax1.set_title("Original",fontsize=20)
plt.imshow(img)
# 上下反転 = 0
ax2 = fig.add_subplot(2, 3, 4)
ax2.set_title("flipCode = 0",fontsize=20)
plt.imshow(cv2.flip(img,flipCode = 0))
# 上下左右反転 = -1
ax3 = fig.add_subplot(2, 3, 5)
ax3.set_title("flipCode = -1",fontsize=20)
plt.imshow(cv2.flip(img,flipCode = -1))
# 左右反転 = 1
ax4 = fig.add_subplot(2, 3, 6)
ax4.set_title("flipCode = 1",fontsize=20)
plt.imshow(cv2.flip(img,flipCode = 1))
plt.subplots_adjust(hspace=0.6,wspace=1.2) #グラフ間隔を調整。
plt.show()
フリップ変換結果
フリップ記述
cv2.flip(src,flipCode)
src = 画像
flipCode = フリップ方向
flipcode | 方向 |
---|---|
0 | 上下反転 |
<0 | 上下左右反転 |
0|左右反転
リサイズ
# 新規ウインドウ作成
fig = plt.figure()
height = img.shape[0]
width = img.shape[1]
# オリジナル画像
ax1 = fig.add_subplot(2, 1, 1)
ax1.set_title("Original",fontsize=20)
plt.imshow(img)
# 16×16
ax2 = fig.add_subplot(2, 3, 4)
ax2.set_title("16*16",fontsize=20)
plt.imshow(cv2.resize(img,(16,16)))
# 50%
ax3 = fig.add_subplot(2, 3, 5)
ax3.set_title("50%",fontsize=20)
plt.imshow(cv2.resize(img,(int(width*0.5),int(height*0.5))))
# 200%*50%
ax3 = fig.add_subplot(2, 3, 6)
ax3.set_title("200%*50%",fontsize=20)
plt.imshow(cv2.resize(img,(int(width*2),int(height*0.5))))
plt.subplots_adjust(hspace=0.6,wspace=1.2) #グラフ間隔を調整。
plt.show()
リサイズ変換結果
回転
height = img.shape[0]
width = img.shape[1]
kaitenP = (int(width/2),int(height/2)) #中央を支点に回転させる
# kaitenP = (80,80)
cv2.circle(img,kaitenP,10,(0,255,0),-1)#支点を表示
# 回転処理
deg = 23.4
bairitu = 0.5
affin_trans = cv2.getRotationMatrix2D(kaitenP,deg,bairitu)
dst = cv2.warpAffine(img,affin_trans,(width,height))
plt.imshow(dst)
回転結果
投影
import numpy as np
# ソース画像の四隅を設定
x0 = 0
x1 = 252
y0 = 0
y1 = 252
list_src = np.float32([[x0,y0],[x0,y1],[x1,y1],[x1,y0]])
# 左上、左下、右下、右上の変換先座標の設定
list_dst = np.float32([
[0,0],
[100,200],
[252,252],
[150,50]])
# 変換処理
perspective_matrix = cv2.getPerspectiveTransform(list_src,list_dst)
dst = cv2.warpPerspective(img,perspective_matrix,(x1,y1))
plt.imshow(dst)
投影結果
すごく簡易的なものだけ実行。
奥深そうなので、細かいところは実際に取り組む際に掘り下げ。
トリミング
# y100~200 x50~250をぬきだし
dst = img[100:200,50:250]
plt.imshow(dst)
トリミングは簡単ですね。
なんかカットインみたいでレナさんかっこいい。