圖像平移¶
概要¶
講解了圖像平移相關的公式還有OpenCV的實現.
keywords 平移 translation 圖像變換
公式推導¶
平移可以說是最簡單的一種空間變換。其表達式為:
\begin{equation}
{
\left[ \begin{array}{c}
x'\\
y'\\
\end{array}
\right ]}=
{
\left[ \begin{array}{cc}
1 & 0\\
0 & 1\\
\end{array}
\right ]}\times
{
\left[\begin{array}{c}
x\\
y\\
\end{array}
\right]
}+
{
\left[\begin{array}{c}
b_0\\
b_1\\
\end{array}
\right]
}
\end{equation}
x' = x + b_0
y' = y + b_1
(b_0, b_1) 是偏移量。
例程¶
如果是向右平移10個像素, 向下平移30個像素的話, 那么變換矩陣M
M =\left[ \begin{array}{c}
1 &0 & 10\\
0& 1& 30\\
\end{array}
\right ]
演示代碼
transformation_demo_v1.py
import cv2 import numpy as np img = cv2.imread('cat.png') height,width,channel = img.shape # 聲明變換矩陣 向右平移10個像素, 向下平移30個像素 M = np.float32([[1, 0, 10], [0, 1, 30]]) # 進行2D 仿射變換 shifted = cv2.warpAffine(img, M, (width, height)) cv2.imwrite('shift_right_10_down_30.png', shifted)
向左平移10個像素, 向上平移30個像素
# 聲明變換矩陣 向左平移10個像素, 向上平移30個像素 M = np.float32([[1, 0, -10], [0, 1, -30]]) # 進行2D 仿射變換 shifted = cv2.warpAffine(img, M, (width, height)) cv2.imwrite('shift_right_-10_down_-30.png', shifted)
圖像平移v2¶
我們可以用translate
這個函數把這個操作封裝一下:
def translate(image, x, y): M = np.float32([[1, 0, x], [0, 1, y]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) return shifted
完成一些的代碼:
transformation_demo_v2.py
import cv2 import numpy as np img = cv2.imread('cat.png') def translate(image, x, y): M = np.float32([[1, 0, x], [0, 1, y]]) shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) return shifted shifted = translate(img, 10, 30) cv2.imwrite('shift_right_10_down_30.png', shifted)