1. 程式人生 > >opencv學習(十一):高斯模糊

opencv學習(十一):高斯模糊

程式碼如下:

# 匯入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()

效果如下: