msu_iqa_features.py 17.8 KB
Newer Older
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
'''
Created on 9 Feb 2016

@author: sbhatta
'''

#import re
#import os
import math
import numpy as np
import scipy as sp
import scipy.signal as ssg
import scipy.ndimage.filters as snf
import bob.ip.base
import bob.ip.color
16 17
import galbally_iqm_features as iqm
import tan_specular_highlights as tsh
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

########## Utility functions ###########
'''
Matlab-like RGB to gray...
    @param: rgbImage : numpy array for the form: [3,h,w] where h is the height of the image and w is the width of the image.
    Returns a y-image in floating-point format (range [(16/255) .. (235/255)])
'''
def matlab_rgb2gray(rgbImage):
    #g1 = 0.299*rgbFrame[0,:,:] + 0.587*rgbFrame[1,:,:] + 0.114*rgbFrame[2,:,:] #standard coeffs CCIR601
    
    #this is how it's done in matlab...
    rgbImage = rgbImage / 255.0
    C0 = 65.481/255.0
    C1 = 128.553/255.0
    C2 = 24.966/255.0
    scaleMin = 16.0/255.0
    #scaleMax = 235.0/255.0
    gray = scaleMin + (C0*rgbImage[0,:,:] + C1*rgbImage[1,:,:] + C2*rgbImage[2,:,:])    

    return gray

'''
'''
def matlab_rgb2hsv(rgbImage):
    # first normalize the range of values to 0-1
   
    isUint8 = True
    if isUint8: rgbImage = rgbImage.astype(np.float64)/255.0
        
    hsv = np.zeros_like(rgbImage)
    bob.ip.color.rgb_to_hsv(rgbImage, hsv)
    h = hsv[0,:,:]
    s = hsv[1,:,:]
    v = hsv[2,:,:]
#     
    return (h, s, v)


def imshow(image):
    import matplotlib
    from matplotlib import pyplot as plt
    if len(image.shape)==3:
        #imshow() expects color image in a slightly different format, so first rearrange the 3d data for imshow...
        outImg = image.tolist()
        print len(outImg)
        result = np.dstack((outImg[0], outImg[1]))
        outImg = np.dstack((result, outImg[2]))
        plt.imshow((outImg*255.0).astype(np.uint8)) #[:,:,1], cmap=mpl.cm.gray)
         
    else:
        if(len(image.shape)==2):
            #display gray image.
            plt.imshow(image.astype(np.uint8), cmap=matplotlib.cm.gray)
             
    plt.show()
    

########### End of Utilities ##############

########### Auxilliary functions  ##############

"""
"""
def sobelEdgeMap(image, orientation='both'):
    
    #bob..sobel returns filter-responses which need to be thresholded to get the edge-map
    thinning=1
    refImage=image.astype(np.float)
    
    #compute edge map for reference image
    refSobel_sep = bob.ip.base.sobel(refImage) #returns 3D image. 1st dim is the edge-direction. 1st component is vertical; 2nd component is hor. responses
    refSobelX = refSobel_sep[0,:,:]
    refSobelY = refSobel_sep[1,:,:]
    if orientation is 'horizontal':
92
        refEdge = iqm.edge_thinning(refSobelX[:,:], refSobelX[:,:], thinning)
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
93 94
    else:
        if orientation is 'vertical':
95
            refEdge = iqm.edge_thinning(refSobelY[:,:], refSobelY[:,:], thinning)
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
96
        else:
97
            refEdge = iqm.edge_thinning(refSobelX[:,:], refSobelY[:,:], thinning)
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
98 99 100 101 102 103
            

    return refEdge

########### End of Aux. functions ##############

104

Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
105
'''
106
main function to call
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
107
'''
108
def compute_msu_iqa_features(rgbImage):
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    """Computes image-quality features for the given input color (RGB) image.

    Parameters:

    rgbImage (:py:class:`numpy.ndarray`): A ``uint8`` array with 3 dimensions, representing the RGB input image of shape [3,M,N] (M rows x N cols).
    
    Returns:

    featSet (:py:class:`numpy.ndarray`): a 1D numpy array of 121 float32 scalars.
    This function returns the image-quality features (for face anti-spoofing) that have been 
    described by Wen et al. in their paper:
    "Face  spoof  detection  with  image distortion analysis", 
    IEEE Trans. on Information Forensics and Security, vol. 10(4), pp. 746-761, April 2015.
    """
                                    
