根据运动模型生成运动模糊图像:对一副灰度图像实现运动模糊,包含主程序、模糊程序。
时间: 2023-11-06 16:15:22 浏览: 36
好的,下面是一个简单的运动模糊图像生成程序:
主程序代码:
```python
import cv2
import numpy as np
# 读取原始图像
img = cv2.imread('lena.jpg', 0)
height, width = img.shape
# 生成运动模糊核
kernel_size = 15
theta = 45.0 # 运动方向(角度)
blur_kernel = np.zeros((kernel_size, kernel_size))
center = kernel_size // 2
slope_tan = np.tan(np.deg2rad(theta))
slope_cot = 1 / slope_tan
if slope_tan <= 1:
for i in range(kernel_size):
x = i - center
y = round(x * slope_tan)
y += center
if y >= kernel_size or y < 0:
continue
blur_kernel[y, i] = 1
else:
for i in range(kernel_size):
y = i - center
x = round(y * slope_cot)
x += center
if x >= kernel_size or x < 0:
continue
blur_kernel[i, x] = 1
blur_kernel /= kernel_size
# 运动模糊
blur_img = cv2.filter2D(img, -1, blur_kernel)
# 显示原始图像和运动模糊图像
cv2.imshow('Original', img)
cv2.imshow('Motion Blur', blur_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
模糊程序代码:
```python
import numpy as np
import cv2
def motion_blur(img, kernel_size, theta):
# 生成运动模糊核
blur_kernel = np.zeros((kernel_size, kernel_size))
center = kernel_size // 2
slope_tan = np.tan(np.deg2rad(theta))
slope_cot = 1 / slope_tan
if slope_tan <= 1:
for i in range(kernel_size):
x = i - center
y = round(x * slope_tan)
y += center
if y >= kernel_size or y < 0:
continue
blur_kernel[y, i] = 1
else:
for i in range(kernel_size):
y = i - center
x = round(y * slope_cot)
x += center
if x >= kernel_size or x < 0:
continue
blur_kernel[i, x] = 1
blur_kernel /= kernel_size
# 运动模糊
blur_img = cv2.filter2D(img, -1, blur_kernel)
return blur_img
```
其中,`motion_blur`函数接收三个参数:原始图像、核大小和运动方向。函数返回运动模糊图像。可以在主程序中调用该函数实现图像运动模糊。