median_blur作业coding
import cv2
import numpy as np
# perspective transform的函数
def median_blur(img,kernel,padding_way):
# 检测传入的kernel是否是一个合法数组
m = kernel.shape[0]
if m % 2 == 0 or m is 1:
print('kernel size need 3, 5, 7, 9...')
return None
#通过kernel的大小来计算padding_size的大小
padding_size = m // 2
#获取传入图片的大小,img.shape[:2]获取图片的长度
height,width = img.shape[:2]
#创建了一个添加padding的0矩阵
mat_base = np.zeros((height + padding_size * 2, width + padding_size * 2))
#将原值写入新矩阵中
mat_base[padding_size:-padding_size,padding_size:-padding_size] = img
if padding_way == 'ZERO':
pass
elif padding_way == 'REPLICA':
for r in range(padding_size):
mat_base[r, padding_size:-padding_size] = img[0,:]
mat_base[-r, padding_size:-padding_size] = img[-1,:]
mat_base[padding_size:-padding_size,r] = img[:,0]
mat_base[padding_size:-padding_size,-r] = img[:,-1]
else:
print('padding_way is wrong')
return None
#创建用于输出的矩阵
mat_out = np.zeros((height,width),dtype = img.dtype) # dtype是什么意思
#遍历矩阵的每一个点
for x in range(height):
for y in range(width):
#flatten将矩阵降维,默认按照行方向降维,F为按列降维
line = mat_base[x : x + m, y : y + m].flatten()
line = np.sort(line)
# 取中间值
mat_out[x,y] = line[(m*m) // 2]
return mat_out
img_input = input("请输入图片地址:")
img_out_path = input("请输入图片保存路径:")
img = cv2.imread(img_input,0)
kernel_size = input("请输入kernel_size:")
padding_way = input("请输入padding_way,ZERO OR REPLICA:")
kernel = np.zeros(int(kernel_size))
img_output = median_blur(img,kernel,padding_way)
cv2.imshow("img_output",img_output)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.imwrite(img_out_path,img_output)
网友评论