124
    assert len(rgbImage.shape)==3, 'compute_msu_iqa_features():: image should be a 3D array (containing a rgb image)'
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
125 126 127 128 129
    h,s,v = matlab_rgb2hsv(rgbImage) #defined above. Calls Bob's rgb_to_hsv() after rescaling the input image.
    
    grayImage = np.zeros_like(h, dtype='uint8')
    bob.ip.color.rgb_to_gray(rgbImage, grayImage)
    
130
    # compute blur-features
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
131 132 133 134 135
    blurFeat = blurriness(grayImage)
    
    pinaBlur = marzilianoBlur(grayImage)
    pinaBlur /= 30.0
    
136
    # compute color-diversity features
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
137 138 139 140 141 142 143 144 145 146 147 148
    colorHist, totNumColors = calColorHist(rgbImage)
    totNumColors /= 2000.0 #as done in Matlab code provided by MSU.
    
    # calculate mean, deviation and skewness of each channel
    # use histogram shifting for the hue channel
    momentFeatsH = calmoment_shift(h)
        
    momentFeats = momentFeatsH.copy()
    momentFeatsS = calmoment(s)
    momentFeats = np.hstack((momentFeats, momentFeatsS))
    momentFeatsV = calmoment(v)
    momentFeats = np.hstack((momentFeats, momentFeatsV))
149

150
    # compute the image-specularity features
151
    speckleFeats = compute_iqa_specularity_features(rgbImage, startEps=0.06)
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
152
    
153 154
    #stack the various feature-values in the same order as in MSU's matlab code.
    fv = speckleFeats.copy()
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
155
    
156
    fv = np.hstack((fv, momentFeats))
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
157 158 159 160 161 162 163 164
    fv = np.hstack((fv, colorHist))
    fv = np.hstack((fv, totNumColors))
    fv = np.hstack((fv, blurFeat))
    fv = np.hstack((fv, pinaBlur))

    return fv


165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
def compute_iqa_specularity_features(rgbImage, startEps=0.05):
    """Returns three features characterizing the specularity present in input color image. 
    First the specular and diffuse components of the input image are separated using the 
    """
                       
    #separate the specular and diffuse components of input color image.
    speckleFreeImg, diffuseImg, speckleImg = tsh.remove_highlights(rgbImage, startEps, verboseFlag=False)
    #speckleImg contains the specular-component
                                       
    if len(speckleImg.shape)==3: 
        speckleImg = speckleImg[0]    
    speckleImg = speckleImg.clip(min=0)
        
    speckleMean = np.mean(speckleImg)
    lowSpeckleThresh = speckleMean*1.5      #factors 1.5 and 4.0 are proposed by Wen et al. in their paper and matlab code.
    hiSpeckleThresh = speckleMean*4.0
    specklePixels = speckleImg[np.where(np.logical_and(speckleImg >= lowSpeckleThresh, speckleImg<hiSpeckleThresh))]

    r = float(specklePixels.flatten().shape[0])/(speckleImg.shape[0]*speckleImg.shape[1]) #percentage of specular pixels in image
    m = np.mean(specklePixels)              #mean-specularity (of specular-pixels)
    s =  np.std(specklePixels)              #std. of specularity (of specular-pixels)

    return np.asarray((r,m/150.0,s/150.0), dtype=np.float32)           #scaling by factor of 150 is as done by Wen et al. in their matlab code.



