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

发布时间 2023-05-10 11:39:40作者: Jocelynn
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