理论介绍
现设点
P
0
(
x
0
,
y
0
)
P_0 (x_0,y_0)
P0(x0,y0) 进行平移后,移动到
P
(
x
,
y
)
P(x,y)
P(x,y),其中
x
x
x 方向的平移量为
Δ
x
\Delta x
Δx,
y
y
y 方向的平移量为
Δ
y
\Delta y
Δy。如图所示,那么,点
P
(
x
,
y
)
P(x,y)
P(x,y) 的坐标为
{
x
=
x
0
+
Δ
x
y
=
y
0
+
Δ
y
\left\{ \begin{matrix} x = x_0 + \Delta x \\ y = y_0 + \Delta y \end{matrix} \right.
{x=x0+Δxy=y0+Δy
这个变换用矩阵可以表示成
[
x
y
]
=
[
x
0
y
0
]
+
[
Δ
x
Δ
y
]
\left[\begin{matrix} x \\ y \end{matrix}\right] =\left[\begin{matrix} x_0 \\ y_0 \end{matrix}\right] + \left[\begin{matrix} \Delta x \\ \Delta y \end{matrix}\right]
[xy]=[x0y0]+[ΔxΔy]
对上式进行简单变换可以写成
[
x
y
]
=
[
1
0
0
1
]
[
x
0
y
0
]
+
[
Δ
x
Δ
y
]
\left[\begin{matrix} x \\ y \end{matrix}\right] =\left[\begin{matrix} 1 & 0 \\ 0 & 1 \end{matrix}\right] \left[\begin{matrix} x_0 \\ y_0 \end{matrix}\right] + \left[\begin{matrix} \Delta x \\ \Delta y \end{matrix}\right]
[xy]=[1001][x0y0]+[ΔxΔy]
进一步变换可得
[
x
y
]
=
[
1
0
Δ
x
0
1
Δ
y
]
[
x
0
y
0
1
]
\left[\begin{matrix} x \\ y \end{matrix}\right] =\left[\begin{matrix} 1 & 0 & \Delta x\\ 0 & 1 & \Delta y \end{matrix}\right] \left[\begin{matrix} x_0 \\ y_0 \\ 1 \end{matrix}\right]
[xy]=[1001ΔxΔy]⎣⎡x0y01⎦⎤
为了使变换矩阵变成方阵,通过增加附加坐标,把左侧写成
[
x
,
y
,
1
]
T
[x,y,1]^T
[x,y,1]T 的形式,右侧坐标写成
[
x
0
,
y
0
,
1
]
T
[x_0, y_0, 1]^T
[x0,y0,1]T形式,最终扩展如下:
[
x
y
1
]
=
[
1
0
Δ
x
0
1
Δ
y
0
0
1
]
[
x
0
y
0
1
]
\left[\begin{matrix} x \\ y \\ 1 \end{matrix}\right] =\left[\begin{matrix} 1 & 0 & \Delta x\\ 0 & 1 & \Delta y\\ 0 & 0 & 1 \end{matrix}\right] \left[\begin{matrix} x_0 \\ y_0 \\ 1 \end{matrix}\right]
⎣⎡xy1⎦⎤=⎣⎡100010ΔxΔy1⎦⎤⎣⎡x0y01⎦⎤
对上式中各个矩阵进行定义:
T
=
[
1
0
Δ
x
0
1
Δ
y
0
0
1
]
T = \left[\begin{matrix} 1 & 0 & \Delta x\\ 0 & 1 & \Delta y\\ 0 & 0 & 1 \end{matrix}\right]
T=⎣⎡100010ΔxΔy1⎦⎤
称为变换矩阵。此处的变换矩阵对应了平移变换。
P
=
[
x
y
1
]
P = \left[\begin{matrix} x \\ y \\ 1 \end{matrix}\right]
P=⎣⎡xy1⎦⎤
为变换后坐标。
P
0
=
[
x
0
y
0
1
]
P_0 = \left[\begin{matrix} x_0 \\ y_0 \\ 1 \end{matrix}\right]
P0=⎣⎡x0y01⎦⎤
为变换前坐标。
实现
编程实现
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def show(img):
if img.ndim == 2:
plt.imshow(img, cmap='gray', vmin=0, vmax=255)
else:
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
img = cv.imread('pic/rabbit500x333.jpg')
transM = np.array([
[1, 0, 20],
[0, 1, 100]
], dtype=np.float32)
img_trans = cv.warpAffine(img, transM, dsize=(333, 500))
show(img_trans)
效果
说明:
- 未经许可,谢绝转载。
- 本教程为《数字图像处理Python OpenCV实战》的配套代码相关内容。
免费视频教程为0-6章(标题号≤6),可在此处点击观看。
所有课件及源代码可在此处下载:
链接:https://pan.baidu.com/s/198PySe_vebO3e06idHSQ6g
提取码:11o4
有问题可在QQ群(1079300899)指出,进群答案:数字图像处理。在本文评论指出可能导致回复很晚。