I think you just have a problem on the definition of your kernel. With the current kernel definition you are just replacing a pixel by the average intensity value in a 3×3 window centered on the pixel. I believe this is the kernel you want:
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]]
Be aware though that this kernel will always make the subtraction of the mean above to the mean below, which could result in negative pixel intensities. So when you plot your image, setting
vmin = 0 will make the pixels with negative intensity to appear black. At this point it depends on what you want exactly, you can compare this resulting three plots to decide:
# 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)
CLICK HERE to find out more related problems solutions.