高斯模糊
高斯模糊本质上是低通滤波器,输出图像的每个像素点是原图像上对应像素点与周围像素点的加权。
高斯分布权重矩阵,就是对二维正态分布的密度函数(也就是高斯函数)采样再做归一化的产物。
使用opencv做高斯模糊,调用GaussianBlur函数,给出高斯矩阵的尺寸和标准差即可:
blur = cv2.GaussianBlur(img,(5,5),0)
其中,(5, 5)表示高斯矩阵的长与宽都是5,标准差取0时OpenCV会根据高斯矩阵的尺寸自己计算。通常,高斯矩阵的尺寸越大,标准差越大,处理过的图像模糊程度越大。
def img_blur(path):
files = os.listdir(path)
count = 0
for file in files:
count += 1
imgs = os.listdir(os.path.join(path,file))
for img in imgs:
filename = os.path.basename(os.path.join(path,file,img))
img = cv2.imread(os.path.join(path,file,img))
dst = cv2.GaussianBlur(img,(5,5),0)
cv2.imwrite(os.path.join(path,file,filename),dst)
print(count)
print('Done')
运动模糊
由于相机和物体之间的相对运动造成的模糊,又称为动态模糊。
使用opencv实现运动模糊,主要用到的函数是cv2.filter2D()。
def motion_blur(path,degree=12,angle=45):
files = os.listdir(path)
count = 0
for file in files:
count += 1
imgs = os.listdir(os.path.join(path,file))
for img in imgs:
filename = os.path.basename(os.path.join(path,file,img))
img = cv2.imread(os.path.join(path,file,img))
img = np.array(img)
#生成任意角度的运动模糊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(img,-1,motion_blur_kernel)
cv2.normalize(blurred,blurred,0,255,cv2.NORM_MINMAX)
blurred = np.array(blurred,dtype=np.uint8)
cv2.imwrite(os.path.join(path,file,filename),blurred)
print(count)
print('Done')
resize模糊
使用opencv中resize()实现图像下采样、上采样,可以使图像模糊。
def img_down_up(path):
files = os.listdir(path)
for file in files:
imgs = os.listdir(os.path.join(path,file))
for img in imgs:
filename = os.path.basename(os.path.join(path,file,img))
img = cv2.imread(os.path.join(path,file,img))
down_img = cv2.resize(img,(64,64),interpolation=cv2.INTER_CUBIC)
up_img = cv2.resize(down_img,(128,128),interpolation=cv2.INTER_CUBIC)
cv2.imwrite(os.path.join(path,file,filename),up_img)
print('Done')