Reputation: 6085
I was reading this page of the OpenCV docs. However, when I run the same code in a Jupyter Notebook the image output differs.
import cv2
import numpy as np
from matplotlib import pyplot as plt
# simple averaging filter without scaling parameter
mean_filter = np.ones((3,3))
# creating a guassian filter
x = cv2.getGaussianKernel(5,10)
gaussian = x*x.T
# different edge detecting filters
# scharr in x-direction
scharr = np.array([[-3, 0, 3],
[-10,0,10],
[-3, 0, 3]])
# sobel in x direction
sobel_x= np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
# sobel in y direction
sobel_y= np.array([[-1,-2,-1],
[0, 0, 0],
[1, 2, 1]])
# laplacian
laplacian=np.array([[0, 1, 0],
[1,-4, 1],
[0, 1, 0]])
filters = [mean_filter, gaussian, laplacian, sobel_x, sobel_y, scharr]
filter_name = ['mean_filter', 'gaussian','laplacian', 'sobel_x', \
'sobel_y', 'scharr_x']
fft_filters = [np.fft.fft2(x) for x in filters]
fft_shift = [np.fft.fftshift(y) for y in fft_filters]
mag_spectrum = [np.log(np.abs(z)+1) for z in fft_shift]
for i in range(6):
plt.subplot(2,3,i+1),plt.imshow(mag_spectrum[i],cmap = 'gray')
plt.title(filter_name[i]), plt.xticks([]), plt.yticks([])
plt.show()
Although the outputs are similar, but they aren't exact. Can someone expalin why is this so?
Upvotes: 1
Views: 424
Reputation: 1380
It has to do with how the images are displayed. The images are actually the same. However the images are being resized for viewing, since they are 3x3 pixels and a pixel is tiny on your monitor. The images from the docs are being displayed with bilinear interpolation, this is a way of smoothing the boundaries between pixels. The jupyter notebook is instead using nearest neighbor interpolation.
With matplotlib, you can tell it the type of interpolation you would like to use for viewing. Options are shown here.
Wikipedia has an article on the topic as well. And information about it can also be found in the OpenCV docs since it is used when resizing an image.
Personally I think the nearest neighbor interpolation is better for describing the filters, but bilinear interpolation would look nicer for looking at a photograph.
Upvotes: 1