代码如下:
import cv2
import numpy as np# 定义添加椒盐噪声的函数
def add_peppersalt_noise(image,n):result = image.copy()h,w = image.shape[:2]for i in range(n):x = np.random.randint(1,h)y = np.random.randint(1,w)if np.random.randint(0,2)==0:result[x,y]=0else:result[x,y]=255return resultVideo = cv2.VideoCapture(r'./images/test.avi')
if not Video.isOpened():print('视频无法打开!')
while True:ret,frame = Video.read()if not ret:breakframe_copy = frame.copy()# 对每一帧图像添加椒盐噪声v_noise = add_peppersalt_noise(frame_copy,10000)# 使用中值滤波对带有椒盐噪声的图像进行处理v_median = cv2.medianBlur(v_noise,3)cv2.imshow('test',frame)cv2.imshow('v_noise',v_noise)cv2.imshow('v_median',v_median)if cv2.waitKey(1) == 27:break
Video.release()
cv2.destroyAllWindows()
结果如下: