python利用opencv合成模糊图像

由于对焦,运动等造成的模糊图像。

图像模糊是图像处理中最简单和常用的操作之一,其主要目的之一是给图像预处理的时候降低图像噪声。比如,在大目标提取之前去除图像中的一些琐碎细节。图像的模糊通常依靠图像的卷积操作来实现。图像模糊又被称为平滑滤波。
常见的图像模糊方法可以总结如下:
(1) 归一化均值滤波器(API为blur())
(2) 高斯滤波器(API为GaussianBlur())
(3) 中值滤波器(API为medianBlur())
(4) 双边滤波器(API为bilateralFilter())

1) 运动模糊图像

一般来说,运动模糊的图像都是朝同一方向运动的,那么就可以利用cv2.filter2D函数。

  1. import numpy as np
  2. def motion_blur(image, degree=10, angle=20):
  3. image = np.array(image)
  4. # 这里生成任意角度的运动模糊kernel的矩阵, degree越大,模糊程度越高
  5. M = cv2.getRotationMatrix2D((degree/2, degree/2), angle, 1)
  6. motion_blur_kernel = np.diag(np.ones(degree))
  7. motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (degree, degree))
  8. motion_blur_kernel = motion_blur_kernel / degree
  9. blurred = cv2.filter2D(image, -1, motion_blur_kernel)
  10. # convert to uint8
  11. cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
  12. blurred = np.array(blurred, dtype=np.uint8)
  13. return blurred

生成模糊图像 - 图1
生成模糊图像 - 图2

2) 对焦模糊

opencv提供了GaussianBlur函数(具体参见这里).
image = cv2.GaussianBlur(image, ksize=(degree, degree), sigmaX=0, sigmaY=0)
生成模糊图像 - 图3

3) 噪点

其实就是在每个像素点添加随机扰动:

生成模糊图像 - 图4

  1. import random
  2. def sp_noise(image,prob=0.5):
  3. '''
  4. 添加椒盐噪声
  5. prob:噪声比例
  6. '''
  7. output = np.zeros(image.shape,np.uint8)
  8. thres = 1 - prob
  9. for i in range(image.shape[0]):
  10. for j in range(image.shape[1]):
  11. rdn = random.random()
  12. if rdn < prob:
  13. output[i][j] = 0
  14. elif rdn > thres:
  15. output[i][j] = 255
  16. else:
  17. output[i][j] = image[i][j]
  18. return output
  19. def gasuss_noise(image, mean=0, var=0.001):
  20. '''
  21. 添加高斯噪声
  22. mean : 均值
  23. var : 方差
  24. '''
  25. image = np.array(image/255, dtype=float)
  26. noise = np.random.normal(mean, var ** 0.5, image.shape)
  27. out = image + noise
  28. if out.min() < 0:
  29. low_clip = -1.
  30. else:
  31. low_clip = 0.
  32. out = np.clip(out, low_clip, 1.0)
  33. out = np.uint8(out*255)
  34. #cv.imshow("gasuss", out)
  35. return out

https://www.cnblogs.com/aiguona/p/9389001.html
https://www.cnblogs.com/arkenstone/p/8480759.html