如何解决Python中的线性过滤器未按预期工作
我正在尝试实现一个线性滤波器,该滤波器使当前像素上方3个像素的平均值之间存在差异。我在做什么错了?
import numpy as np
from skimage import io,color
import matplotlib.pyplot as plt
# Image loading
img = io.imread('lena_256.jpg')
img = color.rgb2gray(img)*255
plt.figure(),plt.imshow(img,cmap='gray')
img_f1 = img.copy()
size = img.shape
kernel = np.vstack((np.ones(3),np.zeros(3),-np.ones(3)))
kernel/=3
for i in range(size[0]-2):
for j in range(size[1]-2):
# define the neighborhood - the current pixel will be at line=i+1 and column=j+1
V = img[i:i+3,j:j+3]
# multiply each pixel in the neighborhood with the weight in the kernel
V = V * kernel
# make the sum of the results and put it in the current pixel
img_f1[i+1,j+1] = np.sum(V)
# Visualize the result
plt.figure(),plt.imshow(img_f1,cmap='gray',vmin = 0,vmax = 255 )
解决方法
我认为您在内核定义方面只是一个问题。使用当前的内核定义,您只是将像素替换为以像素为中心的3x3窗口中的平均强度值。我相信这是您想要的内核:
kernel = np.vstack((np.ones(3),np.zeros(3),-np.ones(3)))
kernel/=3
print(kernel)
[[ 0.33333333 0.33333333 0.33333333]
[ 0. 0. 0. ]
[-0.33333333 -0.33333333 -0.33333333]]
请注意,尽管该内核将始终使上面的平均值减去下面的平均值,这可能会导致像素强度降低。因此,在绘制图像时,设置vmin = 0
将使强度为负的像素显示为黑色。此时,它取决于您的确切需求,您可以将由此产生的三个图进行比较以确定:
# crop negative img intensities to 0
plt.imshow(img_f1,cmap='gray',vmin = 0,vmax = 255)
# absolute value of image intensities
plt.imshow(abs(img_f1),vmax = 255)
# let imshow normalize the data on its own
plt.imshow(img_f1,cmap='gray')
# set minimum and maximum intensity values to the extreme values that could be
# generated by the filtering operation
plt.imshow(img_f1,vmin = -255,vmax = 255)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。