我不知道,是否有内置函数供你计算(也许你想探索scipy.ndimage)。
如果没有,这里是只使用numpy 函数的版本:
import numpy as np
#convert from uint8 to int64 to prevent overflow problems
arr = np.array(loaded_pic, dtype = int)
#calculate squared difference ((x-1, y) - (x+1, y))^2 for each R, G and B pixel
deltaX2 = np.square(np.roll(arr, -1, axis = 0) - np.roll(arr, 1, axis = 0))
#same for y axis
deltaY2 = np.square(np.roll(arr, -1, axis = 1) - np.roll(arr, 1, axis = 1))
#add R, G and B values for each pixel, then add x- and y-shifted values
de_gradient = np.sum(deltaX2, axis = 2) + np.sum(deltaY2, axis = 2)
来自linked reference的示例输入
loaded_pic = np.asarray([[(255, 101, 51), (255, 101, 153), (255, 101, 255)],
[(255, 153, 51), (255, 153, 153), (255, 153, 255)],
[(255, 203, 51), (255, 204, 153), (255, 205, 255)],
[(255, 255, 51), (255, 255, 153), (255, 255, 255)]],
dtype = "uint8")
示例输出:
[[20808 52020 20808]
[20808 52225 21220]
[20809 52024 20809]
[20808 52225 21220]]