python实现图像仿射变换 以图像缩放并平移为例讲解

写文章不易,如果您觉得此文对您有所帮助,请帮忙点赞、评论、收藏,感谢您!


一. 仿射变换介绍:

    请参考:图解图像仿射变换:https://www.cnblogs.com/wojianxin/p/12518393.html

        图像仿射变换之图像平移:https://www.cnblogs.com/wojianxin/p/12519498.html


二. 仿射变换 公式:


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

三. 实验:利用我的上一篇文章(https://www.jianshu.com/p/1cfb3fac3798)的算法实现图像仿射变换——图像缩放

        要实现其他功能的仿射变换,请读者照葫芦画瓢,自行举一反三:

实验目标,将输入图像在x方向上放大至原来的1.5倍,在y方向上缩小为原来的0.6倍。并沿x轴负向移动30像素,y轴正向移动100像素。

实验代码:

 1 import cv2
 2 import numpy as np
 3 
 4 # Affine Transformation
 5 def affine(img, a, b, c, d, tx, ty):
 6     H, W, C = img.shape
 7 
 8     # temporary image
 9     tem = img.copy()
10     img = np.zeros((H+2, W+2, C), dtype=np.float32)
11     img[1:H+1, 1:W+1] = tem
12 
13     # get new image shape
14     H_new = np.round(H * d).astype(np.int)
15     W_new = np.round(W * a).astype(np.int)
16     out = np.zeros((H_new+1, W_new+1, C), dtype=np.float32)
17 
18     # get position of new image
19     x_new = np.tile(np.arange(W_new), (H_new, 1))
20     y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1)
21 
22     # get position of original image by affine
23     adbc = a * d - b * c
24     x = np.round((d * x_new  - b * y_new) / adbc).astype(np.int) - tx + 1
25     y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1
26 
27     x = np.minimum(np.maximum(x, 0), W+1).astype(np.int)
28     y = np.minimum(np.maximum(y, 0), H+1).astype(np.int)
29 
30     # assgin pixcel to new image
31     out[y_new, x_new] = img[y, x]
32 
33     out = out[:H_new, :W_new]
34     out = out.astype(np.uint8)
35 
36     return out
37 
38 # Read image
39 image = cv2.imread("../paojie.jpg").astype(np.float32)
40 # Affine
41 out = affine(image, a=1.5, b=0, c=0, d=0.6, tx=-30, ty=100)
42 # Save result
43 cv2.imshow("result", out)
44 cv2.imwrite("out.jpg", out)
45 cv2.waitKey(0)
46 cv2.destroyAllWindows()

四. 实验中的难点,晦涩难懂的代码讲解:

    可以参考:https://www.cnblogs.com/wojianxin/p/12519498.html  或者

                      https://www.jianshu.com/p/1cfb3fac3798


五. 实验结果:


原图 ↑
 

仿射变换结果(x*1.5-30,y*0.6+100) ↑
 

六. 参考文献:

   https://www.jianshu.com/p/464370cd6408


七. 版权声明:

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

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