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
这个错误通常是由于在使用循环时,循环变量使用了列表或数组而不是单个变量。可以尝试将代码中的错误修改如下:
- 将
kernal[0]
改为kernal.shape[0]
。因为kernal
是一个数组,所以需要使用shape
属性获取其第一维的长度。同理,将kernal[1]
改为kernal.shape[1]
。 - 在计算
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
- scalar TypeError converted integer pythonscalar typeerror converted integer typeerror integers indices string interpreted typeerror integer cannot converting typeerror structure circular typeerror undefined convert cannot runtimeerror expected python scalar typeerror nonetype python object converting shapefile geojson python typeerror arguments student python scalar