python 报错:TypeError: only integer scalar arrays can be converted to a scalar index

复制代码
def convolution(initial_img, kernal):
    img = np.zeros((initial_img.shape[0], initial_img.shape[1])).astype(np.uint8)
    for x in range(1, initial_img.shape[0] - 1):
        for y in range(1, initial_img.shape[1] - 1):
            temp = np.zeros([3, 3]).astype(np.uint8) # 用于存储将要参加卷积计算的像素块
            for i in range(kernal[0]):
                for j in range[kernal[1]]:
                    temp[i, j] = kernal[i, j] * initial_img[x - 1 + i, y - 1 + j, c];
            img[x, y, c] = np.sum(temp)  # 矩阵img[x, y, c]位置存的值为temp中所有数之和
    return img
复制代码

在这个代码中,for i in range(kernal[0]): 这一行报错:TypeError: only integer scalar arrays can be converted to a scalar index

这个错误通常是由于在使用循环时,循环变量使用了列表或数组而不是单个变量。可以尝试将代码中的错误修改如下:

  1. kernal[0] 改为 kernal.shape[0]。因为 kernal 是一个数组,所以需要使用 shape 属性获取其第一维的长度。同理,将 kernal[1] 改为 kernal.shape[1]
  2. 在计算 temp 中的元素时,需要指定通道数 c。 修改后的代码如下:
    复制代码
    def convolution(initial_img, kernal):
        img = np.zeros((initial_img.shape[0], initial_img.shape[1])).astype(np.uint8)
        for x in range(1, initial_img.shape[0] - 1):
            for y in range(1, initial_img.shape[1] - 1):
                temp = np.zeros([3, 3]).astype(np.uint8) # 用于存储将要参加卷积计算的像素块
                for i in range(kernal.shape[0]):
                    for j in range(kernal.shape[1]):
                        temp[i, j] = kernal[i, j] * initial_img[x - 1 + i, y - 1 + j];
                img[x, y] = np.sum(temp)  # 矩阵img[x, y]位置存的值为temp中所有数之和
        return img
    复制代码

     

     
posted @   Jocelynn  阅读(529)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示