1. 程式人生 > >數字影象處理(四)

數字影象處理(四)

本文主要用python在配置了opencv的環境下執行一下程式碼,配置opencv可以參考我的這篇文章:https://blog.csdn.net/weixin_32888153/article/details/84328599。但是,這裡邊並沒有包含python下opencv的配置。在vs2017python環境中搜索並安裝opencv-python

檢查是否安裝成功:

#匯入cv模組
import cv2 as cv
#讀取影象,支援 bmp、jpg、png、tiff 等常用格式
img = cv.imread("111.jpg")
#建立視窗並顯示影象
cv.namedWindow("Image")
cv.imshow("Image",img)
cv.waitKey(0)
#釋放視窗
cv2.destroyAllWindows()

注意:圖片與檔案在同級,否則需要寫好相關的路徑。

#匯入所需要的包
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import math
import random
import cv2
import scipy.signal
import scipy.ndimage

#中值濾波
def medium_filter(im, x, y, step):
    sum_s=[]
    for k in range(-int(step/2),int(step/2)+1):
        for m in range(-int(step/2),int(step/2)+1):
            sum_s.append(im[x+k][y+m])
    sum_s.sort()
    return sum_s[(int(step*step/2)+1)]

#均值濾波
def mean_filter(im, x, y, step):
    sum_s = 0
    for k in range(-int(step/2),int(step/2)+1):
        for m in range(-int(step/2),int(step/2)+1):
            sum_s += im[x+k][y+m] / (step*step)
    return sum_s

def convert_2d(r):
    n = 3
    # 3*3 濾波器, 每個係數都是 1/9
    window = np.ones((n, n)) / n ** 2
    # 使用濾波器卷積影象
    # mode = same 表示輸出尺寸等於輸入尺寸
    # boundary 表示採用對稱邊界條件處理影象邊緣
    s = scipy.signal.convolve2d(r, window, mode='same', boundary='symm')
    return s.astype(np.uint8)

#加椒鹽噪聲
def add_salt_noise(img):
    rows, cols, dims = img.shape 
    R = np.mat(img[:, :, 0])
    G = np.mat(img[:, :, 1])
    B = np.mat(img[:, :, 2])

    Grey_sp = R * 0.299 + G * 0.587 + B * 0.114
    Grey_gs = R * 0.299 + G * 0.587 + B * 0.114

    snr = 0.9
    mu = 0
    sigma = 0.12
    
    noise_num = int((1 - snr) * rows * cols)

    for i in range(noise_num):
        rand_x = random.randint(0, rows - 1)
        rand_y = random.randint(0, cols - 1)
        if random.randint(0, 1) == 0:
            Grey_sp[rand_x, rand_y] = 0
        else:
            Grey_sp[rand_x, rand_y] = 255
    
    Grey_gs = Grey_gs + np.random.normal(0, 48, Grey_gs.shape)
    Grey_gs = Grey_gs - np.full(Grey_gs.shape, np.min(Grey_gs))
    Grey_gs = Grey_gs * 255 / np.max(Grey_gs)
    Grey_gs = Grey_gs.astype(np.uint8)

    # 中值濾波
    Grey_sp_mf = scipy.ndimage.median_filter(Grey_sp, (8, 8))
    Grey_gs_mf = scipy.ndimage.median_filter(Grey_gs, (8, 8))

    # 均值濾波
    n = 3
    window = np.ones((n, n)) / n ** 2
    Grey_sp_me = convert_2d(Grey_sp)
    Grey_gs_me = convert_2d(Grey_gs)

    plt.subplot(321)
    plt.title('Grey salt and pepper noise')
    plt.imshow(Grey_sp, cmap='gray')
    plt.subplot(322)
    plt.title('Grey gauss noise')
    plt.imshow(Grey_gs, cmap='gray')

    plt.subplot(323)
    plt.title('Grey salt and pepper noise (medium)')
    plt.imshow(Grey_sp_mf, cmap='gray')
    plt.subplot(324)
    plt.title('Grey gauss noise (medium)')
    plt.imshow(Grey_gs_mf, cmap='gray')

    plt.subplot(325)
    plt.title('Grey salt and pepper noise (mean)')
    plt.imshow(Grey_sp_me, cmap='gray')
    plt.subplot(326)
    plt.title('Grey gauss noise (mean)')
    plt.imshow(Grey_gs_me, cmap='gray')
    plt.show()

    


def main():
    img = np.array(Image.open('111.jpg'))
    add_salt_noise(img)



if __name__ == '__main__':
    main()

執行效果:

參考:https://blog.csdn.net/u012123989/article/details/78821037