使用OpenCV处理图像,出现RuntimeError: filter weights array has incorrect shape.错误


环境配置: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()

经过以上的修改,代码完美通过。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值