def marzilianoBlur(image): 
    """Method proposed by Marziliano et al. for determining the average width of vertical edges, as a measure of blurredness in an image. 
    (Reimplemented from the Matlab code provided by MSU.)

    :param image: 2D gray-level (face) image 
    :param regionMask: (optional) 2D matrix (binary image), where 1s mark the pixels belonging to a region of interest, and 0s indicate pixels outside ROI.  
    """
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
198 199 200 201 202 203 204

    assert len(image.shape)==2, 'marzilianoBlur():: input image should be a 2D array (gray level image)'
       
    edgeMap = sobelEdgeMap(image, 'vertical')        # compute vertical edge-map of image using sobel 
    
    #There will be some difference between the result of this function and the Matlab version, because the
    #edgeMap produced by sobelEdgeMap() is not exactly the same as that produced by Matlab's edge() function.
205
    #Test edge-map generated in Matlab produces the same result as the matlab version of MarzilianoBlur().
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    
    blurImg = image
    C = blurImg.shape[1]    #number of cols in image
    (row, col) = edgeMap.nonzero()  # row, col contain the indices of the pixels that comprise edge-map.
    
    blurMetric = 0
    if len(row) > 0:

        #to make the following code work in a similar fashion to the original matlab code, sort the cols in ascending order, and sort the rows according to the cols.
    #     ind = np.lexsort((row,col))
    #     row = row[ind]
    #     col = col[ind]
        #print 'lexsort_col:', 1+col
        #print 'lexsort_row:', 1+row
        #This was only used for debugging (to compare with Matlab code). In fact it is not necessary, so it is commented out.
    
        
        edgeWidths = np.zeros_like(row, dtype=int)
        
        firstRow = row[0]
    #     print 'firstRow:',firstRow
        for i in range(len(row)):
            rEdge = row[i]
            cEdge = col[i]
    #         if rEdge == firstRow: print "edgePoints:", (i, rEdge, cEdge)
            
            cStart = 0          # instead of setting them to 'inf' as in MSU's Matlab version
            cEnd = 0       
            
            #we want to estimate the edge-width, which will be cEnd - cStart.
            
            #search for start of edge in horizontal direction
            if cEdge > 0: #i.e., edge is not on the left-border
                #2.1: search left of current pixel (backwards)
                if blurImg[rEdge, cEdge] > blurImg[rEdge, cEdge-1]: #edge corresponds to a local peak; estimate left-extent of peak
                    j=cEdge-1
                    while j>0 and blurImg[rEdge, j] >= blurImg[rEdge, j-1]: j -= 1
                    cStart = j
                else:   #edge corresponds to a local valley; determine left-extent of valley
                    j=cEdge-1
                    while j>0 and blurImg[rEdge, j] <= blurImg[rEdge, j-1]: j-= 1
                    cStart = j
            
            #search for end of edge in horizontal direction        
            cEnd = C-1 #initialize to right-border of image -- the max. possible position for cEnd
            if cEdge < C-1:
                if blurImg[rEdge, cEdge] > blurImg[rEdge, cEdge+1]: #edge corresponds to a local peak; estimate right-extent of peak
                    j=cEdge+1
                    while j< C-1 and blurImg[rEdge, j] >= blurImg[rEdge, j+1]: j += 1
                    cEnd = j
                else:   #edge corresponds to a local valley; determine right-extent of valley
                    j=cEdge+1
                    while j< C-1 and blurImg[rEdge, j] <= blurImg[rEdge, j+1]: j += 1
                    cEnd = j
            
            edgeWidths[i] = cEnd - cStart
            
            #sanity-check (edgeWidths should not have negative values)
            negSum = np.sum( edgeWidths[ np.where(edgeWidths<0) ] )
            assert negSum==0, 'marzilianoBlur():: edgeWidths[] contains negative values. YOU CANNOT BE SERIOUS!'
            
        # Final metric computation
        blurMetric = np.mean(edgeWidths)
            
    #compute histogram of edgeWidths ...(later)
                                # binnum = 100;
                                # t = ((1:binnum) - .5) .* C ./ binnum;
                                # whist = hist(width_array, t) ./ length(width_array);

    return blurMetric


