『youcans 的 OpenCV 例程200篇 - 总目录』
【youcans 的 OpenCV 例程200篇】33. 图像的复合变换
图像的复合变换是指对给定的图像连续进行多次上述的平移、旋转、翻转、缩放、错切等基本变换,也称为级联变换。
对给定图像按一定顺序执行若干次基本变换,其变换矩阵仍然可以用 3x3 阶变换矩阵表示。进一步地,对图像依次执行基本变换 F1、F2、…Fn 的变换矩阵分别为 M1、M2、…Mn,可以证明,以图像中心点为中心进行比例、旋转进行变换,则复合变换的变换矩阵 M 等于各基本变换矩阵依次相乘所得到的组合矩阵:
M
=
M
1
×
M
2
×
⋯
×
M
n
M = M_1 \times M_2 \times \dots \times M_n
M=M1×M2×⋯×Mn
缩放:
M
A
Z
=
[
f
x
0
0
0
f
y
0
0
0
1
]
M_{AZ} = \begin{bmatrix} fx &0 &0\\ 0 &f_y &0\\ 0 &0 &1 \end{bmatrix}
MAZ=⎣⎡fx000fy0001⎦⎤
旋转:
M
A
R
=
[
c
o
s
θ
−
s
i
n
θ
0
s
i
n
θ
c
o
s
θ
0
0
0
1
]
M_{AR} = \begin{bmatrix} cos \theta &-sin \theta &0\\ sin \theta &cos \theta &0\\ 0 &0 &1 \end{bmatrix}
MAR=⎣⎡cosθsinθ0−sinθcosθ0001⎦⎤
平移:
M
A
T
=
[
1
0
d
x
0
1
d
y
0
0
1
]
M_{AT} = \begin{bmatrix} 1 &0 &d_x\\ 0 &1 &d_y\\ 0 &0 &1 \end{bmatrix}
MAT=⎣⎡100010dxdy1⎦⎤
扭变:
M
A
S
=
[
1
t
a
n
θ
0
0
1
0
0
0
1
]
M_{AS} = \begin{bmatrix} 1 &tan \theta &0\\ 0 &1 &0\\ 0 &0 &1 \end{bmatrix}
MAS=⎣⎡100tanθ10001⎦⎤
镜像:
M
A
F
=
[
−
1
0
f
w
0
1
0
0
0
1
]
M_{AF} = \begin{bmatrix} -1 &0 &f_w\\ 0 &1 &0\\ 0 &0 &1 \end{bmatrix}
MAF=⎣⎡−100010fw01⎦⎤
基本例程:1.42 图像的复合变换
# 1.42 图像的复合变换
img = cv2.imread("../images/imgLena.tif") # 读取彩色图像(BGR)
height, width = img.shape[:2] # 图片的高度和宽度
# (1) 缩放
fx, fy = 0.6, 0.6
MAZ = np.float32([[fx, 0, 0], [0, fy, 0]]) # 构造缩放变换矩阵
imgT1 = cv2.warpAffine(img, MAZ, (width, height)) # 仿射变换, 黑色填充
# (2) 平移
dx, dy = 50, 200 # dx=100 向右偏移量, dy=50 向下偏移量
MAT = np.float32([[1, 0, dx], [0, 1, dy]]) # 构造平移变换矩阵
imgT2 = cv2.warpAffine(imgT1, MAT, (width, height), borderValue=(0,255,255)) # 实现仿射变换
# (3) 旋转
theta = -30 * np.pi / 180 # 逆时针旋转 30°
cosTheta = np.cos(theta)
sinTheta = np.sin(theta)
MAR = np.float32([[cosTheta, -sinTheta, 0], [sinTheta, cosTheta, 0]]) # 构造旋转变换矩阵
imgT3 = cv2.warpAffine(imgT2, MAR, (width, height), borderValue=(255,255,0)) # 实现仿射变换
# (4) 扭曲
theta = -30 * np.pi / 180 # 逆时针扭变 30°
MAS = np.float32([[1, np.tan(theta), 0], [0, 1, 0]]) # 构造扭变变换矩阵
imgT4 = cv2.warpAffine(imgT3, MAS, (width, height), borderValue=(255,0,255)) # 实现仿射变换
plt.figure(figsize=(9,6))
plt.subplot(221), plt.axis('off'), plt.title("T1:Zoom")
plt.imshow(cv2.cvtColor(imgT1, cv2.COLOR_BGR2RGB)),
plt.subplot(222), plt.axis('off'), plt.title("T2:Translation")
plt.imshow(cv2.cvtColor(imgT2, cv2.COLOR_BGR2RGB))
plt.subplot(223), plt.axis('off'), plt.title("T3:Rotation")
plt.imshow(cv2.cvtColor(imgT3, cv2.COLOR_BGR2RGB))
plt.subplot(224), plt.axis('off'), plt.title("T4:Shear")
plt.imshow(cv2.cvtColor(imgT4, cv2.COLOR_BGR2RGB))
plt.show()
(本节完)
版权声明:
youcans@xupt 原创作品,转载必须标注原文链接:(https://blog.csdn.net/youcans/article/details/125112487)
Copyright 2022 youcans, XUPT
Crated:2021-11-18
【第3章:图像的几何变换】