[英]Linear FIlter in Python not working as expected
我正在嘗試實現一個線性過濾器,它可以在當前像素上方的 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), cmap='gray', vmin = 0, 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, cmap='gray', vmin = -255, vmax = 255)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.