def calmoment( channel, regionMask=None ):
279 280 281 282
    """ returns the first 3 statistical moments (mean, standard-dev., skewness) and 2 other first-order statistical measures of input image 
    :param channel: 2D array containing gray-image-like data 
    """

Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    assert len(channel.shape) == 2, 'calmoment():: channel should be a 2D array (a single color-channel)'    

    t = np.arange(0.05, 1.05, 0.05) + 0.025                 # t = 0.05:0.05:1;

    nPix = np.prod(channel.shape)                   # pixnum = length(channel(:));
    m = np.mean(channel)                            # m = mean(channel(:));
    d = np.std(channel)                             # d = sqrt(sum((channel(:) - m) .^ 2) / pixnum);
    s = np.sum(np.power( ((channel - m)/d), 3))/nPix  # s = sum(((channel(:) - m) ./ d) .^ 3) / pixnum;
    #print 't:', t
    myHH = np.histogram(channel, t)[0]
    #print myHH
    hh = myHH.astype(float)/nPix              # hh = hist(channel(:),t) / pixnum;
    #print 'numPix:', nPix
    #print 'histogram:',hh
    
    #H = np.array([m,d,s, np.sum(hh[0:1]), np.sum(hh[-2:-1])])  # H = [m d s sum(hh(1:2)) sum(hh(end-1:end))];
    H= np.array([m,d,s])
    s0 = np.sum(hh[0:2])
    #print s0
    H = np.hstack((H,s0))
    s1 = np.sum(hh[-2:])
    #print s1
    H = np.hstack((H, s1) )
    #print 'calmoment:',H.shape
    
    return H


'''
'''
def calmoment_shift( channel ):
    assert len(channel.shape) == 2, 'calmoment_shift():: channel should be a 2D array (a single color-channel)'
    
    channel = channel + 0.5;
                                                    # tag = find(channel>1);
    channel[np.where(channel>1.0)] -= 1.0           # channel(tag) = channel(tag) - 1;

#     t = np.arange(0.05, 1.05, 0.05)                 # t = 0.05:0.05:1;
#     nPix = np.prod(channel.shape)                   # pixnum = length(channel(:));
                                                    #     m = mean(channel(:));
                                                    #     d = sqrt(sum((channel(:) - m) .^ 2) / pixnum);
                                                    #     s = sum(((channel(:) - m) ./ d) .^ 3) / pixnum;
                                                    #     hh = hist(channel(:),t) / pixnum;
                                                    #     
                                                    #     H = [m d s sum(hh(1:2)) sum(hh(end-1:end))];
    
    H = calmoment(channel)
    
    return H



"""
function returns the top 'm' most popular colors in the input image
    :param image: RGB color-image represented in a 3D array
    :param m: integer specifying how many 'top' colors to be counted (e.g. for m=10 the function will return the pixel-counts for the top 10 most popular colors in image)
    :return cHist: counts of the top 100 most popular colors in image
    :return numClrs: total number of distinct colors in image 
"""
def calColorHist(image, m=100):
    #1. compute color histogram of image (normalized, if specified)
    numBins = 32
    maxval=255
    #print "calColorHist():: ", image.shape
    cHist = rgbhist(image, maxval, numBins, 1)

    #2. determine top 100 colors of image from histogram
    #cHist.sort() cHist = cHist[::-1]
    y = sorted(cHist, reverse=True) # [Y, I] = sort(H,'descend');
    cHist=y[0:m]                    # H = Y(1:m)';

    c = np.cumsum(y)                # C = cumsum(Y);
#     print 'cumsum shape:', c.shape
#     thresholdedC = np.where(c>0.999)
#    # print thresholdedC.shape
#     print 'thresholdedC:', thresholdedC[0][0] #:200]
    numClrs = np.where(c>0.99)[0][0]    # clrnum = find(C>.99,1,'first') - 1;
    
    cHist = np.array(cHist)
    return cHist, numClrs


'''
computes 3d color histogram of image
'''
def rgbhist(image, maxval, nBins, normType=0):
    assert len(image.shape)==3, 'image should be a 3D (rgb) array of shape (3, m,n) where m is no. of rows, and n is no. if cols in image.c$'
    assert normType >-1 and normType<2, 'rgbhist():: normType should be only 0 or 1'
    H = np.zeros((nBins, nBins, nBins), dtype=np.uint32)  # zeros([nBins nBins nBins]);

