In [1]:
import cv2
import numpy as np
import math

In [2]:
img = cv2.imread('data/src/lena.jpg')

In [3]:
h, w, c = img.shape
print(h, w, c)


225 400 3


In [4]:
mat = cv2.getRotationMatrix2D((w / 2, h / 2), 45, 0.5)
print(mat)


[[  0.35355339   0.35355339  89.51456544]
 [ -0.35355339   0.35355339 143.43592168]]

In [5]:
affine_img = cv2.warpAffine(img, mat, (w, h))
cv2.imwrite('data/dst/opencv_affine.jpg', affine_img)


Out[5]:
True


In [6]:
affine_img_half = cv2.warpAffine(img, mat, (w, h // 2))
cv2.imwrite('data/dst/opencv_affine_half.jpg', affine_img_half)


Out[6]:
True


In [7]:
affine_img_flags = cv2.warpAffine(img, mat, (w, h), flags=cv2.INTER_CUBIC)
cv2.imwrite('data/dst/opencv_affine_flags.jpg', affine_img_flags)


Out[7]:
True


In [8]:
affine_img_bv = cv2.warpAffine(img, mat, (w, h), borderValue=(0, 128, 255))
cv2.imwrite('data/dst/opencv_affine_border_value.jpg', affine_img_bv)


Out[8]:
True


In [9]:
dst = img // 4

In [10]:
affine_img_bm_bt = cv2.warpAffine(img, mat, (w, h), borderMode=cv2.BORDER_TRANSPARENT, dst=dst)
cv2.imwrite('data/dst/opencv_affine_border_transparent.jpg', affine_img_bm_bt)


Out[10]:
True


In [11]:
affine_img_bm_br = cv2.warpAffine(img, mat, (w, h), borderMode=cv2.BORDER_REPLICATE)
cv2.imwrite('data/dst/opencv_affine_border_replicate.jpg', affine_img_bm_br)


Out[11]:
True


In [12]:
affine_img_bm_bw = cv2.warpAffine(img, mat, (w, h), borderMode=cv2.BORDER_WRAP)
cv2.imwrite('data/dst/opencv_affine_border_wrap.jpg', affine_img_bm_bw)


Out[12]:
True


In [13]:
mat = np.array([[1, 0, 50], [0, 1, 20]], dtype=np.float32)
print(mat)


[[ 1.  0. 50.]
 [ 0.  1. 20.]]

In [14]:
affine_img_translation = cv2.warpAffine(img, mat, (w, h))
cv2.imwrite('data/dst/opencv_affine_translation.jpg', affine_img_translation)


Out[14]:
True


In [15]:
a = math.tan(math.radians(15))

In [16]:
mat = np.array([[1, a, 0], [0, 1, 0]], dtype=np.float32)
print(mat)


[[1.        0.2679492 0.       ]
 [0.        1.        0.       ]]

In [17]:
affine_img_skew_x = cv2.warpAffine(img, mat, (int(w + h * a), h))
cv2.imwrite('data/dst/opencv_affine_skew_x.jpg', affine_img_skew_x)


Out[17]:
True


In [18]:
mat = np.array([[1, 0, 0], [a, 1, 0]], dtype=np.float32)
print(mat)


[[1.        0.        0.       ]
 [0.2679492 1.        0.       ]]

In [19]:
affine_img_skew_y = cv2.warpAffine(img, mat, (w, int(h + w * a)))
cv2.imwrite('data/dst/opencv_affine_skew_y.jpg', affine_img_skew_y)


Out[19]:
True