寫文章不易,如果您覺得此文對您有所幫助,請幫忙點贊、評論、收藏,感謝您!
一. 仿射變換介紹:
請參考:圖解圖像仿射變換:https://www.cnblogs.com/wojianxin/p/12518393.html
二. 仿射變換 公式:
三. 仿射變換——圖像平移 算法:
四. python實現仿射變換——圖像平移
1 import cv2 2 import numpy as np 3 4 # 圖像仿射變換->圖像平移 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 # 避免目標圖像對應的原圖像中的坐標溢出 28 x = np.minimum(np.maximum(x, 0), W+1).astype(np.int) 29 y = np.minimum(np.maximum(y, 0), H+1).astype(np.int) 30 31 # assgin pixcel to new image 32 out[y_new, x_new] = img[y, x] 33 34 out = out[:H_new, :W_new] 35 out = out.astype(np.uint8) 36 37 return out 38 39 40 # Read image 41 image1 = cv2.imread("../paojie.jpg").astype(np.float32) 42 43 # Affine : 平移,tx(W向):向右30;ty(H向):向上100 44 out = affine(image1, a=1, b=0, c=0, d=1, tx=30, ty=-100) 45 46 # Save result 47 cv2.imshow("result", out) 48 cv2.imwrite("out.jpg", out) 49 cv2.waitKey(0) 50 cv2.destroyAllWindows()
五. 代碼實現過程中遇到的問題:
① 原圖像進行仿射變換時,原圖像中的坐標可能超出了目標圖像的邊界,需要對原圖像坐標進行截斷處理。如何做呢?首先,計算目標圖像坐標對應的原圖像坐標,算法如下:
以下代碼實現了該逆變換:
# get position of original image by affine
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)
原圖像范圍:長W,高H
② 難點解答:
x_new = np.tile(np.arange(W_new), (H_new, 1))
y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1)
造這兩個矩陣是為了這一步:
# assgin pixcel to new image
out[y_new, x_new] = img[y, x]
六. 實驗結果:
七. 參考內容:
① https://www.jianshu.com/p/1cfb3fac3798
八. 版權聲明:
未經作者允許,請勿隨意轉載抄襲,抄襲情節嚴重者,作者將考慮追究其法律責任,創作不易,感謝您的理解和配合!
