Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of Square Differences (SSD) in numpy/scipy

I'm trying to use Python and Numpy/Scipy to implement an image processing algorithm. The profiler tells me a lot of time is being spent in the following function (called often), which tells me the sum of square differences between two images

def ssd(A,B):
    s = 0
    for i in range(3):
        s += sum(pow(A[:,:,i] - B[:,:,i],2))
    return s

How can I speed this up? Thanks.

like image 938
Internet man Avatar asked Feb 17 '10 21:02

Internet man


People also ask

How do you calculate square in Numpy?

Python numpy. square() function returns a new array with the element value as the square of the source array elements. The source array remains unchanged.

How do you find the sum in Numpy?

sum() in Python. numpy. sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis.

Does Numpy Have a sum function?

The numpy. sum() function is available in the NumPy package of Python. This function is used to compute the sum of all elements, the sum of each row, and the sum of each column of a given array.

How do I get the sum of all columns in Numpy?

Method 2: Using the sum() function in NumPy, numpy. sum(arr, axis, dtype, out) function returns the sum of array elements over the specified axis. To compute the sum of all columns the axis argument should be 0 in sum() function.


2 Answers

Just

s = numpy.sum((A[:,:,0:3]-B[:,:,0:3])**2)

(which I expect is likely just sum((A-B)**2) if the shape is always (,,3))

You can also use the sum method: ((A-B)**2).sum()

Right?

like image 154
Andrew Jaffe Avatar answered Sep 17 '22 18:09

Andrew Jaffe


Just to mention that one can also use np.dot:

def ssd(A,B):
  dif = A.ravel() - B.ravel()
  return np.dot( dif, dif )

This might be a bit faster and possibly more accurate than alternatives using np.sum and **2, but doesn't work if you want to compute ssd along a specified axis. In that case, there might be a magical subscript formula using np.einsum.

like image 29
Jonathan H Avatar answered Sep 18 '22 18:09

Jonathan H