提示:内容整理自:https://github.com/gzr2017/ImageProcessing100Wen
CV小白从0开始学数字图像处理
31 仿射变换(Afine Transformations)——倾斜
- 使用仿射变换,输出(1)那样的x轴倾斜30度的图像(dx=30),这种变换被称为
X-sharing
。 - 使用仿射变换,输出(2)那样的y轴倾斜30度的图像(dy=30),这种变换被称为
Y-sharing
。 - 使用仿射变换,输出(3)那样的x轴、y轴都倾斜30度的图像(dx = 30, dy = 30)。
原图像的大小为hxw,使用下面各式进行仿射变换。
(1) X-sharing (2) Y-sharing
a = dx / h a = dy / w
x' 1 a tx x x' 1 0 tx x
[ y' ] = [ 0 1 ty ][ y ] [ y' ] = [ a 1 ty ][ y ]
1 0 0 1 1 1 0 0 1 1
代码如下:
1.引入库
CV2计算机视觉库
import cv2
import numpy as np
import matplotlib.pyplot as plt
2.读入数据
_img = cv2.imread("imori.jpg").astype(np.float32)
H, W, C = _img.shape
3.倾斜
dx = 30.
dy = 30.
a = 1.
b = dx / H
c = dy / W
d = 1.
tx = 0.
ty = 0.
img = np.zeros((H+2, W+2, C), dtype=np.float32)
img[1:H+1, 1:W+1] = _img
H_new = np.ceil(dy + H).astype(np.int)
W_new = np.ceil(dx + W).astype(np.int)
out = np.zeros((H_new, W_new, C), dtype=np.float32)
x_new = np.tile(np.arange(W_new), (H_new, 1))
y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1)
adbc = a * d - b * c
x = np.round((d * x_new - b * y_new) / adbc).astype(np.int) - tx + 1
y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1
x = np.minimum(np.maximum(x, 0), W+1).astype(np.int)
y = np.minimum(np.maximum(y, 0), H+1).astype(np.int)
out[y_new, x_new] = img[y, x]
out = out.astype(np.uint8)
4.保存结果
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.imwrite("out.jpg", out)