跳转至

图像平移

概要

讲解了图像平移相关的公式还有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)

shift_right_10_down_30

向左平移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)

shift_right_-10_down_-30

图像平移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)