Jupyter和OpenCV文档中的不同图像输出

时间:2019-07-13 12:12:41

标签: python opencv jupyter-notebook

我正在读this page of the OpenCV docs。但是,当我在Jupyter Notebook中运行相同的代码时,图像输出会有所不同。

文档中的图像

Image in the docs

图像在Jupyter中输出

Image output in Jupyter

代码

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()

尽管输出是相似的,但并不精确。有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

这与图像的显示方式有关。图像实际上是相同的。但是,图像正在调整大小以供查看,因为它们是3x3像素,并且显示器上的像素很小。来自文档的图像正在使用双线性插值显示,这是一种平滑像素之间边界的方法。 Jupyter笔记本而是使用最近邻插值。

使用matplotlib,您可以告诉它要用于查看的插值类型。选项显示here

维基百科在该主题上也有article。由于它在调整图像大小时使用,因此也可以在OpenCV docs中找到有关它的信息。

我个人认为,最近邻插值法更适合描述滤镜,但双线性插值法对于查看照片会更好。