1. 程式人生 > 其它 >中值濾波(python實現)

中值濾波(python實現)

技術標籤:opencvpython計算機視覺

版本opencv-python (4.4.0.46)

第一步:rgb影象轉為灰度影象

import cv2
import numpy as np

image = cv2.imread("E:/code/python/medfilter/1lena.png")
width = image.shape[0]
height = image.shape[1]
grayimg = np.zeros([width,height,1],np.uint8) 
for i in range(height):
    for j in range(width):
        grayimg[i,j] = 0.299 * image[i,j][0] + 0.587 * image[i,j][1] +  0.114 * image[i,j][2]
cv2.imshow('srcImage', image)           
cv2.imshow('grayImage', grayimg)
cv2.imwrite("E:/code/python/medfilter/2graylena.png", grayimg)
cv2.waitKey(0)

#gray=R*0.299+G*0.587+B*0.114  Gray = (R*306 + G*601 + B*117) >> 10

在這裡插入圖片描述 在這裡插入圖片描述

第二步:新增椒鹽噪聲

from PIL import Image
import numpy as np
 
def AddNoise(src, dst, probility = 0.05, method = "salt_pepper"):
 
	imarray = np.array(Image.open(src))
	height, width = imarray.shape
 
	for i in range(height):
		for j in range(width):
			if np.random.random(1) < probility:
				if np.random.random(1) < 0.5:
					imarray[i, j] = 0
				else:
					imarray[i, j] = 255
	new_im = Image.fromarray(imarray)
	new_im.save(dst)
 
gray_girl = "E:/code/python/medfilter/2graylena.png"
tar = "E:/code/python/medfilter/3saltlena.png"
 
AddNoise(gray_girl, tar)

在這裡插入圖片描述

第三步:中值濾波

#https://blog.csdn.net/baidu_41902768/article/details/94451787
from PIL import Image
import numpy as np
 
def MedianFilter(src, dst, k = 3, padding = None):
	#k=3表示視窗大小
 
	imarray = np.array(Image.open(src))
	height, width = imarray.shape
 
	if not padding:
		edge = int((k-1)/2)
		if height - 1 - edge <= edge or width - 1 - edge <= edge:
			print("The parameter k is to large.")
			return None
		new_arr = np.zeros((height, width), dtype = "uint8")
		for i in range(height):
			for j in range(width):
				if i <= edge - 1 or i >= height - 1 - edge or j <= edge - 1 or j >= height - edge - 1:
					new_arr[i, j] = imarray[i, j]
				else:
					new_arr[i, j] = np.median(imarray[i - edge:i + edge + 1, j - edge:j + edge + 1])
		new_im = Image.fromarray(new_arr)
		new_im.save(dst)
 

src = "E:/code/python/medfilter/3saltlena.png"
dst = "E:/code/python/medfilter/4medlena.png"

MedianFilter(src, dst)

在這裡插入圖片描述