环境配置:win10+python3.5+opencv
原版代码如下(《OpenCV计算机视觉 Python语言实现》书上的示例代码):
import cv2
import numpy as np
from scipy import ndimage
kernel_3x3 = np.array([[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]])
kernel_5x5 = np.array([[-1, -1, -1, -1, -1],
[-1, 1, 2, 1, -1],
[-1, 2, 4, 2, -1],
[-1, 1, 2, 1, -1],
[-1, -1, -1, -1, -1]])
img = cv2.imread("../images/statue_small.jpg", 0)
k3 = ndimage.convolve(img, kernel_3x3)
k5 = ndimage.convolve(img, kernel_5x5)
blurred = cv2.GaussianBlur(img, (17,17), 0)
cv2.namedWindow('3x3', 0)
cv2.imshow("3x3", k3)
cv2.namedWindow('5x5', 0)
cv2.imshow("5x5", k5)
cv2.namedWindow('g_hpf', 0)
cv2.imshow("g_hpf", g_hpf)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行后有如下错误:
RuntimeError: filter weights array has incorrect shape.
这里出错的原因猜测可能是因为用scipy的’ndimage.convolve’缘故。ndimage提供的卷积,如果想让卷积工作,图像和内核必须有相同的维数。其中任何一个尺寸不正确都会导致错误。(这只是我查阅资料过程中猜测的原因之一,具体的出错原因,如果你有更详细的解释还请不吝赐教。)
修改几行代码,具体如下:
import cv2
import numpy as np
from skimage import io
from scipy import ndimage
kernel_3x3 = np.array([[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]])
kernel_5x5 = np.array([[-1, -1, -1, -1, -1],
[-1, 1, 2, 1, -1],
[-1, 2, 4, 2, -1],
[-1, 1, 2, 1, -1],
[-1, -1, -1, -1, -1]])
img = io.imread("images/statue_small2.jpg",as_grey=True)
k3 = ndimage.convolve(img, kernel_3x3)
k5 = ndimage.convolve(img, kernel_5x5)
blurred = cv2.GaussianBlur(img, (17,17), 0)
g_hpf = img - blurred
cv2.namedWindow('3x3', 0)
cv2.imshow("3x3", k3)
cv2.namedWindow('5x5', 0)
cv2.imshow("5x5", k5)
cv2.namedWindow('g_hpf', 0)
cv2.imshow("g_hpf", g_hpf)
cv2.waitKey(0)
cv2.destroyAllWindows()
经过以上的修改,代码完美通过。