#     testImage = image[:,0:3,0:3].copy()
#     print testImage.shape
#     print image.shape
#     print testImage[0,:,:]
#     print ''
#     print testImage[1,:,:]
#     print ''
#     print testImage[2,:,:]
#     print ''
#     print testImage.reshape(3, 9, order='C').T
#     
#     assert(0>1), "Stop!"
    
    decimator = (maxval+1)/nBins
    numPix = image.shape[1]*image.shape[2]
    im = image.reshape(3, numPix).copy() # im = reshape(I,[size(I,1)*size(I,2) 3]);
    im=im.T
    
    for i in range(0, numPix):          # for i=1:size(I,1)*size(I,2)
        p = (im[i,:]).astype(float)     # p = double(im(i,:));
393
        p = (np.floor(p/decimator)).astype(np.uint32)       # p = floor(p/(maxval/nBins))+1;
Sushil BHATTACHARJEE's avatar
Sushil BHATTACHARJEE committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        H[p[0], p[1], p[2]] += 1        # H(p(1),p(2),p(3)) = H(p(1),p(2),p(3)) + 1;
                                        # end
    #totalNBins = np.prod(H.shape)
    #H = H.reshape(totalNBins, 1, order='F') same as H = reshape(H, nBins**3, 1)
    H = H.ravel()        #H = H(:);
#     print 'H type:',type(H[0])
#     print H.shape
    # Un-Normalized histogram
    
    if normType ==1: H =  H.astype(np.float32) / np.sum(H)    # l1 normalization
#     else:
#         if normType==2:
#             H = normc(H);            # l2 normalization
    
    return H


"""
function to estimate blurriness of an image, as computed by Di Wen et al. in their IEEE-TIFS-2015 paper.
    :param image: a gray-level image
"""
def blurriness(image):
    
    assert len(image.shape) == 2, 'Input to blurriness() function should be a 2D (gray) image'
    
    d=4
    fsize = 2*d + 1
    kver = np.ones((1, fsize))/fsize
    khor = kver.T
    
    Bver = ssg.convolve2d(image.astype(np.float32), kver.astype(np.float32), mode='same');
    Bhor = ssg.convolve2d(image.astype(np.float32), khor.astype(np.float32), mode='same');
    
    #DFver = np.abs(np.diff(image.astype('int32'), axis=0)) # abs(img(2:end,:) - img(1:end-1,:));
    #DFhor = np.abs(np.diff(image.astype('int32'), axis=1)) #abs(img(:,2:end) - img(:,1:end-1));
    # implementations of DFver and DFhor below don't look the same as in the Matlab code, but the following implementation produces equivalent results.
    # there might be a bug in Matlab!
    #The 2 commented statements above would correspond to the intent of the Matlab code.
    DFver = np.diff(image.astype('int16'), axis=0)
    DFver[np.where(DFver<0)]=0

    DFhor = np.diff(image.astype('int16'), axis=1)
    DFhor[np.where(DFhor<0)]=0

    DBver = np.abs(np.diff(Bver, axis=0)) # abs(Bver(2:end,:) - Bver(1:end-1,:));
    DBhor = np.abs(np.diff(Bhor, axis=1)) #abs(Bhor(:,2:end) - Bhor(:,1:end-1));

    Vver = DFver.astype(float) - DBver.astype(float)
    Vhor = DFhor.astype(float) - DBhor.astype(float)
    Vver[Vver<0]=0 #Vver(find(Vver<0)) = 0;
    Vhor[Vhor<0]=0 #Vhor(find(Vhor<0)) = 0;

    SFver = np.sum(DFver)
    SFhor = np.sum(DFhor) #sum(DFhor(:));

    SVver = np.sum(Vver) #sum(Vver(:));
    SVhor = np.sum(Vhor) #sum(Vhor(:));

    BFver = (SFver - SVver) / SFver;
    BFhor = (SFhor - SVhor) / SFhor;

    blurF = max(BFver, BFhor) #max([BFver BFhor]);
    
    return blurF