Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate Mutual information of 2d images in python

The images are stored in images_values

such as 276 images with columns x rows

images_values.shape = (276, 1080, 1920)

How can I correctly pass it to the following function to calculate the mutual information between two images ? i.e. images_values[0,:,:] and images_values[1,:,:] ?

from scipy import ndimage

EPS = np.finfo(float).eps

 def mutual_information_2d(x, y, sigma=1, normalized=False):
    """
    Computes (normalized) mutual information between two 1D variate from a
    joint histogram.
    Parameters
    ----------
    x : 1D array
        first variable
    y : 1D array
        second variable
    sigma: float
        sigma for Gaussian smoothing of the joint histogram
    Returns
    -------
    nmi: float
        the computed similariy measure
    """
    bins = (256, 256)



    jh = np.histogram2d(x, y, bins=bins)[0]

    # smooth the jh with a gaussian filter of given sigma
    ndimage.gaussian_filter(jh, sigma=sigma, mode='constant',
                                 output=jh)

    # compute marginal histograms
    jh = jh + EPS
    sh = np.sum(jh)
    jh = jh / sh
    s1 = np.sum(jh, axis=0).reshape((-1, jh.shape[0]))
    s2 = np.sum(jh, axis=1).reshape((jh.shape[1], -1))

    # Normalised Mutual Information of:
    # Studholme,  jhill & jhawkes (1998).
    # "A normalized entropy measure of 3-D medical image alignment".
    # in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.
    if normalized:
        mi = ((np.sum(s1 * np.log(s1)) + np.sum(s2 * np.log(s2)))
                / np.sum(jh * np.log(jh))) - 1
    else:
        mi = ( np.sum(jh * np.log(jh)) - np.sum(s1 * np.log(s1))
               - np.sum(s2 * np.log(s2)))

    return mi
like image 764
Joseph Adam Avatar asked Oct 20 '25 15:10

Joseph Adam


1 Answers

you could just pass this as

mi=mutual_information_2d(images_values[0,:,:].ravel(), images_values[1,:,:].ravel())

ravel will reshape the 2d array to 1d as expected by the mutual_information_2d function.

Have i understood your question correctly?

like image 77
sukhbinder Avatar answered Oct 23 '25 05:10

sukhbinder