深入理解缩放变换的原理、实现与应用
缩放变换是改变图像尺寸的基本几何变换,通过调整图像的宽度和高度来放大或缩小图像。
缩放变换是通过改变图像中每个像素点相对于参考点的距离来实现图像尺寸变化的操作。设原始点为(x, y),缩放因子为(sx, sy),则变换后的点为(x', y'):
| 插值方法 | 计算速度 | 图像质量 | 适用场景 |
|---|---|---|---|
| 最近邻 | ★★★ 最快 | ★☆☆ 锯齿 | 实时处理 |
| 双线性 | ★★☆ 中等 | ★★☆ 良好 | 一般应用 |
| 双三次 | ★☆☆ 最慢 | ★★★ 优秀 | 高质量输出 |
x' = x × sx
y' = y × sy
在齐次坐标系下,缩放变换可以用矩阵形式表示:
[x'] [sx 0 0] [x]
[y'] = [0 sy 0] [y]
[1 ] [0 0 1] [1]
当sx=sy时,称为均匀缩放;当sx≠sy时,称为非均匀缩放。
import cv2
import numpy as np
import matplotlib.pyplot as plt
def scaling_transform(image_path, fx, fy, interpolation=cv2.INTER_LINEAR):
"""
实现图像缩放变换
:param image_path: 输入图像路径
:param fx: 水平方向缩放因子
:param fy: 垂直方向缩放因子
:param interpolation: 插值方法
:return: 原图和缩放后的图像
"""
# 读取图像
img = cv2.imread(image_path)
# 应用缩放变换
scaled = cv2.resize(img, None, fx=fx, fy=fy, interpolation=interpolation)
return img, scaled
def manual_scaling(image_path, fx, fy):
"""
手动实现图像缩放变换
:param image_path: 输入图像路径
:param fx: 水平方向缩放因子
:param fy: 垂直方向缩放因子
:return: 缩放后的图像
"""
# 读取图像
img = cv2.imread(image_path)
height, width = img.shape[:2]
# 计算新图像尺寸
new_width = int(width * fx)
new_height = int(height * fy)
# 创建输出图像
scaled = np.zeros((new_height, new_width, img.shape[2]), dtype=img.dtype)
# 进行缩放变换
for i in range(new_height):
for j in range(new_width):
# 计算原图中的对应坐标
orig_x = int(j / fx)
orig_y = int(i / fy)
# 边界检查
if 0 <= orig_x < width and 0 <= orig_y < height:
scaled[i, j] = img[orig_y, orig_x]
return img, scaled
def scaling_with_interpolation(image_path, fx, fy, method='bilinear'):
"""
带插值的缩放变换
:param image_path: 输入图像路径
:param fx: 水平方向缩放因子
:param fy: 垂直方向缩放因子
:param method: 插值方法 ('nearest', 'bilinear', 'bicubic')
:return: 原图和缩放后的图像
"""
# 读取图像
img = cv2.imread(image_path)
# 根据插值方法选择OpenCV函数参数
if method == 'nearest':
interpolation = cv2.INTER_NEAREST
elif method == 'bilinear':
interpolation = cv2.INTER_LINEAR
elif method == 'bicubic':
interpolation = cv2.INTER_CUBIC
else:
interpolation = cv2.INTER_LINEAR
# 应用缩放变换
scaled = cv2.resize(img, None, fx=fx, fy=fy, interpolation=interpolation)
return img, scaled
def adaptive_scaling(image_path, max_width, max_height):
"""
自适应缩放,保持宽高比
:param image_path: 输入图像路径
:param max_width: 最大宽度
:param max_height: 最大高度
:return: 原图和自适应缩放后的图像
"""
# 读取图像
img = cv2.imread(image_path)
height, width = img.shape[:2]
# 计算缩放比例
scale_w = max_width / width
scale_h = max_height / height
scale = min(scale_w, scale_h) # 保持宽高比
# 应用缩放
scaled = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
return img, scaled
# 使用示例
if __name__ == "__main__":
# 注意:需要提供实际的图像路径
# img, result = scaling_transform('image.jpg', 1.5, 1.5)
# manual_img, manual_result = manual_scaling('image.jpg', 1.5, 1.5)
# interp_img, interp_result = scaling_with_interpolation('image.jpg', 1.5, 1.5, 'bicubic')
# adaptive_img, adaptive_result = adaptive_scaling('image.jpg', 800, 600)
pass
| 插值方法 | 计算速度 | 图像质量 | 适用场景 |
|---|---|---|---|
| 最近邻 | 最快 | 低(锯齿) | 实时处理 |
| 双线性 | 中等 | 中 | 一般应用 |
| 双三次 | 最慢 | 高 | 高质量输出 |