用Numpy计算双能梯度

时间:2018-02-25 13:07:22

标签: python numpy image-processing

我对像素(x, y)的“双能量梯度”(Reference)的定义是Δ^2(x, y) + Δy^2(x, y),其中x-gradient的平方Δx^2(x, y) = Rx(x, y)^2 + Gx(x, y)^2 + Bx(x, y)^2和哪里中心差Rx(x,y),Gx(x,y)和Bx(x,y)是像素(x + 1,y)和像素之间红色,绿色和蓝色分量差异的绝对值( x-1,y)和y梯度相似。

如何使用numpy有效地计算?

我不确定numpy.gradient是否可以帮助我解决问题。

2 个答案:

答案 0 :(得分:1)

假设我正确理解了你的公式,这就是我的建议:

from scipy.misc import face
import matplotlib.pyplot as plt
import numpy as np

img = face() # this is just a sample racoon RGB image for testing

#uncomment to show the racoon image
#plt.imshow(img)
#plt.show(img) # this displays the original image

计算x梯度:

gradX = np.gradient(img,axis=0)

计算沿RGB分量的x梯度的平方和:

squareX = np.sum(np.square(gradX),axis=2)

y渐变相同:

gradY = np.gradient(img,axis=1)
squareY = np.sum(np.square(gradY),axis=2)

"双能量梯度":

dualEnergy = squareX + squareY

#uncomment to display the image
#plt.imshow(dualEnergy)
#plt.show()

原始图片

enter image description here

<强>双能量

enter image description here

答案 1 :(得分:1)

我不知道,如果你的计算有内置函数(也许你想探索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]]