1. 程式人生 > >Python+OpenCV寫椒鹽噪聲和高斯噪聲

Python+OpenCV寫椒鹽噪聲和高斯噪聲

學習OpenCV+Python第二天,老師佈置作業讓給圖片新增噪聲,我是一臉懵,通過查資料和看書,寫下如下程式碼:

import cv2
import numpy as np
import random
import tkinter
import math

def rgb2gray(rgb):
    gray = np.zeros((rgb.shape[0],rgb.shape[1],1),np.uint8)  # 建立影象變數,防止gray的改變導致如果把原圖的改變
    for i in range(rgb.shape[0]):
        for j in range(rgb.shape[1]):
            gray[i,j] = 0.299 * rgb[i, j, 0] + 0.587 * rgb[i, j, 1] + 0.114 * rgb[i, j, 2]
    return gray

def Gauss_random(mu,sigem):  #  X是隨機變數,mu是均值,sigema是方差
    x = random.uniform(mu,sigem*sigem)
    t1 = (x-mu)*(x-mu)
    t2 = 2*sigem*sigem
    t3 = math.exp(-(t1/t2))
    t4 = sigem*math.sqrt(2*math.pi)
    f = 1/t4 * t3
    return f

def Gauss(gray,m,s,k):  #高斯噪聲就是噪聲是按照高斯分佈,分佈在影象上的,是黑色的
    gauss_p = gray*1
    for i in range(gauss_p.shape[0]):
        for j in range(gauss_p.shape[1]):
            temp = gauss_p[i,j] + Gauss_random(m,s)*k
            if temp < 0:
                temp = 0
            elif temp > 255:
                temp = 255
            gauss_p[i,j] = temp
    return gauss_p

def Salt(gray):
    salt_p = gray*1
    for i in range(6000):
        addx = random.randint(0, salt_p.shape[0] - 1)      #產生隨機整數  用於確定X和Y的位置,即畫素的位置
        addy = random.randint(0, salt_p.shape[1] - 1)
        if random.randint(0,1) == 0 :
            salt_p[addx,addy] = 0
        else:
            salt_p[addx,addy] = 255
    return salt_p

def Img(m,s,k):
    m=int(m)
    s=int(s)
    k = int(k)
    img = cv2.imread("d:/5.rgb")
    gray = rgb2gray(img)
    print(gray.shape[0],gray.shape[1])
    salt = Salt(gray)
    gauss = Gauss(gray,m,s,k)
    cv2.imshow("gray",gray)
    cv2.imshow("salt",salt)
    cv2.imshow("gauss",gauss)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def input():
    mu = enterS1.get()
    sigem = enterS2.get()
    k = enterS3.get()
    Img(mu,sigem,k)

root = tkinter.Tk()
s1 = tkinter.StringVar(value='')
s2 = tkinter.StringVar(value='')
s3 = tkinter.StringVar(value='')

labelS1 = tkinter.Label(root,text = 'μ:',justify = tkinter.RIGHT,width = 80)
labelS1.place(x = 10,y = 5,width = 80,height = 20)

enterS1 = tkinter.Entry(root,width = 80,textvariable = s1)
enterS1.place(x = 100,y = 5,width = 80,height = 20)

labelS2 = tkinter.Label(root,text = 'σ:',justify = tkinter.RIGHT,width = 80)
labelS2.place(x = 10,y = 30,width = 80,height = 20)

enterS2 = tkinter.Entry(root,width = 80,textvariable = s2)
enterS2.place(x = 100,y =30 ,width = 80,height = 20)

labelS3 = tkinter.Label(root,text = 'k :',justify = tkinter.RIGHT,width = 80)
labelS3.place(x = 10,y = 55,width = 80,height = 20)

enterS3 = tkinter.Entry(root,width = 80,textvariable = s3)
enterS3.place(x = 100,y = 55,width = 80,height = 20)

buttonOK = tkinter.Button(root,text = '確定',command = input)
buttonOK.place(x=90,y=90,width = 50,height = 30)

root.mainloop()


椒鹽噪聲比較簡單,就不多說了。 高斯噪聲是加性噪聲,所以要將噪聲和原圖片加在一起。 在這裡寫了一個小介面,方便調節引數 μ和σ,k,以便觀察圖片的變化。使用搜狗輸入法,輸入v6再往下找找就能找到這些符號。 如果有什麼問題可以發表評論詢問。