0
votes

I have the definition of "dual-energy gradient" (Reference) of pixel (x, y) is Δ^2(x, y) + Δy^2(x, y), where the square of the x-gradient Δx^2(x, y) = Rx(x, y)^2 + Gx(x, y)^2 + Bx(x, y)^2 and where the central differences Rx(x, y), Gx(x, y), and Bx(x, y) are the absolute value in differences of red, green, and blue components between pixel (x + 1, y) and pixel (x − 1, y) and similar for y-gradient.

How do I calculate this efficiently using numpy?

I am not sure if the numpy.gradient can help me out of box.

2
What are Rx(x,y) Gx(x,y) Bx(x,y) ? I'm guessing it has something to do with the RGB components of the image but what does the 'x' mean ? - ma3oun
@ma3oun - updated my definition. - Senthil Kumaran

2 Answers

1
votes

I don't know, if there is a built-in function for your calculation (maybe you want to explore scipy.ndimage).
If not, here is a version using only numpy functions:

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)

Sample input from 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")

Sample output:

[[20808 52020 20808]
 [20808 52225 21220]
 [20809 52024 20809]
 [20808 52225 21220]]
1
votes

Assuming I understood your formulas correctly, here's what I would suggest:

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

Compute the x-gradient:

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

Compute the sum of square of the x-gradient along the RGB components:

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

Same for y-gradient:

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

"Dual-energy gradient":

dualEnergy = squareX + squareY

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

Original image

enter image description here

Dual-energy

enter image description here