拉普拉斯算子图像增强
拉普拉斯算子空间域增强python
原理很简单,自己搜的时候发现有些人的代码结果完全不对,就离谱。比如图像是uint8,但是计算后的结果明显不在此区域就会导致溢出。这些部分处理不当可能会产生偏差,我自己处理完后是变清晰了,但是亮度下降了。和书上不完全一样,可能有地方写错了,欢迎指正。
代码里两个函数效果一样,不同的地方是对边缘处理与否
import numpy as np
import cv2
import os
import tifffile as tif
import matplotlib.pyplot as plt
import math
def read_img(path):
if os.path.exists(path):
#获取文件夹下所有文件名
files = os.listdir(path)
#存储所有文件的绝对路径
path_detail=[]
#存储所有文件内容
data=[]
for f in files:
path_detail.append(os.path.join(path,f ))
img=cv2.imread(os.path.join(path,f))
img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
data.append(img)
return data
def laplace(img, filter):
img=img.astype(np.int16)
row, col = img.shape
img_temp = np.zeros((row + 2, col + 2))
img_temp=img_temp.astype(np.int16)
img_temp[1:row + 1, 1:col + 1] = img
img_empty = np.zeros(img.shape)
img_empty=img_empty.astype(np.int16)
for i in range(row):
for j in range(col):
img_empty[i,j] = np.sum(filter * img_temp[i:i+3,j:j+3])
for i in range(1,row-1):
for j in range(1,col-1):
img[i,j]=img[i,j]+img_empty[i, j]
if (img[i,j])<0:
img[i,j]=0
return [img,img_empty]
def Laplc(img,filter):
img=img.astype(np.int16)
row,col=img.shape
img_temp=np.zeros(img.shape)
img_temp = img_temp.astype(np.int16)
for i in range(1,row-1):
for j in range(1,col-1):
img_temp[i,j]=np.sum(filter*img[i-1:i+2,j-1:j+2])
for i in range(1,row-1):
for j in range(1,col-1):
img[i,j]=img[i,j]+img_temp[i, j]
if (img[i,j])<0:
img[i,j]=0
return [img,img_temp]
if __name__=="__main__":
#拉普拉斯算子
fil1_1 = np.asarray([[0, 1, 0], [1, -4, 1], [0, 1, 0]])
fil1_2 = -1 * fil1_1
fil2_1 = np.asarray([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
fil2_2 = -1 * fil2_1
###读取图像
img = tif.imread("C:\Users\34927\Desktop\work\digital_image_processing\img_work\2022-ImagesSet\moon.tif")
plt.imshow(img,gray)
plt.show()
# cv2.imshow("img",img)
#平滑滤波
#img = cv2.GaussianBlur (img, (3, 3), 0)
[res,lp]=Laplc(img,fil2_1)
plt.imshow(res,gray)
plt.show()
"""
显示标定的拉普拉斯图像只要保持其负数区域,不对其置0即可
一般拉普拉斯图像显示要将负数区域置0即可
原始图像加上拉普拉斯图像后,对于小于0的部分也是置0处理
"""
