大三上学期,数字摄影测量(张云生教授)一课中第一个实验:高斯滤波
以下主要是本人在该实验过程中发现的问题,仅作为日后参考
问题:
- input()函数默认输入的为字符型
- 计算n的m次幂时尽量使用:n**m
- 尽量不要使用循环,会使程序变慢
- 缩进是python的灵魂
- @jit 仅仅作为尝试,并未掌握
疑问:
- python允许不声明(或使用前声明)变量而直接使用,但在矩阵时就出现了问题
#头文件
import numpy as np
import cv2 as cv
import mathimport matplotlib.pyplot as plt
import time
from numba import jit
delta=float(input('输入高斯滤波的参数delta:')) #高斯滤波参数
img = cv.imread('data1.jpg') #读入图片
img2 = img.copy()
def creat_gauss(local_delta = 1.5):
""" 生成高斯滤波器 """
g = lambda x,y: (math.e**((-x * x - y * y) / (2 * local_delta**2))) / (2 * math.pi * local_delta**2) #高斯函数
#计算参数
gauss_mat = np.mat(np.ones((3,3)))
gauss_mat[1,1] = g(0,0)
gauss_mat[0,0] = gauss_mat[0,2] = gauss_mat[2,0] = gauss_mat[2,2] = g(1,1)
gauss_mat[0,1] = gauss_mat[1,0] = gauss_mat[1,2] = gauss_mat[2,1] = g(1,0)
gauss_mat = gauss_mat * (1 / gauss_mat.sum()) #归一化
return gauss_mat
#####得到中心位置为(a,b)滤波部分的三种方法#####
#第一种方法
# for i in range(3):
# for j in range(3):
# old_mat[i,j] = img[a-1+i,b-1+j,z]
# #第二种方法(比第一种方法快上3s)
# old_mat[0,0]=img[a-1,b-1,z]
# old_mat[0,1]=img[a-1,b,z]
# old_mat[0,2]=img[a-1,b+1,z]
# old_mat[1,0]=img[a,b-1,z]
# old_mat[1,1]=img[a,b,z]
# old_mat[1,2]=img[a,b+1,z]
# old_mat[2,0]=img[a+1,b-1,z]
# old_mat[2,1]=img[a+1,b,z]
# old_mat[2,2]=img[a+1,b+1,z]
#第三种方法(比第二种方法快1s)
# old_mat=img[a-1:a+2,b-1:b+2,z] #左开右闭区间 例如:[1,3)
#矩阵定义
gauss_mat = np.mat(np.ones((3,3)))
old_mat = np.mat(np.ones((3,3)))
#预处理
gauss_mat = creat_gauss(delta)
[X,Y,Z] = img.shape
#遍历图像进行滤波(很耗时)
for z in range(Z):
for x in range(1,X-1):
for y in range(1,Y-1):
old_mat = img[x-1:x+2,y-1:y+2,z]
final_mat = np.multiply(gauss_mat,old_mat) #矩阵对应元素相乘
img2[x,y,z] = final_mat.sum()
##尝试加快程序运行速度
#@jit
# def try12():
# for z in range(Z):
# for x in range(1,X-1):
# for y in range(1,Y-1):
# old_mat=img[x-1:x+2,y-1:y+2,z]
# final_mat = np.multiply(gauss_mat,old_mat)
# a=final_mat.sum()
##计时
# t1 = time.time()
# t2 = time.time()
# print(t2-t1)
#显示图像
cv.imshow(' Original image ', img)
cv.imshow(' New image ', img2)
cv.waitKey(0)
# ##使用matplotlib显示
# img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
# img2 = cv.cvtColor(img2, cv.COLOR_BGR2RGB)
# fig = plt.figure()
# plt.subplot(1,2,1) #分割显示
# plt.imshow(img)
# plt.axis('off')
# plt.title(' Original image ')
#plt.subplot(1,2,2)
# plt.imshow(img2)
# plt.axis('off')
# plt.title(' New image ')
# plt.show() #必须加该语句
##使用numpy显示
# htitch= np.hstack((img, img2))
# cv.imshow("test1",htitch)
# cv.waitKey(0)