本文是 OpenCV 学习5-你知道图像旋转的原理吗? 的一个补充
图像平移就是着沿x轴和y轴将其移动指定数量的像素。假设需要移动的像素为 t x tx tx和 t y ty ty,这个线性变换可以表示为一个矩阵:
M = [ 1 0 t x 0 1 t y ] M = \begin{bmatrix} 1 & 0 & t_x \\ 0 & 1 & t_y \end{bmatrix} M=[1001txty]
📌 同时需要了解的是 t x tx tx为正值将使图像向右移动,负值将使图像向左移动; t y ty ty为正值将使图像向下移动,负值将使图像向上移动。
代码示例说明
- 读取图像
- 定义一个转换矩阵
- 使用warpAffine()函数进行图像的平移
- 显示图像
python
import cv2
import numpy as np
import os
# 1.读取图像
img_path = "img/dog.jpg"
if not os.path.exists(img_path):
raise FileNotFoundError(f"未找到图像文件{img_path}")
img = cv2.imread(img_path, cv2.IMREAD_COLOR)
height, width = img.shape[:2]
# 向右平移100像素,向上平移100像素
tx = 100
ty = -100
# 2.创建一个转换矩阵,使用tx和ty,它是一个NumPy数组
translation_matrix = np.array([
[1, 0, tx],
[0, 1, ty]
], dtype=np.float32)
# 3.使用cv2.warpAffine()函数进行图像的平移
translated_image = cv2.warpAffine(src=img, M=translation_matrix, dsize=(width, height))
# 4.显示图像
cv2.imshow('Translated image', translated_image)
cv2.imshow('Original image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()