基于傅里叶变换的图像旋转实验代码
时间: 2023-06-25 07:07:35 浏览: 45
以下是一个基于傅里叶变换的图像旋转实验代码,使用Python和OpenCV库实现:
```python
import cv2
import numpy as np
import math
# 读取图片
img = cv2.imread('test.jpg', 0)
# 获取图片的高度和宽度
rows, cols = img.shape
# 设置旋转角度
theta = 45
# 将角度转换为弧度
theta_rad = theta * math.pi / 180.0
# 定义旋转矩阵
M = np.array([
[math.cos(theta_rad), -math.sin(theta_rad)],
[math.sin(theta_rad), math.cos(theta_rad)]
])
# 计算旋转后的图片大小
new_cols = int(abs(rows * math.sin(theta_rad)) + abs(cols * math.cos(theta_rad)))
new_rows = int(abs(rows * math.cos(theta_rad)) + abs(cols * math.sin(theta_rad)))
# 定义傅里叶变换的中心点
center = (cols / 2, rows / 2)
# 进行傅里叶变换
fft = np.fft.fft2(img)
fftshift = np.fft.fftshift(fft)
# 将傅里叶变换后的图像进行中心化
for i in range(rows):
for j in range(cols):
fftshift[i][j] = fftshift[i][j] * math.pow(-1, i + j)
# 将中心化后的图像进行旋转
rotated_fft = np.zeros((new_rows, new_cols), dtype=np.complex64)
for i in range(new_rows):
for j in range(new_cols):
x = j - center[0]
y = i - center[1]
new_x = int(x * math.cos(theta_rad) + y * math.sin(theta_rad) + center[0])
new_y = int(-x * math.sin(theta_rad) + y * math.cos(theta_rad) + center[1])
if new_x >= 0 and new_x < cols and new_y >= 0 and new_y < rows:
rotated_fft[i][j] = fftshift[new_y][new_x]
# 将旋转后的傅里叶变换进行逆变换
ifftshift = np.fft.ifftshift(rotated_fft)
ifft = np.fft.ifft2(ifftshift)
result = np.abs(ifft)
# 显示原始图片和旋转后的图片
cv2.imshow('Original Image', img)
cv2.imshow('Rotated Image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在代码中,首先读取测试图片,然后定义旋转角度和旋转矩阵。接下来,计算旋转后的图片大小,并定义傅里叶变换的中心点。然后,对原始图像进行傅里叶变换,并将其进行中心化。接着,对中心化后的图像进行旋转,并将旋转后的傅里叶变换进行逆变换。最后,显示原始图片和旋转后的图片。
需要注意的是,这里使用的是二维傅里叶变换,因此需要将图片转换为灰度图像。此外,代码中还进行了一些优化,例如对图像进行中心化以避免频谱的漂移问题。