数字图像处理基础与应用 第四章

3-1
(1) 感觉就是图像模糊了,并没有去噪

from cv2 import cv2
import numpy as np
import random


def spNoise(img,prob):
    # 添加椒盐噪声,prob:噪声比例 
    output = np.zeros(img.shape,np.uint8)
    thres = 1 - prob 
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = img[i][j]
    return output


def gaussNoise(img, mean=0, var=0.0001):
    # 添加,高斯噪声mean : 均值,var : 方差
    img = np.array(img/255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, img.shape)
    out = img + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out*255)
    return out


def meanFilter(img, c):
    # 均值滤波,2c+1*2c+1矩阵取平均值
    img_shape = np.shape(img)
    out = np.zeros(img_shape)
    for i in range(img_shape[0]):
        for j in range(img_shape[1]):
            if i >= c and i < img_shape[0] - c and j >= c and j < img_shape[1] - c:
                out[i][j] = min(sum(img[i - c:i + c + 1, j - c:j + c + 1].flatten()) // ((2 * c + 1) * (2 * c + 1)), img[i][j])
            else:
                out[i][j] = img[i][j]
    return out


def medianFilter(img, c):
    # 中值滤波,2c+1*2c+1矩阵再取中值
    img_shape = np.shape(img)
    out = np.zeros(img_shape)
    for i in range(img_shape[0]):
        for j in range(img_shape[1]):
            if i >= c and i < img_shape[0] - c and j >= c and j < img_shape[1] - c:
                out[i][j] = medianValueOdd(img[i - c:i + c + 1, j - c:j + c + 1].flatten())
            else:
                out[i][j] = img[i][j]
    return out


def medianValueOdd(arr):
    # 希尔排序
    length = len(arr)
    gap = length//2
    while gap > 0:
        for i in range(gap, length):
            tem = arr[i]
            j = i 
            while  j >= gap and arr[j-gap] >tem: 
                arr[i], arr[i - gap] = arr[i - gap], arr[i]
                j -= gap 
        gap = gap // 2
    return arr[length//2]

img = cv2.imread("C:\\test\\1.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

img_noise = spNoise(gray, 0.0005)
img_noise = gaussNoise(img_noise)

img_mean_filter1 = meanFilter(img_noise, 1)
img_mean_filter2 = meanFilter(img_noise, 2)
img_mean_filter3 = meanFilter(img_noise, 3)
img_median_filter1 = medianFilter(img_noise, 1)
img_median_filter2 = medianFilter(img_noise, 2)
img_median_filter3 = medianFilter(img_noise, 3)

cv2.imwrite("C:\\test\\img_mean_filter1.jpg", img_mean_filter1)
cv2.imwrite("C:\\test\\img_mean_filter2.jpg", img_mean_filter2)
cv2.imwrite("C:\\test\\img_mean_filter3.jpg", img_mean_filter3)
cv2.imwrite("C:\\test\\img_median_filter1.jpg", img_median_filter1)
cv2.imwrite("C:\\test\\img_median_filter2.jpg", img_median_filter2)
cv2.imwrite("C:\\test\\img_median_filter3.jpg", img_median_filter3)

img_mean_filter1 = cv2.imread("C:\\test\\img_mean_filter1.jpg")
img_mean_filter2 = cv2.imread("C:\\test\\img_mean_filter2.jpg")
img_mean_filter3 = cv2.imread("C:\\test\\img_mean_filter3.jpg")
img_median_filter1 = cv2.imread("C:\\test\\img_median_filter1.jpg")
img_median_filter2 = cv2.imread("C:\\test\\img_median_filter2.jpg")
img_median_filter3 = cv2.imread("C:\\test\\img_median_filter3.jpg")

cv2.imshow('gray', gray)
cv2.imshow('img_noise', img_noise)
cv2.imshow('img_mean_filter1', img_mean_filter1)
cv2.imshow('img_mean_filter2', img_mean_filter2)
cv2.imshow('img_mean_filter3', img_mean_filter3)
cv2.imshow('img_median_filter1', img_median_filter1)
cv2.imshow('img_median_filter2', img_median_filter2)
cv2.imshow('img_median_filter3', img_median_filter3)
cv2.waitKey()
cv2.destroyAllWindows

4-1
(2)使用K邻近滤波和对称邻近滤波,发现K邻近滤波时,若仅取K=3,会产生很多早点,取K=5,K=7时,能有效去噪

from cv2 import cv2
import numpy as np
import random


def spNoise(img,prob):
    # 添加椒盐噪声,prob:噪声比例 
    output = np.zeros(img.shape,np.uint8)
    thres = 1 - prob 
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = img[i][j]
    return output


def gaussNoise(img, mean=0, var=0.0001):
    # 添加,高斯噪声mean : 均值,var : 方差
    img = np.array(img/255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, img.shape)
    out = img + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out*255)
    return out


def shellSort(arr):
    # 希尔排序
    length = len(arr)
    gap = length//2
    while gap > 0:
        for i in range(gap, length):
            tem = arr[i]
            j = i 
            while  j >= gap and arr[j-gap] >tem: 
                arr[i], arr[i - gap] = arr[i - gap], arr[i]
                j -= gap 
        gap = gap // 2
    return arr


def kNeighborFilter(img, N):
    square = N * N
    K = 2 * N - 1
    q = N // 2
    img_shape = np.shape(img)
    out = np.zeros(img_shape)
    for i in range(img_shape[0]):
        for j in range(img_shape[1]):
            if i >= q and i < img_shape[0] - q and j >= q and j < img_shape[1] - q:
                img_flatten = img[i - q:i + q + 1, j - q:j + q + 1].flatten()
                arr = np.append(img_flatten[0:square // 2], (img_flatten[square // 2 + 1:]))
                arr = shellSort(arr)
                p = 0
                while p < len(arr)-1:
                    if arr[p] > img[i][j]:
                        break
                    if arr[p] <= img[i][j] and arr[p + 1] >= img[i][j]:
                        break
                    p += 1
                if p < K // 2:
                    out[i][j] = sum(arr[0:K]) // K
                elif p > square - K // 2:
                    out[i][j] = sum(arr[square - K:]) // K
                else:
                    out[i][j] = sum(arr[p - K // 2:p + K // 2 + 1]) // K
            else:
                out[i][j] = img[i][j]
    return out


def symmetricNeighborFilter(img, N):
    p = N // 2
    img_shape = np.shape(img)
    out = np.zeros(img_shape)
    for i in range(img_shape[0]):
        for j in range(img_shape[1]):
            if i >= p and i < img_shape[0] - p and j >= p and j < img_shape[1] - p:
                tem = []
                for k in range(i - p, i + p + 1):
                    for l in range(j - p, j):
                        tem.append([img[k][l], img[2 * i - k][2 * j - l]])
                for k in range(i - p, i):
                    tem.append([img[k, j], img[2 * i - k][j]])
                total = 0
                print(tem)
                for m in range(len(tem)):
                    if abs(tem[m][0] - img[i][j]) < abs(tem[m][1] - img[i][j]):
                        total += tem[m][0]
                    else:
                        total += tem[m][1]
                    print(total)
                out[i][j] = total // len(tem)
                print(out[i][j])
            else:
                out[i][j] = img[i][j]
    return out


img = cv2.imread("C:\\test\\1.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

img_noise = spNoise(gray, 0.0005)
img_noise = gaussNoise(img_noise)

k_neighbor_filter1 = kNeighborFilter(img_noise, 3)
k_neighbor_filter2 = kNeighborFilter(img_noise, 5)
k_neighbor_filter3 = kNeighborFilter(img_noise, 7)
symmetric_neighbor_filter1 = symmetricNeighborFilter(img_noise, 3)
symmetric_neighbor_filter2 = symmetricNeighborFilter(img_noise, 5)
symmetric_neighbor_filter3 = symmetricNeighborFilter(img_noise, 7)

cv2.imwrite("C:\\test\\kNeighborFilter3.jpg", k_neighbor_filter1)
cv2.imwrite("C:\\test\\kNeighborFilter5.jpg", k_neighbor_filter2)
cv2.imwrite("C:\\test\\kNeighborFilter7.jpg", k_neighbor_filter3)
cv2.imwrite("C:\\test\\symmetricNeighborFilter3.jpg", symmetric_neighbor_filter1)
cv2.imwrite("C:\\test\\symmetricNeighborFilter5.jpg", symmetric_neighbor_filter2)
cv2.imwrite("C:\\test\\symmetricNeighborFilter7.jpg", symmetric_neighbor_filter3)

k_neighbor_filter1 = cv2.imread("C:\\test\\kNeighborFilter3.jpg")
k_neighbor_filter2 = cv2.imread("C:\\test\\kNeighborFilter5.jpg")
k_neighbor_filter3 = cv2.imread("C:\\test\\kNeighborFilter7.jpg")
symmetric_neighbor_filter1 = cv2.imread("C:\\test\\symmetricNeighborFilter3.jpg")
symmetric_neighbor_filter2 = cv2.imread("C:\\test\\symmetricNeighborFilter5.jpg")
symmetric_neighbor_filter3 = cv2.imread("C:\\test\\symmetricNeighborFilter7.jpg")

cv2.imshow('gray', gray)
cv2.imshow('img_noise', img_noise)
cv2.imshow('kNeighborFilter3', k_neighbor_filter1)
cv2.imshow('kNeighborFilter5', k_neighbor_filter2)
cv2.imshow('kNeighborFilter7', k_neighbor_filter3)
cv2.imshow('kNeighborFilter3', symmetric_neighbor_filter1)
cv2.imshow('kNeighborFilter5', symmetric_neighbor_filter2)
cv2.imshow('kNeighborFilter7', symmetric_neighbor_filter3)
cv2.waitKey()
cv2.destroyAllWindows

4-1(3)看起来开运算去掉了白点,闭运算去掉了黑点

from cv2 import cv2
import numpy as np
import random


def spNoise(img,prob):
    # 添加椒盐噪声,prob:噪声比例 
    output = np.zeros(img.shape,np.uint8)
    thres = 1 - prob 
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = img[i][j]
    return output


def gaussNoise(img, mean=0, var=0.0001):
    # 添加,高斯噪声mean : 均值,var : 方差
    img = np.array(img/255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, img.shape)
    out = img + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out*255)
    return out


def grayErosion(img, N):
    arr = np.ones((N, N))
    p = N // 2
    img_shape = np.shape(img)
    out = np.zeros(img_shape)
    for i in range(img_shape[0]):
        for j in range(img_shape[1]):
            if i >= p and i < img_shape[0] - p and j >= p and j < img_shape[1] - p:
                out[i][j] = max(0, min(img[i - p:i + p + 1, j - p:j + p + 1].flatten()-arr.flatten()))
            else:
                out[i][j] = img[i][j]
    return out

def grayScale(img, N):
    arr = np.ones((N, N))
    p = N // 2
    img_shape = np.shape(img)
    out = np.zeros(img_shape)
    for i in range(img_shape[0]):
        for j in range(img_shape[1]):
            if i >= p and i < img_shape[0] - p and j >= p and j < img_shape[1] - p:
                out[i][j] = min(255, max(img[i - p:i + p + 1, j - p:j + p + 1].flatten()-arr.flatten()))
            else:
                out[i][j] = img[i][j]   
    return out


def openFilter(img, arr):
    return grayScale(grayErosion(img, arr), arr)
    

def closeFilter(img, arr):
    return grayErosion(grayScale(img, arr), arr)
    

img = cv2.imread("C:\\test\\1.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

img_noise = spNoise(gray, 0.0005)
img_noise = gaussNoise(img_noise)

image_open_filter = openFilter(img_noise, 3)
image_close_filter = closeFilter(img_noise, 3)

cv2.imwrite("C:\\test\\image_open_filter.jpg", image_open_filter)
cv2.imwrite("C:\\test\\image_close_filter.jpg", image_close_filter)

image_open_filter = cv2.imread("C:\\test\\image_open_filter.jpg")
image_close_filter = cv2.imread("C:\\test\\image_close_filter.jpg")

cv2.imshow('gray', gray)
cv2.imshow('img_noise', img_noise)
cv2.imshow('image_open_filter', image_open_filter)
cv2.imshow('image_close_filter', image_close_filter)
cv2.waitKey()
cv2.destroyAllWindows
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值