深入理解平移变换的原理、实现与应用
平移变换是最基本的几何变换之一,用于将图像中的每个点按照指定的方向和距离移动。
平移变换是指将图像中的每个像素点按照指定的水平和垂直方向移动一定距离的操作。设原始点为(x, y),平移量为(tx, ty),则变换后的点为(x', y'):
| 变换类型 | 变换矩阵 | 效果 |
|---|---|---|
| 水平平移 | tx≠0, ty=0 | 左右移动 |
| 垂直平移 | tx=0, ty≠0 | 上下移动 |
| 对角平移 | tx≠0, ty≠0 | 斜向移动 |
x' = x + tx
y' = y + ty
在齐次坐标系下,平移变换可以用矩阵形式表示:
[x'] [1 0 tx] [x]
[y'] = [0 1 ty] [y]
[1 ] [0 0 1 ] [1]
import cv2
import numpy as np
import matplotlib.pyplot as plt
def translation_transform(image_path, tx, ty):
"""
实现图像平移变换
:param image_path: 输入图像路径
:param tx: 水平方向平移量(正数向右,负数向左)
:param ty: 垂直方向平移量(正数向下,负数向上)
:return: 原图和平移后的图像
"""
# 读取图像
img = cv2.imread(image_path)
# 定义平移矩阵
M = np.float32([[1, 0, tx], [0, 1, ty]])
# 应用平移变换
translated = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
return img, translated
def manual_translation(image_path, tx, ty):
"""
手动实现图像平移变换
:param image_path: 输入图像路径
:param tx: 水平方向平移量
:param ty: 垂直方向平移量
:return: 平移后的图像
"""
# 读取图像
img = cv2.imread(image_path)
rows, cols, channels = img.shape
# 创建输出图像
translated = np.zeros_like(img)
# 计算新位置
for i in range(rows):
for j in range(cols):
# 计算原始位置
orig_x = j - tx
orig_y = i - ty
# 检查是否在原图像范围内
if 0 <= orig_x < cols and 0 <= orig_y < rows:
translated[i, j] = img[int(orig_y), int(orig_x)]
# 否则保持默认值(黑色或零值)
return img, translated
def translation_with_padding(image_path, tx, ty, fill_value=(0, 0, 0)):
"""
带填充的平移变换
:param image_path: 输入图像路径
:param tx: 水平方向平移量
:param ty: 垂直方向平移量
:param fill_value: 填充颜色值(RGB)
:return: 原图和平移后的图像
"""
# 读取图像
img = cv2.imread(image_path)
rows, cols, channels = img.shape
# 定义平移矩阵
M = np.float32([[1, 0, tx], [0, 1, ty]])
# 应用平移变换,指定边界填充方式
translated = cv2.warpAffine(img, M, (cols, rows),
borderMode=cv2.BORDER_CONSTANT,
borderValue=fill_value)
return img, translated
# 使用示例
if __name__ == "__main__":
# 注意:需要提供实际的图像路径
# img, result = translation_transform('image.jpg', 100, 50)
# manual_img, manual_result = manual_translation('image.jpg', 100, 50)
# padded_img, padded_result = translation_with_padding('image.jpg', 100, 50, (255, 255, 255))
pass
| 变换类型 | 变换矩阵 | 效果 |
|---|---|---|
| 水平平移 | tx≠0, ty=0 | 左右移动 |
| 垂直平移 | tx=0, ty≠0 | 上下移动 |
| 对角平移 | tx≠0, ty≠0 | 斜向移动 |