Calculating the pixel variance of a mask in an image

Viewed 389

I trying to analyze statistically an eye image. I have an elipse that covers the whole eye area.

This is my original image:

enter image description here

This is the mask generated in form of ellipse:

enter image description here

I found this link that suggests the calculation of covariance but i cant really grasp how to work with ma module of numpy, and its not quite variance. https://www.nbshare.io/notebook/160784578/How-To-Handle-nan-In-Numpy/

Here's my current code from what i was trying:

img = 'path'
img = Image.fromarray(img)
img_PIL = img

    h_1 = 13
    k_1 = 23.5
    a_1 = 3
    b_1 = 5
    
   def _in_ellipse_sub_mask(x, y, h, k, a, b):
        z = ((x-h)**2)/a**2 + ((y-k)**2)/b**2
        if z < 1:
            return True
        else:
            return False
    in_ellipse_mask = np.vectorize(_in_ellipse_iris)
    img = np.asarray(img)
    
    mask_ = _in_ellipse_sub_mask(*np.indices(img.shape), h_1,k_1,a_1,b_1)
    
    plt.imshow(mask_ )
    plt.show()

mask_var = np.nanvar(np.where(sub_mask_, img, np.nan), dtype=np.float64, out=None, ddof=1)

The output:

0.04677148697358601

I was expecting a large number over 100, but i guess this isnt the right way to calculate variance for masks, given that masks works with boolean values, it will not give me a proper result

1 Answers

Your img is a matrix with values between 0 to 1 (indicating grayscale levels). You expect the values to be 0-255. This is why you expect variance to be more than 100. So multiply the img values by 255 before the nanvar() or just the result by 255^2 (scaling property). Please note that nanvar() flattens matrix to vector before performing calculations, this is how you can get a scalar out of the matrix.

As for ma submodule, masked array contains two parts: data and mask. data is the actual data array, mask is a boolean matrix of the same dimensions as data with 1 in the places you want to disregard (mask) and 0 in the places you care (the unmasked values). The ma math functions ignore masked values.

Related