图像仿射变换之图像倾斜 含pyhon源码

如果您觉得本文对您有所帮助,请帮忙点赞,感谢!


一. 仿射变换算法原理:


仿射变换过程,(x,y)表示原图像中的坐标,(x',y')表示目标图像的坐标 ↑
 

二. 仿射变换倾斜算法原理:

    原图像大小为h*w

    X-sharing:


倾斜之x轴逆时针旋转tx度时的图像仿射变换公式 ↑
 

    Y-sharing:


倾斜之y轴逆时针旋转ty度时的图像仿射变换公式 ↑
 

三. 实验:python实现仿射变换 ——> 图像倾斜 ——> x轴逆时针旋转 30°,y轴逆时针旋转30°

 1 import cv2
 2 import numpy as np
 3 import matplotlib.pyplot as plt
 4 
 5 # Affine
 6 def affine(img, dx=30, dy=30):
 7     # get shape
 8     H, W, C = img.shape
 9 
10     # Affine hyper parameters
11     a = 1.
12     b = dx / H
13     c = dy / W
14     d = 1.
15     tx = 0.
16     ty = 0.
17 
18     # prepare temporary
19     _img = np.zeros((H+2, W+2, C), dtype=np.float32)
20 
21     # insert image to center of temporary
22     _img[1:H+1, 1:W+1] = img
23 
24     # prepare affine image temporary
25     H_new = np.ceil(dy + H).astype(np.int)
26     W_new = np.ceil(dx + W).astype(np.int)
27     out = np.zeros((H_new, W_new, C), dtype=np.float32)
28 
29     # preprare assigned index
30     x_new = np.tile(np.arange(W_new), (H_new, 1))
31     y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1)
32 
33     # prepare inverse matrix for affine
34     adbc = a * d - b * c
35     x = np.round((d * x_new  - b * y_new) / adbc).astype(np.int) - tx + 1
36     y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1
37 
38     x = np.minimum(np.maximum(x, 0), W+1).astype(np.int)
39     y = np.minimum(np.maximum(y, 0), H+1).astype(np.int)
40 
41     # assign value from original to affine image
42     out[y_new, x_new] = _img[y, x]
43     out = out.astype(np.uint8)
44 
45     return out
46 
47 # Read image
48 image1 = cv2.imread("../paojie.jpg").astype(np.float32)
49 # Affine
50 out = affine(image1, dx=30, dy=30)
51 # Save result
52 cv2.imshow("result", out)
53 cv2.imwrite("out.jpg", out)
54 cv2.waitKey(0)
55 cv2.destroyAllWindows()

四. 实验结果:


x轴和y轴倾斜后图像 ↑
 

原图 ↑
 

五. 代码疑难点讲解:

    请参考:https://www.cnblogs.com/wojianxin/p/12519498.html 的第五部分内容


六.  参考内容:

    https://www.jianshu.com/p/08611282153f


七. 版权声明:

    未经作者允许,请勿随意转载抄袭,抄袭情节严重者,作者将考虑追究其法律责任,创作不易,感谢您的理解和配合!

原文地址:https://www.cnblogs.com/wojianxin/p/12522945.html