写文章不易,如果您觉得此文对您有所帮助,请帮忙点赞、评论、收藏,感谢您!
一. 仿射变换介绍:
二. 仿射变换 公式:
仿射变换过程,(x,y)表示原图像中的坐标,(x',y')表示目标图像的坐标 ↑
要实现其他功能的仿射变换,请读者照葫芦画瓢,自行举一反三:
实验目标,将输入图像在x方向上放大至原来的1.5倍,在y方向上缩小为原来的0.6倍。并沿x轴负向移动30像素,y轴正向移动100像素。
实验代码:
import cv2
import numpy as np
# Affine Transformation
def affine(img, a, b, c, d, tx, ty):
H, W, C = img.shape
# temporary image
tem = img.copy()
img = np.zeros((H+2, W+2, C), dtype=np.float32)
img[1:H+1, 1:W+1] = tem
# get new image shape
H_new = np.round(H * d).astype(np.int)
W_new = np.round(W * a).astype(np.int)
out = np.zeros((H_new+1, W_new+1, C), dtype=np.float32)
# get position of new image
x_new = np.tile(np.arange(W_new), (H_new, 1))
y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1)
# 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)
# assgin pixcel to new image
out[y_new, x_new] = img[y, x]
out = out[:H_new, :W_new]
out = out.astype(np.uint8)
return out
# Read image
image = cv2.imread("../paojie.jpg").astype(np.float32)
# Affine Transformation
out = affine(image, a=1.5, b=0, c=0, d=0.6, tx=-30, ty=100)
# Save result
cv2.imshow("result", out)
cv2.imwrite("out.jpg", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
四. 实验中的难点,晦涩难懂的代码讲解:
五. 实验结果:
原图 ↑
仿射变换结果(x*1.5-30,y*0.6+100) ↑
六. 参考文献:
七. 版权声明:
未经作者允许,请勿随意转载抄袭,抄袭情节严重者,作者将考虑追究其法律责任,创作不易,感谢您的理解和配合!