中值滤波(利用快排的方法)

import cv2
import numpy as np
import sys
#加椒盐噪声函数
def noise(img):
    h, w, _= img.shape
    for i in range(2000):
        x = np.random.randint(0,h)
        y = np.random.randint(0,w)
        img[x,y,:] = 255

    return img

def medium_filter(img, filter_size):
    """""
    img : 加噪声的图
    filter_size : 滤波器大小
    """""
    h, w = img.shape
    #im = np.zeros([h,w],np.uint8) #接受每个像素点,作为最终返回图
    pixel = [] #用于保存滤波器内像素

    length = filter_size//2

    for i in range(h):
        if i < length or i > h-2: #像素点是边缘像素的话跳过
            continue
        for j in range(w):
            if j < length or j > w -2: #边缘像素跳过
                continue
            k_index = length   #设置两个滤波器大小相关值,用于从滤波器中取出所有像素
            l_index = length

            for k in range(filter_size): #对应滤波器大小的遍历
                for l in range(filter_size):
                    pixel.append(img[i-k_index+k][j-l_index+l]) #列表存储滤波器中的像素

            pixel = quick_paixu(pixel,0,filter_size*filter_size -1) #利用快排后取出中值像素点
            mid_pixel = pixel[int((filter_size*filter_size-1)/2)]
            img[i][j] = mid_pixel
            pixel.clear()
    return img



#以下为快排代码:熟悉的可以直接跳过
"""""
采用原地修改,递归方式的快排:
1,函数quick_mid_return:实现将传进来的序列,取一个比较元素,进行排序后返回新的中间元素的指针
2,quick_paixu:实现传回来的新指针将序列分为左右,送入递归
"""""
def quick_paixu(target,start,end):
    if start < end:
        mid = quick_mid_return(target,start,end)
        quick_paixu(target,start,mid)
        quick_paixu(target,mid+1,end)
    return target

#获取每一次排序完后的指针
def quick_mid_return(target,start,end):
    left = start+1
    right = end
    cmp = target[start]
    while True:
        while left <= right and target[left] < cmp:
            left += 1
        while right >= left and target[right] >= cmp:
            right -= 1

        if left > right:
            break
        else:
            target[left],target[right] = target[right],target[left]

    target[right],target[start] = target[start],target[right]
    return right

if __name__ == '__main__':
    img = cv2.imread("./images/1.png")
    img = noise(img)
    cv2.imshow("1",img)
    b, g, r = cv2.split(img)
    b = medium_filter(b,3)
    g = medium_filter(g,3)
    r = medium_filter(r,3)
    img[:,:,0] = b
    img[:,:,1] = g
    img[:,:,2] = r
    cv2.imshow("q",img)
    cv2.waitKey(0)

你可能感兴趣的:(图像处理)