代码如下:
# 导入cv模块
import cv2 as cv
import numpy as np
# 确保在0-255之间
def clamp(pv):
if pv > 255:
return 255
if pv < 0:
return 0
else:
return pv
def gaussian_noise(image): # 加噪声
h, w, c = image.shape
for row in range(h):
for col in range(w):
s = np.random.normal(0, 20, 3)
b = image[row, col, 0] # blue
g = image[row, col, 1] # green
r = image[row, col, 2] # red
image[row, col, 0] = clamp(b + s[0])
image[row, col, 1] = clamp(g + s[1])
image[row, col, 2] = clamp(r + s[2])
cv.imshow("noise image", image)
print("------------Hi,Python!-------------")
# 读取图像,支持 bmp、jpg、png、tiff 等常用格式
src = cv.imread("F:/Projects/images/2.jpg")
# 创建窗口并显示图像
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src) # 显示原图
t1 = cv.getCPUTickCount()
gaussian_noise(src) #加噪声
t2 = cv.getCPUTickCount()
time = (t2 - t1)/cv.getTickFrequency()
print("time consume:%s ms"%(time*1000))
dst=cv.GaussianBlur(src,(0,0),15)
cv.imshow("Gaussian Blur",src) #高斯模糊
dst1=cv.GaussianBlur(src,(5,5),0)
cv.imshow("Gaussian_Blur",dst1)
cv.waitKey(0)
# 释放窗口
cv.destroyAllWindows()
效果如下: