python利用opencv合成模糊图像
由于对焦,运动等造成的模糊图像。
图像模糊是图像处理中最简单和常用的操作之一,其主要目的之一是给图像预处理的时候降低图像噪声。比如,在大目标提取之前去除图像中的一些琐碎细节。图像的模糊通常依靠图像的卷积操作来实现。图像模糊又被称为平滑滤波。
常见的图像模糊方法可以总结如下:
(1) 归一化均值滤波器(API为blur())
(2) 高斯滤波器(API为GaussianBlur())
(3) 中值滤波器(API为medianBlur())
(4) 双边滤波器(API为bilateralFilter())
1) 运动模糊图像
一般来说,运动模糊的图像都是朝同一方向运动的,那么就可以利用cv2.filter2D函数。
import numpy as np
def motion_blur(image, degree=10, angle=20):
image = np.array(image)
# 这里生成任意角度的运动模糊kernel的矩阵, degree越大,模糊程度越高
M = cv2.getRotationMatrix2D((degree/2, degree/2), angle, 1)
motion_blur_kernel = np.diag(np.ones(degree))
motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (degree, degree))
motion_blur_kernel = motion_blur_kernel / degree
blurred = cv2.filter2D(image, -1, motion_blur_kernel)
# convert to uint8
cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
blurred = np.array(blurred, dtype=np.uint8)
return blurred
2) 对焦模糊
opencv提供了GaussianBlur函数(具体参见这里).
image = cv2.GaussianBlur(image, ksize=(degree, degree), sigmaX=0, sigmaY=0)
3) 噪点
其实就是在每个像素点添加随机扰动:
import random
def sp_noise(image,prob=0.5):
'''
添加椒盐噪声
prob:噪声比例
'''
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
return output
def gasuss_noise(image, mean=0, var=0.001):
'''
添加高斯噪声
mean : 均值
var : 方差
'''
image = np.array(image/255, dtype=float)
noise = np.random.normal(mean, var ** 0.5, image.shape)
out = image + noise
if out.min() < 0:
low_clip = -1.
else:
low_clip = 0.
out = np.clip(out, low_clip, 1.0)
out = np.uint8(out*255)
#cv.imshow("gasuss", out)
return out
https://www.cnblogs.com/aiguona/p/9389001.html
https://www.cnblogs.com/arkenstone/p/8480759.html