def get_textural_features(img):
    img = img_as_ubyte(rgb2gray(img))
    glcm = greycomatrix(img, [1], [0], 256, symmetric=True, normed=True)
    dissimilarity = greycoprops(glcm, 'dissimilarity')[0, 0]
    correlation = greycoprops(glcm, 'correlation')[0, 0]
    homogeneity = greycoprops(glcm, 'homogeneity')[0, 0]
    energy = greycoprops(glcm, 'energy')[0, 0]
    feature = np.array([dissimilarity, correlation, homogeneity, energy])
    return feature
Exemple #2
0
def compute_feats(image, distances, angles):
    """
    compute the texture feature by grey level co-occurrence matrices
    :param image: is just numpy array
    :param distances: List of pixel pair distance offsets
    :param angles: List of pixel pair angles in radians for the offsets
    :return: [[diss1, corr1], [diss2, corr2], [diss3, corr3], [diss4, corr4]... ] stand for dissimilarity and correlation attribute of co-occurrence matrix  by different input parameters combinations [[dis1, ang1], [dis1, ang2],[dis2, ang1],[dis2, ang2]]. So there are totally len(distances) * len(angles) pairs of return features, wrapped by pandas.Series
    """
    glcm = greycomatrix(image, distances, angles, 256, symmetric=True, normed=True)
    dissimilarities = greycoprops(glcm, 'dissimilarity').flat
    correlations = greycoprops(glcm, 'correlation').flat
    energy = greycoprops(glcm, 'energy').flat

    data = []
    label_l2 = []
    for idx, (d, c, e) in enumerate(zip(dissimilarities, correlations, energy)):
        data.append(d)
        label_l2.append(feature_name_dissimilarity.format(idx))

        data.append(c)
        label_l2.append(feature_name_correlation.format(idx))

        data.append(e)
        label_l2.append(feature_name_energy.format(idx))

    label_l1 = [feature_method_name] * len(data)
    index = pd.MultiIndex.from_tuples(list(zip(label_l1, label_l2)), names=['method', 'attr'])

    return pd.Series(data, index)
 def test_uniform_properties(self):
     im = np.ones((4, 4), dtype=np.uint8)
     result = greycomatrix(im, [1, 2, 8], [0, np.pi / 2], 4, normed=True,
                           symmetric=True)
     for prop in ['contrast', 'dissimilarity', 'homogeneity',
                  'energy', 'correlation', 'ASM']:
         greycoprops(result, prop)
def GLCM_features(img):
    gray = rgb2gray(img)
    gmatr = greycomatrix(gray, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4])
    contrast = greycoprops(gmatr, 'contrast')
    correlation = greycoprops(gmatr, 'correlation')
    energy = greycoprops(gmatr, 'energy')
    homogeneity = greycoprops(gmatr, 'homogeneity')
    return [contrast, correlation, energy, homogeneity]
Exemple #5
0
			def texture_prop(region,patch_size = 2):
				_mean_min = region_props[0][region]-patch_size;
				_mean_max = region_props[0][region]+patch_size;
				glcm = greycomatrix(gray_frame[_mean_min[0]:_mean_max[0],_mean_min[1]:_mean_max[1]],
							[3], [0], 256, symmetric=True, normed=True)
				_dis = greycoprops(glcm, 'dissimilarity')[0, 0];
				_cor = greycoprops(glcm, 'correlation')[0, 0];
				return (_dis,_cor);
def parallel_me(Z, dissim, correl, contrast, energy, mn):
    try:
       glcm = greycomatrix(Z, [5], [0], 256, symmetric=True, normed=True)
       if (greycoprops(glcm, 'dissimilarity')[0, 0] < dissim) and (greycoprops(glcm, 'correlation')[0, 0] < correl) and (greycoprops(glcm, 'contrast')[0, 0] < contrast) and (greycoprops(glcm, 'energy')[0, 0] > energy) and (np.mean(Z)<mn):
          return 1
       else:
          return 0
    except:
       return 0
def getSuperPixelTexture(superpixels, image):
    texture = []
    numSuperpixels = np.max(superpixels) + 1
    greyImage = np.around(color.rgb2gray(image) * 255, 0)
    for i in xrange(0,numSuperpixels):
    	indices = np.where(superpixels == i)
        glcm = greycomatrix([greyImage[indices]], [5], [0], 256, symmetric=True, normed=True)
        dissimilarity = greycoprops(glcm, 'dissimilarity')[0, 0]
        correlation = greycoprops(glcm, 'correlation')[0, 0]
        texture.append([dissimilarity, correlation])
    return np.array(texture)
Exemple #8
0
def glcm_fe(f):
    # 1 pixel, 6 pixesls, 20 pixels
    grey = np.array(Image.open(f), 'uint8')
    glcm = feature.greycomatrix(grey,[1,6,20],[np.pi])
    cont = feature.greycoprops(glcm, 'contrast')
    enrg = feature.greycoprops(glcm, 'energy')
    hmgn = feature.greycoprops(glcm, 'homogeneity')
    corr = feature.greycoprops(glcm, 'correlation')
    for i in cont[:,0]: print i,
    for i in enrg[:,0]: print "%.3f" % i,
    for i in hmgn[:,0]: print "%.3f" % i,
    for i in corr[:,0]:
        if np.isnan(i): i = 1
        print "%.6f" % i,
 def calc_texture(inputs):
     inputs = np.reshape(a=inputs, newshape=[ksize, ksize])
     inputs = inputs.astype(np.uint8)
     # Greycomatrix takes image, distance offset, angles (in radians), symmetric, and normed
     # http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.greycomatrix
     glcm = greycomatrix(inputs, [offset], [0], 256, symmetric=True, normed=True)
     diss = greycoprops(glcm, texture_method)[0, 0]
     return diss
Exemple #10
0
def plot_residuals():
    numberOfImages = 12
    residuals = []
    featureList = np.zeros((numberOfImages, FEATURE_SIZE))
    model = train()

    # Get feautures
    for i in range(1, numberOfImages):
        # Load image
        filename = "../Wheat_Images/{:03d}.jpg".format(i);
        img = misc.imread(filename);
        img_gray = img_as_ubyte(rgb2gray(img));
        glcm = greycomatrix(img_gray, [5], [0], 256, symmetric=True, normed=True)
        dissimilarity = greycoprops(glcm, 'dissimilarity')[0, 0]
        correlation = greycoprops(glcm, 'correlation')[0, 0]
        homogeneity = greycoprops(glcm, 'homogeneity')[0, 0]
        energy = greycoprops(glcm, 'energy')[0, 0]
        feature = np.array([dissimilarity, correlation, homogeneity, energy])
        featureList[i-1] = feature

    # Apply model to data
    predictions = model.predict(featureList)

    # Compute residuals
    for i in range(len(predictions)):
        e = predictions[i] - COUNTS[i]
        residuals.append(e)

    # Plot residual graph
    plt.figure(1)
    plt.scatter(predictions, residuals,  color='blue')
    plt.axhline(0, color='black')
    plt.xlabel('Predictions')
    plt.ylabel('Residuals')

    # Plot accuracy graph (ie predicted vs actual)
    plt.figure(2)
    plt.scatter(predictions, COUNTS,  color='blue')
    plt.plot(range(-500, 2500, 250), range(-500, 2500, 250), color='black', linestyle='dotted')
    plt.xlim(xmin=0)
    plt.ylim(ymin=0)
    plt.xlabel('Predicted')
    plt.ylabel('Actual')

    plt.show()
Exemple #11
0
def glcm(imagem,mask,grayLevels,d):
    imagem = cv2.equalizeHist(imagem)
    imagem = categorizar(imagem,8)
    imagem = cv2.bitwise_and(imagem,mask)
    matrix0 = greycomatrix(imagem, [d], [0], levels=grayLevels)
    matrix1 = greycomatrix(imagem, [d], [np.pi/4], levels=grayLevels)
    matrix2 = greycomatrix(imagem, [d], [np.pi/2], levels=grayLevels)
    matrix3 = greycomatrix(imagem, [d], [3*np.pi/4], levels=grayLevels)
    matrix = (matrix0+matrix1+matrix2+matrix3)/4 #isotropic glcm
    if mask != []:
        matrix[0,0,0,0] = 0 #remove 0->0 (mask)
    props = np.zeros((5))
    props[0] = greycoprops(matrix,'contrast')
    props[1] = greycoprops(matrix,'dissimilarity')
    props[2] = greycoprops(matrix,'homogeneity')
    props[3] = greycoprops(matrix,'energy')
    props[4] = greycoprops(matrix,'ASM')
    return props
Exemple #12
0
def texture_moving_window(input_band_list,window_dimension,index,quantization_factor):
    
    '''Compute the desired spectral feature from each window
    
    :param input_band_list: list of 2darrays (list of numpy arrays)
    :param window_dimension: dimension of the processing window (integer)
    :param index: string with index to compute (contrast, energy, homogeneity, correlation, dissimilarity, ASM) (string)
    :param quantization_factor: number of levels to consider (suggested 64) (integer)
    :returns:  list of 2darrays corresponding to computed index per-band (list of numpy arrays)
    :raises: AttributeError, KeyError
    
    Author: Daniele De Vecchi - Mostapha Harb
    Last modified: 19/03/2014
    '''
    
    #TODO: Please explain better what this function does. I assume it calculates GLCM derived features from a moving window.
    #TODO: Always provide full list of options in function description (e.g. which features are supported here?)
    #TODO: Output should be array. Only dissimilarity and only 3 bands? 
    
    band_list_q = linear_quantization(input_band_list,quantization_factor)
    output_list = []
    
               
    feat1 = 0.0
    
    rows,cols=input_band_list[0].shape
    output_ft_1 = np.zeros((len(input_band_list),rows,cols)).astype(np.float32)
    
    print input_band_list[0].shape
    if (rows%window_dimension)!=0:
        rows_w = rows-1
    else:
        rows_w = rows
    if (cols%window_dimension)!=0:
        cols_w = cols-1
    else:
        cols_w = cols
    print rows,cols
#
#    rows_w = 10
    for i in range(0,rows_w):
        print str(i+1)+' of '+str(rows_w)
        for j in range(0,cols_w):
            for b in range(0,len(input_band_list)):
                data_glcm_1 = band_list_q[0][i:i+window_dimension,j:j+window_dimension] #extract the data for the glcm
            
                if (i+window_dimension<rows_w) and (j+window_dimension<cols_w):
                    glcm1 = greycomatrix(data_glcm_1, [1], [0, np.pi/4, np.pi/2, np.pi*(3/4)], levels=quantization_factor, symmetric=False, normed=True)
                    feat1 = greycoprops(glcm1, index)[0][0]
                    index_row = i+1 #window moving step
                    index_col = j+1 #window moving step
                    
                    output_ft_1[b][index_row][index_col]=float(feat1) #stack to store the results for different bands
    for b in range(0,len(input_band_list)):
        output_list.append(output_ft_1[b][:][:])
    
    return output_list
def get_features(img):
    grey_m = greycomatrix(img, [5], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=256)
    # grey_props = ['contrast', 'dissimilarity', 'homogeneity', 'ASM', 'energy', 'correlation']
    grey_props = ['contrast', 'dissimilarity', 'homogeneity', 'ASM', 'energy']
    grey_feas = []
    for prop in grey_props:
        grey_fea = greycoprops(grey_m, prop)
        grey_feas.extend(list(grey_fea))
    return grey_props, grey_feas
Exemple #14
0
def train():
    '''
    Builds linear regression from wheat images using GLCM properties.

    Returns:
        linear regression model
    '''
    if(Helper.unserialize(LIN_REGRESSION_MODEL_NAME) == None):
        numberOfImages = 12;

    # TODO: AUTOMATICALLY GET NUMBER OF IMAGES
    # Get number of images. Remeber to divide by 2 as for every relevant image,
    # theres also the comparison image.
    # if ".DS_Store" in os.listdir("Wheat_ROIs"):
    #     numberOfImages = (len(os.listdir("Wheat_ROIs")) - 1)/2;
    # else:
    #     numberOfImages = len(os.listdir("Wheat_ROIs"))/2;

    featureList = np.zeros((numberOfImages, FEATURE_SIZE))

    # For each ROI image in folder
    for i in range(1, numberOfImages+1):
        # Load image
        filename = "../Wheat_Images/{:03d}.jpg".format(i);
        img = misc.imread(filename);
        img_gray = img_as_ubyte(rgb2gray(img));

        glcm = greycomatrix(img_gray, [5], [0], 256, symmetric=True, normed=True)
        dissimilarity = greycoprops(glcm, 'dissimilarity')[0, 0]
        correlation = greycoprops(glcm, 'correlation')[0, 0]
        homogeneity = greycoprops(glcm, 'homogeneity')[0, 0]
        energy = greycoprops(glcm, 'energy')[0, 0]
        feature = np.array([dissimilarity, correlation, homogeneity, energy])
        featureList[i-1] = feature
        #print("{} = {}A + {}B + {}C + {}D".format(filename, dissimilarity, correlation, homogeneity, energy))
        #print(feature)

    # Build regression model
    regression_model = linear_model.LinearRegression()
    regression_model.fit(featureList, COUNTS[:numberOfImages])
    Helper.serialize(LIN_REGRESSION_MODEL_NAME, regression_model)
    print("COEFF: {}\nINTERCEPT: {}".format(regression_model.coef_, regression_model.intercept_))
    print("SCORE: {}".format(regression_model.score(featureList, COUNTS[:numberOfImages])))
    return regression_model
Exemple #15
0
 def __call__(self):
     global res
     check = 1
     print str(self.i+1)+' of '+str(self.rows_w)
     for j in range(0,self.cols_w):
         data_glcm_1 = self.band_list_q[0][self.i:self.i+self.window_dimension,j:j+self.window_dimension] #extract the data for the glcm
         data_glcm_2 = self.band_list_q[1][self.i:self.i+self.window_dimension,j:j+self.window_dimension] #extract the data for the glcm
         data_glcm_3 = self.band_list_q[2][self.i:self.i+self.window_dimension,j:j+self.window_dimension] #extract the data for the glcm
         if (self.i+self.window_dimension<self.rows_w) and (j+self.window_dimension<self.cols_w):
             glcm1 = greycomatrix(data_glcm_1, [1], [0, np.pi/4, np.pi/2, np.pi*(3/4)], levels=self.quantization_factor, symmetric=False, normed=True)
             feat1 = greycoprops(glcm1, self.index)[0][0]
             glcm2 = greycomatrix(data_glcm_2, [1], [0, np.pi/4, np.pi/2, np.pi*(3/4)], levels=self.quantization_factor, symmetric=False, normed=True)
             feat2 = greycoprops(glcm2, self.index)[0][0]
             glcm3 = greycomatrix(data_glcm_3, [1], [0, np.pi/4, np.pi/2, np.pi*(3/4)], levels=self.quantization_factor, symmetric=False, normed=True)
             feat3 = greycoprops(glcm3, self.index)[0][0]
             index_row = self.i+1
             index_col = j+1
             if (check):
                 res = []
                 check = 0
             tmp1 = np.array([0,index_row,index_col,feat1])
             tmp2 = np.array([1,index_row,index_col,feat2])
             tmp3 = np.array([2,index_row,index_col,feat3])
             res = np.append(res,tmp1)
             res = np.append(res,tmp2)
             res = np.append(res,tmp3)
         '''
         for b in range(0,len(self.input_band_list)):
             data_glcm_1 = self.band_list_q[b][self.i:self.i+self.window_dimension,j:j+self.window_dimension] #extract the data for the glcm
             if (self.i+self.window_dimension<self.rows_w) and (j+self.window_dimension<self.cols_w):
                 glcm1 = greycomatrix(data_glcm_1, [1], [0, np.pi/4, np.pi/2, np.pi*(3/4)], levels=self.quantization_factor, symmetric=False, normed=True)
                 feat1 = greycoprops(glcm1, self.index)[0][0]
                 index_row = self.i+1 #window moving step
                 index_col = j+1 #window moving step
                 #FIX IT NOOB
                 if (check):
                     res = []
                     check = 0
                 tmp = np.array([b,index_row,index_col,feat1])
                 res = np.append(res,tmp)
         '''
     if (check):
         res = np.zeros(1)
     return res
 def homogeneity_fun(outRaster):
     """
     create Homogeneity using the GLCM function 
     of Skimage
     """
     if len(outRaster.shape) == 1:
         outRaster = np.reshape(outRaster, (-1, sizeWindow))
         
     glcm = greycomatrix(outRaster, [1], [0], symmetric = True, normed = True)
     return greycoprops(glcm, 'homogeneity')[0,0]
def  dissimilarity_fun(outRaster):
    """
    create dissimilarity_fun using the GLCM function 
    of Skimage
    """
    if len(outRaster.shape) == 1:
        outRaster = np.reshape(outRaster, (-1, sizeWindow))
        
    glcm = greycomatrix(outRaster, [1], [0],  symmetric = True, normed = True)
    return greycoprops(glcm, 'dissimilarity').sum()
def load_xy(dataset, nb_crops_max, nb_augmentations):
    X = []
    y = []

    examples = get_crops_with_labels(dataset, nb_crops_max, nb_augmentations,
                                     nb_crops_per_image=NB_CROPS_PER_IMAGE,
                                     model_image_height=MODEL_IMAGE_HEIGHT,
                                     model_image_width=MODEL_IMAGE_WIDTH,
                                     crop_height=CROP_HEIGHT, crop_width=CROP_WIDTH)

    for i, (crop, face_factor) in enumerate(examples):
        if i % 100 == 0:
            print("Crop %d of %d" % (i+1, nb_crops_max))

        distances = [1, 2, 3, 4, 5, 7, 11]
        angles = [0*np.pi, 0.25*np.pi, 0.5*np.pi, 0.75*np.pi, 1.0*np.pi, 1.25*np.pi, 1.5*np.pi, 1.75*np.pi]
        glcm = greycomatrix(crop, distances, angles, 256, symmetric=True, normed=True)
        dissimilarities = greycoprops(glcm, 'dissimilarity')
        energies = greycoprops(glcm, 'energy')
        correlations = greycoprops(glcm, 'correlation')

        nb_matrices = len(distances) * len(angles)
        all_values = np.zeros((3*nb_matrices))
        all_values[0:nb_matrices] = dissimilarities.flatten()
        all_values[nb_matrices:nb_matrices*2] = energies.flatten()
        all_values[nb_matrices*2:nb_matrices*3] = correlations.flatten()

        is_cat = True if face_factor >= CAT_FRACTION_THRESHOLD else False
        #if is_cat or random.random() < 0.25:
        X.append(all_values)
        y.append(1 if is_cat else 0)

    # all entries in X/Y same length
    assert len(set([len(row) for row in X])) == 1
    #assert len(set([len(row) for row in y])) == 1

    X = np.array(X, dtype=np.float32)
    y = np.array(y, dtype=np.float32)

    X = scale_linear_bycolumn(X)

    return X, y
 def haralick(self, img, ndistances, min_distance, dist_diff, nangles,
              levels, symmetric, normed, features):
     img -= np.min(img)
     img /= np.max(img)
     img_ = np.round(img*(levels-1)).astype(int)
     distances = np.arange(ndistances)*dist_diff + min_distance
     angles = np.linspace(0, np.pi, num=nangles, endpoint=False)
     M = greycomatrix(img_, distances=distances, angles=angles,
                      levels=levels, symmetric=symmetric, normed=normed)
     f = [greycoprops(M, prop=prop) for prop in features]
     return np.ravel(f)
def GLCM(im):
    """Calculate the grey level co-occurrence matrices and output values for 
    contrast, dissimilarity, homogeneity, energy, correlation, and ASM in a list"""
    
    newIm = im.convert('L') #Conver to a grey scale image
    glcm = greycomatrix(newIm, [5], [0]) #calcualte the glcm  
    
    #Compute all of the grey co occurrence features. 
    contrast = greycoprops(glcm, 'contrast')[0][0]
    if numpy.isnan(contrast): #Make sure that no value is recorded as NAN. 
        contrast = 0 #if it is replace with 0. 
    dissim = greycoprops(glcm, 'dissimilarity')[0][0]
    if numpy.isnan(dissim): 
        dissim = 0
    homog = greycoprops(glcm, 'homogeneity')[0][0]
    if numpy.isnan(homog): 
        homog = 0
    energy = greycoprops(glcm, 'energy')[0][0]
    if numpy.isnan(energy): 
        energy = 0
    corr = greycoprops(glcm, 'correlation')[0][0]
    if numpy.isnan(corr): 
        corr = 0
    ASM = greycoprops(glcm, 'ASM')[0][0]
    if numpy.isnan(ASM): 
        ASM = 0
    return numpy.concatenate(([contrast], [dissim], [homog], [energy], [corr], [ASM]), 0) #concatenate into one list along axis 0 and return 
    def matriz_coocorrencia(self):
        """

        Extraí atributos de textura baseados em matrizes de coocorrência (GLCM). São utilizadas matrizes 4x4
        nas distäncias 1 e 2 e com ângulos 0, 45 e 90.

        """

        g = feature.greycomatrix(self.imagemTonsDeCinza, [1, 2], [0, np.pi / 4, np.pi / 2], glcmNiveis,normed=True, symmetric=True)

        contrastes = feature.greycoprops(g, 'contrast').tolist()
        dissimilaridades = feature.greycoprops(g, 'dissimilarity').tolist()
        homogeneidades = feature.greycoprops(g, 'homogeneity').tolist()
        asm = feature.greycoprops(g, 'ASM').tolist()
        energias = feature.greycoprops(g, 'energy').tolist()
        correlacoes = feature.greycoprops(g, 'correlation').tolist()

        nomes = [
            'glcm_cont_1_0', 'glcm_cont_1_45', 'glcm_cont_1_90', 'glcm_cont_2_0', 'glcm_cont_2_45', 'glcm_cont_2_90',
            'glcm_diss_1_0', 'glcm_diss_1_45', 'glcm_diss_1_90', 'glcm_diss_2_0', 'glcm_diss_2_45', 'glcm_diss_2_90',
            'glcm_homo_1_0', 'glcm_homo_1_45', 'glcm_homo_1_90', 'glcm_homo_2_0', 'glcm_homo_2_45', 'glcm_homo_2_90',
            'glcm_asm_1_0', 'glcm_asm_1_45', 'glcm_asm_1_90', 'glcm_asm_2_0', 'glcm_asm_2_45', 'glcm_asm_2_90',
            'glcm_ener_1_0', 'glcm_ener_1_45', 'glcm_ener_1_90', 'glcm_ener_2_0', 'glcm_ener_2_45', 'glcm_ener_2_90',
            'glcm_corr_1_0', 'glcm_corr_1_45', 'glcm_corr_1_90', 'glcm_corr_2_0', 'glcm_corr_2_45', 'glcm_corr_2_90',

        ]
        tipos = [numerico] * len(nomes)

        valores = contrastes[0] + contrastes[1] + dissimilaridades[0] + dissimilaridades[1] + homogeneidades[0] + \
                  homogeneidades[1] + asm[0] + asm[1] + energias[0] + energias[1] + correlacoes[0] + correlacoes[1]

        return nomes, tipos, valores
Exemple #22
0
def generate(path):

    # ####### LBP ######## #
    img = data.load(abspath(path))
    img_gray = rgb2gray(img)
    img_gray *= 255

    img_lbp = local_binary_pattern(
                    img_gray, 8, 1, method='nri_uniform'
                    )

    histogram = np.hstack((img_lbp.flatten(), list(range(59))))
    histogram = scipy.stats.itemfreq(histogram)
    # print histogram.shape

    try:
        a, b, c = img.shape
    except:
        a, b = img.shape

    # We know they are equal:
    # print a*b
    # print sum(a[1] for a in histogram)

    # lbp histogram values Normalization
    lbp_features = [(element[1]/float(a*b)) for element in histogram]
    # print len(lbp_features)

    # ####### GLCM ######## #

    distances = [2, 3, 4, 5]
    theta = [0,  np.pi/4,  np.pi/2,  3*np.pi/2,  np.pi]

    glcm = greycomatrix(img_gray, distances, theta, normed=True)
    props = {}
    for prop in [
            'contrast', 'dissimilarity', 'homogeneity', 'energy',
            'correlation', 'ASM'
            ]:
        props[prop] = greycoprops(glcm, prop)
    props['contrast'] /= props['contrast'].max()
    props['dissimilarity'] /= props['dissimilarity'].max()

    glcm_feature = []
    for i in props.keys():
        for d in range(len(distances)):
            for t in range(len(theta)):
                glcm_feature.append(props[i][d][t])

    # print len(glcm_feature)

    return np.hstack([lbp_features, glcm_feature])
Exemple #23
0
def count(filename, model):
    '''
    Returns an estimate of the number of grains in a given wheat image.

    Args:
        filename: Name of image file containing grains to be counted.

        model: regression model for estimating count
    Returns:
        estimation of the number of grains in image.
    '''
    img = misc.imread(filename);
    img_gray = img_as_ubyte(rgb2gray(img));

    glcm = greycomatrix(img_gray, [5], [0], 256, symmetric=True, normed=True)
    dissimilarity = greycoprops(glcm, 'dissimilarity')[0, 0]
    correlation = greycoprops(glcm, 'correlation')[0, 0]
    homogeneity = greycoprops(glcm, 'homogeneity')[0, 0]
    energy = greycoprops(glcm, 'energy')[0, 0]
    feature = np.array([dissimilarity, correlation, homogeneity, energy])

    count = model.predict(feature)
    return count
    def compute_texture(self):

        offset = int(self.param_glcm.distance)
        sct.printv('\nCompute texture metrics...', self.param.verbose, 'normal')

        # open image and re-orient it to RPI if needed
        im_tmp = Image(self.param.fname_im)
        if self.orientation_im != self.orientation_extraction:
            im_tmp.change_orientation(self.orientation_extraction)

        dct_metric = {}
        for m in self.metric_lst:
            im_2save = msct_image.zeros_like(im_tmp, dtype='float64')
            dct_metric[m] = im_2save
            # dct_metric[m] = Image(self.fname_metric_lst[m])

        with tqdm.tqdm() as pbar:
            for im_z, seg_z, zz in zip(self.dct_im_seg['im'], self.dct_im_seg['seg'], range(len(self.dct_im_seg['im']))):
                for xx in range(im_z.shape[0]):
                    for yy in range(im_z.shape[1]):
                        if not seg_z[xx, yy]:
                            continue
                        if xx < offset or yy < offset:
                            continue
                        if xx > (im_z.shape[0] - offset - 1) or yy > (im_z.shape[1] - offset - 1):
                            continue  # to check if the whole glcm_window is in the axial_slice
                        if False in np.unique(seg_z[xx - offset: xx + offset + 1, yy - offset: yy + offset + 1]):
                            continue  # to check if the whole glcm_window is in the mask of the axial_slice

                        glcm_window = im_z[xx - offset: xx + offset + 1, yy - offset: yy + offset + 1]
                        glcm_window = glcm_window.astype(np.uint8)

                        dct_glcm = {}
                        for a in self.param_glcm.angle.split(','):  # compute the GLCM for self.param_glcm.distance and for each self.param_glcm.angle
                            dct_glcm[a] = greycomatrix(glcm_window,
                                                       [self.param_glcm.distance], [np.radians(int(a))],
                                                       symmetric=self.param_glcm.symmetric,
                                                       normed=self.param_glcm.normed)

                        for m in self.metric_lst:  # compute the GLCM property (m.split('_')[0]) of the voxel xx,yy,zz
                            dct_metric[m].data[xx, yy, zz] = greycoprops(dct_glcm[m.split('_')[2]], m.split('_')[0])[0][0]

                        pbar.set_postfix(pos="{}/{}".format(zz, len(self.dct_im_seg["im"])))
                        pbar.update(1)

        for m in self.metric_lst:
            fname_out = sct.add_suffix(''.join(sct.extract_fname(self.param.fname_im)[1:]), '_' + m)
            dct_metric[m].save(fname_out)
            self.fname_metric_lst[m] = fname_out
Exemple #25
0
def glcm_image(im, extent, distances, angles, props):
    """Given a 2D image, compute the local GLCM for each pixel
    Parameters
    ==========
    im : ndarray (im.ndim == 2)
        2D array to compute local GLCM on
        If `im` is a masked array, only compute results over the unmasked area
    extent: int
        Each local GLCM is computed in a square region around the current voxel,
        with 2*width = 2*height = extent
    distances : iterable<int>
        Iterable of distances to compute local GLCM at
    angles : iterable<float>
        Iterable of angles to compute local GLCM at
    props : iterable<str>
        Iterable of property names to compute
        
    Returns
    =======
    out : ndarray
        5D array of local GLCM results
        Dimensions are: [rows, cols, distances, angles, property]
    """
    assert im.ndim == 2, 'Only supports 2D arrays'
    nrows = im.shape[0]
    ncols = im.shape[1]
    is_masked = np.ma.isMaskedArray(im)
    distances = list(distances)
    angles = list(angles)
    props = list(props)
    if is_masked:
        data = im.data
        indices = zip(*np.where(~im.mask))
    else:
        data = im
        indices = itertools.product(range(nrows), range(ncols))
    g = rescale_intensity(data, out_range=(0, 255)).astype(int)
    out = np.zeros(g.shape + (len(distances), len(angles), len(props)))
    for r, c in indices:
        rmin = np.clip(r-extent, 0, nrows)
        rmax = np.clip(r+extent, 0, nrows)
        cmin = np.clip(c-extent, 0, ncols)
        cmax = np.clip(c+extent, 0, ncols)
        glcm = greycomatrix(g[rmin:rmax, cmin:cmax], distances, angles)
        for i, prop in enumerate(props):
            out[r, c, :, :, i] = greycoprops(glcm, prop)
    if is_masked:
        out = np.ma.array(out, mask=jtmri.np.expand(im.mask, out.shape[2:]))
    return out
Exemple #26
0
def calc_blob_property(b, keys = None):
    props = {}
    greycovmat = greycomatrix(np.nan_to_num((b/2.)+128), [2], [0], 256, symmetric=True, normed=True) #this func expects 0< pixel value < 256
    props['grey_dissimilarity'] = greycoprops(greycovmat, 'dissimilarity')[0, 0] 
    props['grey_energy'] = greycoprops(greycovmat, 'energy')[0, 0] 
    props['aspect_ratio'] = b.shape[0]*1./b.shape[1]
    props['size'] = np.count_nonzero(~np.isnan(b))
    
    props['threshold_otsu'] = threshold_otsu(np.nan_to_num(b))
    b_bw = (b>props['threshold_otsu'])    
    props['extent'] = 1.*np.count_nonzero(b_bw) / props['size']  # fraction of non zero pixels 
    
    ncluster = ndimage.label(b_bw,structure=np.ones((3,3)))[1]
    props['ncluster_frac'] = ncluster*1./np.count_nonzero(b_bw)
    
    corners = corner_peaks(corner_harris(b_bw), min_distance=1)
    props['corner_frac'] = len(corners)*100./np.count_nonzero(b_bw)
    
    props['median_intensity'] = np.nanmedian(abs(b)) 
    props['max_intensity'] = np.nanmax(abs(b)) 
    props['max_intensity'] = np.nanmax(abs(b)) 
    if keys:
        return [props[k] for k in keys]
    else: return props
def compute_glcm(image):
    glcm = greycomatrix(image, distances=[1, 2, 3, 4], angles=[0, numpy.pi/4, numpy.pi/2, 3*numpy.pi/4], levels=256, symmetric=False, normed=True)
    
    features = numpy.zeros((6, glcm.shape[2] * glcm.shape[3]), dtype = numpy.float64)
    features[0, :] = greycoprops(glcm, 'contrast').flatten()
    features[1, :] = greycoprops(glcm, 'energy').flatten()
    features[2, :] = greycoprops(glcm, 'homogeneity').flatten()
    features[3, :] = greycoprops(glcm, 'dissimilarity').flatten()
    features[4, :] = greycoprops(glcm, 'correlation').flatten()
    features[5, :] = greycoprops(glcm, 'ASM').flatten()
    
    return features
Exemple #28
0
def extractFeatV3(image_file):
    feat = extractFeatV1(image_file)
    
    image = imread(image_file, as_grey=True)
    image = image.copy()
    glcm = greycomatrix(image,
                        distances=[1, 2, 4, 8],
                        angles=[0, pi/4, pi/2, 3*pi/4],
                        levels=256,
                        normed=True,
                        symmetric=True)
    props = ['contrast', 'dissimilarity', 'homogeneity',
             'energy', 'correlation', 'ASM']
    for p in props:
        res = greycoprops(glcm, p)
        feat = np.hstack((feat, res.flatten()))
        
    return feat
Exemple #29
0
        def filter(self, array, *args, **kwargs):
            shp = array.shape
            array = array.reshape((np.prod(shp[0:-2]),) + shp[-2:])   # reshape to (nch, ny, nx)

            for k, amp in enumerate(np.abs(array)):  # loop over channels
                if self.ang == 'all':
                    angles = [0, np.pi/4, np.pi/2, 3*np.pi/4]
                else:
                    angles = [float(self.ang)/180.0*np.pi]

                shape = (amp.shape[0] - self.win + 1, amp.shape[1] - self.win + 1) + (self.win, self.win)
                strid = (amp.strides[0], amp.strides[1]) + amp.strides
                amp = as_strided(amp, shape=shape, strides=strid)
                for y in range(amp.shape[0]):
                    for x in range(amp.shape[1]):
                        win = amp[y, x]
                        p = greycomatrix(win, [self.dist], angles, levels=self.levels, symmetric=self.sym)  # calc glcm histogram
                        array[k, y+self.win//2, x+self.win//2] = np.mean(greycoprops(p, self.property))  # calc property
            array = array.reshape(shp)      # back to original shape
            return array
Exemple #30
0
def get_htf_features(image, props):
    features = []
    grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    g = greycomatrix(grey, [1], [0, 90, 45, 135], 256, symmetric=True, normed=True)
    for p in props:
        if p == 'entropy':
            entropy = np.apply_over_axes(np.sum, g * (-np.log1p(g)), axes=(0, 1))[0, 0]
            eu = np.mean(entropy)
            er = np.ptp(entropy)
            features.append([eu, er])
        else:
            gp = greycoprops(g, p)
            u = np.mean(gp)
            r = np.ptp(gp)
            features.append([u, r])

    features = np.array(features, dtype=np.float64)

    if len(props) != 1:
        for (x, y), value in np.ndenumerate(features):
            features[x, y] = (value - np.mean(features[:,y]))/np.std(features[:,y])

    return features.flatten()
Exemple #31
0
def glcm(im,
         mask=None,
         offset=None,
         features=[
             'contrast', 'dissimilarity', 'homogeneity', 'energy',
             'correlation', 'ASM'
         ]):
    """Calculate the grey level co-occurrence matrices and output values for
    contrast, dissimilarity, homogeneity, energy, correlation, and ASM in a list"""

    newIm = im
    if not isinstance(im, np.ndarray):
        newIm = np.array(im.convert('L'))  #Convert to a grey scale image
    # TODO: check if you want the offset to be a list or just a single value
    if offset is None:
        # we assume the pixel of interest is in the center of the rectangular image
        # and calculate the offset as half of the radius (or 1/4th of the diameter)
        offset = [int(s / 4) for s in newIm.shape[::-1]] * 2
    elif type(offset) == int:
        offset = [offset] * 4
    # calculate the glcm and then average over all 4 angles
    # glcm = np.mean(greycomatrix(newIm, offset, [0, np.pi/4, np.pi/2, 3*np.pi/4])[mask], axis=(-1, -2), keepdims=True)
    glcm = np.mean(greycomatrix(newIm, offset,
                                [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4]),
                   axis=(-1, -2),
                   keepdims=True)

    returns = []
    for feature in features:
        #Compute all of the grey co occurrence features.
        metric = greycoprops(glcm, feature)[0][0]
        if np.isnan(metric):
            metric = 0
        returns.append([metric])
    return np.concatenate(
        tuple(returns), 0)  #concatenate into one list along axis 0 and return
def glcm_image(img, measure="dissimilarity"):
    """TODO: allow different window sizes by parameterizing 3, 4. Also should
    parameterize direction vector [1] [0]"""
    texture = np.zeros_like(sub)

    # quadratic looping in python w/o vectorized routine, yuck!
    for i in range(img.shape[0]):
        for j in range(sub.shape[1]):

            # don't calculate at edges
            if (i < 3) or \
               (i > (img.shape[0])) or \
               (j < 3) or \
               (j > (img.shape[0] - 4)):
                continue

            # calculate glcm matrix for 7 x 7 window, use dissimilarity (can swap in
            # contrast, etc.)
            glcm_window = img[i - 3:i + 4, j - 3:j + 4]
            glcm = greycomatrix(glcm_window, [1], [0],
                                symmetric=True,
                                normed=True)
            texture[i, j] = greycoprops(glcm, measure)
    return texture
Exemple #33
0
    def _calculate_haralick(self, data):
        result = np.empty(data.shape, dtype=np.float)
        # For each date and each band
        for time in range(data.shape[0]):
            for band in range(data.shape[3]):
                image = data[time, :, :, band]
                image_min, image_max = np.min(image), np.max(image)
                coef = (image_max - image_min) / self.levels
                digitized_image = np.digitize(
                    image,
                    np.array([
                        image_min + k * coef for k in range(self.levels - 1)
                    ]))

                # Padding the image to handle borders
                pad = self.window_size // 2
                digitized_image = np.pad(digitized_image,
                                         ((pad, pad), (pad, pad)), 'edge')
                # Sliding window
                for i in range(0, image.shape[0], self.stride):
                    for j in range(0, image.shape[1], self.stride):
                        window = digitized_image[i:i + self.window_size,
                                                 j:j + self.window_size]
                        glcm = greycomatrix(window, [self.distance],
                                            [self.angle],
                                            levels=self.levels,
                                            normed=True,
                                            symmetric=True)

                        if self.texture_feature in self.AVAILABLE_TEXTURES_SKIMAGE:
                            res = greycoprops(glcm, self.texture_feature)[0][0]
                        else:
                            res = self._custom_texture(glcm[:, :, 0, 0])

                        result[time, i, j, band] = res
        return result
def calc_glcm_core(filename,
                   dists=[5],
                   agls=[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4],
                   lvl=256,
                   sym=True,
                   norm=True):
    img = cv2.imread(filename)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    h, w = gray.shape
    ymin, ymax, xmin, xmax = h // 3, h * 2 // 3, w // 3, w * 2 // 3
    crop = gray[ymin:ymax, xmin:xmax]

    resize = cv2.resize(crop, (0, 0), fx=0.5, fy=0.5)
    cv2.imwrite(filename, resize)
    props = [
        'dissimilarity', 'correlation', 'homogeneity', 'contrast', 'ASM',
        'energy'
    ]
    glcm = greycomatrix(resize,
                        distances=dists,
                        angles=agls,
                        levels=lvl,
                        symmetric=sym,
                        normed=norm)
    out = {}
    for name in props:
        out[name] = greycoprops(glcm, name)[0]

    feature = {}
    for i, angel in enumerate(["0", "45", "90", "135"]):
        feature[angel] = {}
        for name in props:
            feature[angel][name] = out[name][i]
    print(feature)
    return feature
Exemple #35
0
def glcm_f(segment_region):
    glcm = greycomatrix(segment_region, [5], [0], 256)

    stats = [
        "dissimilarity", "correlation", "contrast", "homogeneity", "ASM",
        "energy"
    ]
    dissimilarity = greycoprops(glcm, stats[0])[0, 0]
    correlation = greycoprops(glcm, stats[1])[0, 0]
    contrast = greycoprops(glcm, stats[2])[0, 0]
    homogeneity = greycoprops(glcm, stats[3])[0, 0]
    ASM = greycoprops(glcm, stats[4])[0, 0]
    energy = greycoprops(glcm, stats[5])[0, 0]
    entropy_f = entropy(segment_region)
    temp_features = [
        dissimilarity, correlation, contrast, homogeneity, ASM, energy,
        entropy_f
    ]
    return temp_features
Exemple #36
0
        def allFeatures(self, image):
            #Calculate the grey-level co-occurrence matrix.
            #result = greycomatrix(image, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4])
            #glcmFeat = []
            glcm = feature.greycomatrix(image, [1], self.axis, normed=True, symmetric=True)
            #print(type(feature.greycoprops(glcm, 'contrast')))
            glcmFeat = feature.greycoprops(glcm, 'contrast').reshape(-1,)
            #print(type(glcmFeat))
            #print(glcmFeat)
            glcmFeat = np.concatenate((glcmFeat, feature.greycoprops(glcm, 'dissimilarity').reshape(-1,)))
            glcmFeat = np.concatenate((glcmFeat, feature.greycoprops(glcm, 'homogeneity').reshape(-1,)))
            glcmFeat = np.concatenate((glcmFeat, feature.greycoprops(glcm, 'ASM').reshape(-1,)))
            glcmFeat = np.concatenate((glcmFeat, feature.greycoprops(glcm, 'energy').reshape(-1,)))
            glcmFeat = np.concatenate((glcmFeat, feature.greycoprops(glcm, 'correlation').reshape(-1,)))
			
            #print(type(glcmFeat))
            #print(glcmFeat)
			
            return glcmFeat
Exemple #37
0
def glcm_feature(image_gray):
    """
    基于灰度共生矩阵的纹理特征提取
    :param image_gray: 灰度图像
    :return: 灰度图像的六种纹理特征
    """
    image_gray = np.uint(np.floor(image_gray / 255 / 0.33333334))
    image_glcm = greycomatrix(image_gray, [1], [0], 3)
    image_glcm_feature = [
        int(greycoprops(image_glcm, 'contrast')),
        int(greycoprops(image_glcm, 'dissimilarity')),
        int(greycoprops(image_glcm, 'homogeneity')),
        int(greycoprops(image_glcm, 'energy')),
        int(greycoprops(image_glcm, 'ASM')),
        int(greycoprops(image_glcm, 'correlation'))
    ]
    # image_glcm_feature = (image_glcm_feature - np.min(image_glcm_feature)) / (
    #         np.max(image_glcm_feature) - np.min(image_glcm_feature))
    return list(image_glcm_feature)
Exemple #38
0
    def glcm_extraction(data):
        new_data = []

        for im in data:
            im = im.reshape(35, 35)
            im = im.astype(np.uint8)

            g = feature.greycomatrix(im, [0, 1], [0, np.pi/2], levels=8, normed=True, symmetric=True)
            contrast = feature.greycoprops(g, 'contrast').flatten()
            energy = feature.greycoprops(g, 'energy').flatten()
            homogeneity = feature.greycoprops(g, 'homogeneity').flatten()
            correlation = feature.greycoprops(g, 'correlation').flatten()
            dissimilarity = feature.greycoprops(g, 'dissimilarity').flatten()
            asm = feature.greycoprops(g, 'ASM').flatten()

            features = np.concatenate((contrast, energy, homogeneity, correlation, dissimilarity, asm))
            new_data.append(features)

        return np.array(new_data)
Exemple #39
0
def compute_glcm_feature(glcm):
    """
    glcm:[nbit,nbit,len(step),len(angle),h,w], usually the len(step) and len(angle) is 1.
    """
    nbit, _, len_step, len_angle, h, w = glcm.shape
    # create zeros-array
    contrast = np.zeros(shape=(h, w, len_step, len_angle), dtype=np.float32)
    dissimilarity = np.zeros(shape=(h, w, len_step, len_angle),
                             dtype=np.float32)
    homogeneity = np.zeros(shape=(h, w, len_step, len_angle), dtype=np.float32)
    energy = np.zeros(shape=(h, w, len_step, len_angle), dtype=np.float32)
    correlation = np.zeros(shape=(h, w, len_step, len_angle), dtype=np.float32)
    ASM = np.zeros(shape=(h, w, len_step, len_angle), dtype=np.float32)

    for i in range(h):
        for j in range(w):
            contrast[i, j] = greycoprops(glcm[:, :, :, :, i, j], "contrast")
            dissimilarity = greycoprops(glcm[:, :, :, :, i, j],
                                        "dissimilarity")
            homogeneity = greycoprops(glcm[:, :, :, :, i, j], "homogeneity")
            energy = greycoprops(glcm[:, :, :, :, i, j], "energy")
            correlation = greycoprops(glcm[:, :, :, :, i, j], "correlation")
            ASM = greycoprops(glcm[:, :, :, :, i, j], "ASM")
    """
    contrast = greycoprops(glcm,"constrast")
    dissimilarity = greycoprops(glcm,"dissimilarity")
    homogeneity = greycoprops(glcm,"homogeneity")
    energy = greycoprops(glcm,"energy")
    correlation = greycoprops(glcm,"corellation")
    ASM = greycoprops(glcm,"ASm")
    """

    texture = {
        "contrast": contrast,
        "dissimilarity": dissimilarity,
        "homogeneity": homogeneity,
        "energy": energy,
        "correlation": correlation,
        "ASM": ASM
    }

    return texture
Exemple #40
0
def p_me(Z, win, dist, angle):
    '''
    loop to standard deviation
    '''
    if np.count_nonzero(Z) > 0.75 * win**2:
        glcm = greycomatrix(Z, [dist], [angle],
                            256,
                            symmetric=True,
                            normed=True)
        cont = greycoprops(glcm, 'contrast')
        diss = greycoprops(glcm, 'dissimilarity')
        h**o = greycoprops(glcm, 'homogeneity')
        eng = greycoprops(glcm, 'energy')
        corr = greycoprops(glcm, 'correlation')
        ASM = greycoprops(glcm, 'ASM')
        entropy = entropy_calc(glcm)
        mean, var = mean_var(glcm)
        return (cont, diss, h**o, eng, corr, ASM, entropy, mean, var)
    else:
        return (0, 0, 0, 0, 0, 0, 0, 0, 0)
def getGLCMfeatures(img_path):
    img = cv2.imread(img_path)
    img = img[:, :, 0]

    glcm = greycomatrix(img, [1], [0], symmetric=True, normed=True)
    contrast = greycoprops(glcm, 'contrast')
    dissimilarityraster = greycoprops(glcm, 'dissimilarity')
    homogeneityraster = greycoprops(glcm, 'homogeneity')
    energyraster = greycoprops(glcm, 'energy')
    correlationraster = greycoprops(glcm, 'correlation')
    ASMraster = greycoprops(glcm, 'ASM')
    '''
    print("contrast={}".format(contrast))
    print("dissimilarityraster={}".format(dissimilarityraster))
    print("homogeneityraster={}".format(homogeneityraster))
    print("energyraster={}".format(energyraster))
    print("correlationraster={}".format(correlationraster))
    print("ASMraster={}".format(ASMraster))
    '''
    return ASMraster, contrast, correlationraster, homogeneityraster, energyraster, dissimilarityraster
    def ext_text(image, x_min, x_max, y_min, y_max, channel):

        texture_props = np.zeros((len(x_min), 6))

        for i in range(len(x_min)):
            window = image[y_min[i]:y_max[i], x_min[i]:x_max[i], channel]

            GLCM = greycomatrix(
                window, [5], [0, np.pi / 4, np.pi / 2, (3 * np.pi) / 4],
                symmetric=True,
                normed=True
            )  # "angular" mean for 0°, 45°, 90°, 135° as defined in Albregtsen

            texture_props[i, 0] = np.mean(greycoprops(GLCM, 'contrast'))
            texture_props[i, 1] = np.mean(greycoprops(GLCM, 'dissimilarity'))
            texture_props[i, 2] = np.mean(greycoprops(GLCM, 'homogeneity'))
            texture_props[i, 3] = np.mean(greycoprops(GLCM, 'ASM'))
            texture_props[i, 4] = np.mean(greycoprops(GLCM, 'energy'))
            texture_props[i, 5] = np.mean(greycoprops(GLCM, 'correlation'))

        return texture_props
def get_features(image):
    sub_window_size_r = int(64 / 2)
    sub_window_size_c = int(64 / 2)
    dissimilarity_desc = []
    contrast_desc = []
    homogeneity_desc = []
    asm_desc = []
    energy_desc = []
    correlation_desc = []
    for r in range(0, image.shape[0] - 1, sub_window_size_r):
        for c in range(0, image.shape[1] - 1, sub_window_size_c):
            window = image[r:r + sub_window_size_r, c:c + sub_window_size_c]
            g = greycomatrix(window,
                             distances=[5],
                             angles=[0],
                             levels=256,
                             symmetric=True,
                             normed=True)
            dissimilarity = greycoprops(g, 'dissimilarity')
            dissimilarity_desc.append(dissimilarity[0, 0])

            contrast = greycoprops(g, 'contrast')
            contrast_desc.append(contrast[0, 0])

            homogeneity = greycoprops(g, 'homogeneity')
            homogeneity_desc.append(homogeneity[0, 0])

            asm = greycoprops(g, 'ASM')
            asm_desc.append(asm[0, 0])

            energy = greycoprops(g, 'energy')
            energy_desc.append(energy[0, 0])

            correlation = greycoprops(g, 'correlation')
            correlation_desc.append(correlation[0, 0])

    grey_coocurrence_props_descriptors = np.concatenate(
        [dissimilarity_desc, contrast_desc, asm_desc])

    return grey_coocurrence_props_descriptors
Exemple #44
0
    def run(self, image):
        """Extract the following texture properties defined in the GLCM: energy, contrast, correlation, homogeneity and dissimilarity,
        with distance 1 and 2 and angles 0, 45 and 90 degrees.
        
        Parameters
        ----------
        image : opencv image
            Image to be analyzed.
        
        Returns
        -------
        features : tuple
            Returns a tuple containing a list of labels, type and values for each feature extracted.
        """
        image_grayscale = ImageUtils.image_grayscale(image, bgr = True)

        g = feature.greycomatrix(image_grayscale, [1, 2], [0, np.pi / 4, np.pi / 2], self.glcm_levels, normed=True, symmetric=True)

        contrast = feature.greycoprops(g, 'contrast').tolist()
        dissimilarity = feature.greycoprops(g, 'dissimilarity').tolist()
        homogeneity = feature.greycoprops(g, 'homogeneity').tolist()
        asm = feature.greycoprops(g, 'ASM').tolist()
        energy = feature.greycoprops(g, 'energy').tolist()
        correlation = feature.greycoprops(g, 'correlation').tolist()

        labels = [
            'glcm_cont_1_0', 'glcm_cont_1_45', 'glcm_cont_1_90', 'glcm_cont_2_0', 'glcm_cont_2_45', 'glcm_cont_2_90',
            'glcm_diss_1_0', 'glcm_diss_1_45', 'glcm_diss_1_90', 'glcm_diss_2_0', 'glcm_diss_2_45', 'glcm_diss_2_90',
            'glcm_homo_1_0', 'glcm_homo_1_45', 'glcm_homo_1_90', 'glcm_homo_2_0', 'glcm_homo_2_45', 'glcm_homo_2_90',
            'glcm_asm_1_0', 'glcm_asm_1_45', 'glcm_asm_1_90', 'glcm_asm_2_0', 'glcm_asm_2_45', 'glcm_asm_2_90',
            'glcm_ener_1_0', 'glcm_ener_1_45', 'glcm_ener_1_90', 'glcm_ener_2_0', 'glcm_ener_2_45', 'glcm_ener_2_90',
            'glcm_corr_1_0', 'glcm_corr_1_45', 'glcm_corr_1_90', 'glcm_corr_2_0', 'glcm_corr_2_45', 'glcm_corr_2_90',

        ]
        types = [Extractor.NUMERIC] * len(labels)

        values = contrast[0] + contrast[1] + dissimilarity[0] + dissimilarity[1] + homogeneity[0] + \
                  homogeneity[1] + asm[0] + asm[1] + energy[0] + energy[1] + correlation[0] + correlation[1]

        return labels, types, values
	def feature_coMat(self,mode = 'all',index=None,distances=[10],angles=[0, np.pi/4, np.pi/2, 3*np.pi/4]):
		if mode=='all':
			output = []
			for i in range(self.n_index):
				temp_img = self.get1img(i,'gray')
				temp_comat = feature.greycomatrix(temp_img,distances, angles)
				en = feature.greycoprops(temp_comat,'energy')
				const = feature.greycoprops(temp_comat,'contrast')
				coore = feature.greycoprops(temp_comat,'correlation')
				output.append( np.concatenate([en,const,coore]).reshape((-1)) )

			return np.array(output)
		elif mode=='single':
			if index == None:
				print("please input index")
				return
			temp_img  = self.get1img(index,'gray')
			temp_comat = feature.greycomatrix(temp_img,distances, angles)
			en = feature.greycoprops(temp_comat,'energy')
			const = feature.greycoprops(temp_comat,'contrast')
			coore = feature.greycoprops(temp_comat,'correlation')
			return np.concatenate([en,const,coore]).reshape((-1)) 
def featureImage(resized_img):
    iar = np.asarray(resized_img)
    #     print(iar)
    iar.max()
    # 'contrast',‘dissimilarity’, ‘homogeneity’, ‘energy’, ‘correlation’, ‘ASM’
    glcm = g = greycomatrix(iar, [1, 2], [0, np.pi / 2],
                            levels=260,
                            normed=True,
                            symmetric=True)

    contrast = greycoprops(glcm, 'contrast')
    print("the contrast of the images is ", contrast)
    dissimilarity = greycoprops(glcm, 'dissimilarity')
    print("the dissimilarity of the images is ", dissimilarity)
    homogeneity = greycoprops(glcm, 'homogeneity')
    print("the homogeneity of the images is ", homogeneity)
    energy = greycoprops(glcm, 'energy')
    print("the energy of the images is ", energy)
    correlation = greycoprops(glcm, 'correlation')
    print("the correlation of the images is ", energy)
    ASM = greycoprops(glcm, 'ASM')
    print("the ASM of the images is ", ASM)
Exemple #47
0
    def feature_extraction(self, matrix_coocurrence):
        contrast = greycoprops(matrix_coocurrence, 'contrast')
        dissimilarity = greycoprops(matrix_coocurrence, 'dissimilarity')
        homogeneity = greycoprops(matrix_coocurrence, 'homogeneity')
        energy = greycoprops(matrix_coocurrence, 'energy')
        correlation = greycoprops(matrix_coocurrence, 'correlation')
        asm = greycoprops(matrix_coocurrence, 'ASM')

        contrast_df = pd.DataFrame(np.concatenate([contrast]))
        dissimilarity_df = pd.DataFrame(np.concatenate([dissimilarity]))
        homogeneity_df = pd.DataFrame(np.concatenate([homogeneity]))
        energy_df = pd.DataFrame(np.concatenate([energy]))
        correlation_df = pd.DataFrame(np.concatenate([correlation]))
        asm_df = pd.DataFrame(np.concatenate([asm]))

        result = pd.concat([
            contrast_df, dissimilarity_df, homogeneity_df, energy_df,
            correlation_df, asm_df
        ],
                           axis=1)

        return result
Exemple #48
0
def texture(image, PATCH_SIZE = 5):

    # therefore windows size = 2*Patchsize +1

    #setting up progress bar
    bar = progressbar.ProgressBar(max_value=image.shape[0])

    #sarraster is satellite image, testraster will receive texture
    texraster =  np.zeros([6, image.shape[0], image.shape[1]])


    for i in range(image.shape[0] ):
        time.sleep(0.1)
        bar.update(i)

        for j in range(image.shape[1] ):

            #windows needs to fit completely in image
            if i <PATCH_SIZE or j <PATCH_SIZE:
                continue
            if i > (image.shape[0] - (PATCH_SIZE+1)) or j > (image.shape[1] - (PATCH_SIZE+1)):
                continue

            #Calculate GLCM on a 7x7 window
            glcm_window = image[i-PATCH_SIZE: i+PATCH_SIZE+1, j-PATCH_SIZE : j+PATCH_SIZE+1]
            glcm = greycomatrix(image = glcm_window, distances = [1], angles = [0], levels= 256,  symmetric = True, normed = True )

            #Calculate contrast and replace center pixel
            # http: // scikit - image.org / docs / dev / api / skimage.feature.html  # skimage.feature.greycoprops
            texraster[0, i, j] = greycoprops(glcm, 'contrast')
            texraster[1, i, j] = greycoprops(glcm, 'dissimilarity')
            texraster[2, i, j] = greycoprops(glcm, 'correlation')
            texraster[3, i, j] = greycoprops(glcm, 'homogeneity')
            texraster[4, i, j] = greycoprops(glcm, 'energy')
            texraster[5, i, j] = greycoprops(glcm, 'ASM')

    #sarplot = plt.imshow(texraster, cmap = 'gray')
    return texraster
Exemple #49
0
    def features(self, img, winSize, stepSize=1):
        #calculating glcm-features
        assert winSize % 2 == 1, "Window Size has to be odd number!"

        (width, height) = img.shape

        contrast = np.zeros([width, height])
        dissimilarity = np.zeros([width, height])
        homogeneity = np.zeros([width, height])
        ASM = np.zeros([width, height])
        energy = np.zeros([width, height])
        correlation = np.zeros([width, height])

        for (x, y, window) in self.slidingWindow(img, winSize):
            if window.shape[0] != winSize or window.shape[1] != winSize:
                continue
            glcm = greycomatrix(window, [1], [0],
                                levels=256,
                                symmetric=True,
                                normed=True)
            contrast[y, x] = greycoprops(glcm, 'contrast')
            dissimilarity[y, x] = greycoprops(glcm, 'dissimilarity')
            homogeneity[y, x] = greycoprops(glcm, 'homogeneity')
            ASM[y, x] = greycoprops(glcm, 'ASM')
            energy[y, x] = greycoprops(glcm, 'energy')
            correlation[y, x] = greycoprops(glcm, 'correlation')

        glcm_feat = np.stack(
            (contrast, dissimilarity, homogeneity, ASM, energy, correlation),
            axis=2)

        #filling edges of feature-array
        glcm_feat[:self.edge, :] = glcm_feat[(self.edge):(self.edge * 2), :]
        glcm_feat[-self.edge:, :] = glcm_feat[(-self.edge * 2):(-self.edge), :]
        glcm_feat[:, :self.edge] = glcm_feat[:, (self.edge):(self.edge * 2)]
        glcm_feat[:, -self.edge:] = glcm_feat[:, (-self.edge * 2):(-self.edge)]

        return (glcm_feat)
Exemple #50
0
    def glcm(self, X):

        X_new = []
        for img in X:
            g = feature.greycomatrix(np.array(img, dtype='uint8'), [1, 2],
                                     [0, np.pi / 4, np.pi / 2],
                                     2,
                                     normed=True,
                                     symmetric=True)

            contrast = feature.greycoprops(g, 'contrast').tolist()
            dissimilarity = feature.greycoprops(g, 'dissimilarity').tolist()
            homogeneity = feature.greycoprops(g, 'homogeneity').tolist()
            asm = feature.greycoprops(g, 'ASM').tolist()
            energy = feature.greycoprops(g, 'energy').tolist()
            correlation = feature.greycoprops(g, 'correlation').tolist()

            values = contrast[0] + contrast[1] + dissimilarity[0] + dissimilarity[1] + homogeneity[0] + \
                      homogeneity[1] + asm[0] + asm[1] + energy[0] + energy[1] + correlation[0] + correlation[1]

            X_new.append(values)

        return X_new
Exemple #51
0
def get_feature(img):
    matrix_coocurrence = img_2_glcm(img)

    contrast = greycoprops(matrix_coocurrence, "contrast")
    cs = np.hstack((contrast[0], contrast[1], contrast[2]))

    dissimilarity = greycoprops(matrix_coocurrence, "dissimilarity")
    ds = np.hstack((dissimilarity[0], dissimilarity[1], dissimilarity[2]))

    homogeneity = greycoprops(matrix_coocurrence, "homogeneity")
    hs = np.hstack((homogeneity[0], homogeneity[1], homogeneity[2]))

    energy = greycoprops(matrix_coocurrence, "energy")
    es = np.hstack((energy[0], energy[1], energy[2]))

    correlation = greycoprops(matrix_coocurrence, "correlation")
    cos = np.hstack((correlation[0], correlation[1], correlation[2]))

    asm = greycoprops(matrix_coocurrence, "ASM")
    asms = np.hstack((asm[0], asm[1], asm[2]))

    img_feature = np.hstack((cs, ds, hs, es, cos, asms))
    return img_feature
def glcm(image, window_size):
    OFFSET = [1]
    THETA = [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4]
    N_GREY_LEVELS = 256

    patches = extract_patches_2d(image, (window_size, window_size))

    contrast = []
    ASM = []
    correlation = []

    for patch in patches:
        P = feature.greycomatrix(patch,
                                 OFFSET,
                                 THETA,
                                 levels=N_GREY_LEVELS,
                                 symmetric=True,
                                 normed=True)
        feature.greycoprops(P, prop='contrast')
        feature.greycoprops(P, prop='ASM')
        feature.greycoprops(P, prop='correlation')

    return contrast, ASM, correlation, P
def getGLCMFeatures(image,
                    distances=[1, 3, 5],
                    angles=[0, np.pi / 4.0, np.pi / 2.0, 3 * np.pi / 4.0]):
    glcm_feature_vector = []

    x = 0
    for i in range(0, 5):
        patch = image[x:x + 20][:]
        x += 20
        glcm = greycomatrix(patch,
                            distances,
                            angles,
                            2,
                            symmetric=True,
                            normed=True)
        for j in range(len(distances)):
            for k in range(len(angles)):
                contrast = float(greycoprops(glcm, 'contrast')[j, k])
                glcm_feature_vector.append(contrast)

                dissimilarity = greycoprops(glcm, 'dissimilarity')[j, k]
                glcm_feature_vector.append(dissimilarity)

                homogeneity = greycoprops(glcm, 'homogeneity')[j, k]
                glcm_feature_vector.append(homogeneity)

                ASM = greycoprops(glcm, 'ASM')[j, k]
                glcm_feature_vector.append(ASM)

                energy = greycoprops(glcm, 'energy')[j, k]
                glcm_feature_vector.append(energy)

                correlation = greycoprops(glcm, 'correlation')[j, k]
                glcm_feature_vector.append(correlation)

    glcm_feature_vector = np.array(glcm_feature_vector)
    return glcm_feature_vector
def glcm_features(img_orig,mask,img_gray):
    mask_idx = mask.astype('uint8')
    segment_region = np.multiply(img_gray, mask_idx)
    segment_region = segment_region.astype('uint8')
    comp_temp = ma.array(segment_region, mask=~mask_idx)
    comp_temp = comp_temp.astype('uint8')
    comp_temp = np.delete(comp_temp, np.argwhere(np.all(comp_temp[..., :] == 0, axis=0)), axis=1)
    comp_temp = np.delete(comp_temp, np.where(~comp_temp.any(axis=1))[0], axis=0)
    comp_temp = np.delete(comp_temp, np.argwhere(np.all(comp_temp[..., :] == 0, axis=0)), axis=1)
    comp_temp = np.delete(comp_temp, np.where(~comp_temp.any(axis=1))[0], axis=0)

    compressed_segment_region = ma.array(segment_region, mask=~mask_idx).compressed()
    glcm = greycomatrix(comp_temp, [5], [0], 256)

    stats = ["dissimilarity", "correlation", "contrast", "homogeneity", "ASM", "energy"]
    dissimilarity = greycoprops(glcm, stats[0])[0, 0]
    correlation = greycoprops(glcm, stats[1])[0, 0]
    contrast = greycoprops(glcm, stats[2])[0, 0]
    homogeneity = greycoprops(glcm, stats[3])[0, 0]
    ASM = greycoprops(glcm, stats[4])[0, 0]
    energy = greycoprops(glcm, stats[5])[0, 0]

    temp_features = [dissimilarity, correlation,contrast,homogeneity,ASM,energy]
    return temp_features
    grass_patches.append(image[loc[0]:loc[0] + PATCH_SIZE,
                               loc[1]:loc[1] + PATCH_SIZE])

# select some patches from sky areas of the image
sky_locations = [(54, 48), (21, 233), (90, 380), (195, 330)]
sky_patches = []
for loc in sky_locations:
    sky_patches.append(image[loc[0]:loc[0] + PATCH_SIZE,
                             loc[1]:loc[1] + PATCH_SIZE])

# compute some GLCM properties each patch
xs = []
ys = []
for patch in (grass_patches + sky_patches):
    glcm = greycomatrix(patch, [5], [0], 256, symmetric=True, normed=True)
    xs.append(greycoprops(glcm, 'contrast')[0, 0])
    ys.append(greycoprops(glcm, 'correlation')[0, 0])

# create the figure
fig = plt.figure(figsize=(8, 8))

# display original image with locations of patches
ax = fig.add_subplot(3, 2, 1)
ax.imshow(image, cmap=plt.cm.gray, interpolation='nearest', vmin=0, vmax=255)
for (y, x) in grass_locations:
    ax.plot(x + PATCH_SIZE / 2, y + PATCH_SIZE / 2, 'gs')
for (y, x) in sky_locations:
    ax.plot(x + PATCH_SIZE / 2, y + PATCH_SIZE / 2, 'bs')
ax.set_xlabel('Original Image')
ax.set_xticks([])
ax.set_yticks([])
def _contrast(glcm):
    return greycoprops(glcm, 'contrast')[0][0]
def _correlation(glcm):
    return greycoprops(glcm, 'correlation')[0][0]
yHeader2.insert(0,'Time')
yHeader = yHeader1 + "\t".join(yHeader2) + '\n'
outFileY.write(yHeader)

numImages = tiffStack.shape[0]

timeMinutes = 0
d = np.arange(1,100,2)
de= np.arange(101,512,8)
d = np.concatenate((d,de))

for i in range(5,numImages,numSkippedFrames):
    iImage = tiffStack[i,:,:]
    gx = skf.greycomatrix(iImage, d, [0], 1024, 
                        symmetric=True, normed=True)
    cx = skf.greycoprops(gx, 'dissimilarity')
    cx = np.ndarray.flatten(cx)
    cx = np.ndarray.tolist(cx)
    gy = skf.greycomatrix(iImage, d, [1.5708], 1024, 
                        symmetric=True, normed=True)
    cy = skf.greycoprops(gy, 'dissimilarity')
    cy = np.ndarray.flatten(cy)
    cy = np.ndarray.tolist(cy)    
    timeMinutes = timeMinutes + 5*numSkippedFrames
    outFileX.write('%8.2f\t' % timeMinutes)
    for n in cx:
        outFileX.write('%8.3f\t' % n)
    outFileX.write('\n')
    outFileY.write('%8.2f\t' % timeMinutes)
    for n in cy:
        outFileY.write('%8.3f\t' % n)
Exemple #59
0
def test_result(feature_book , path , root):
    gray_test_image = rgb2gray(test_image)
    sheet = feature_book['Sheet1']
    pixel_frequency = get_frequency(gray_test_image)
    result_list = []

    t_maximum_probability = np.amax(pixel_frequency)
    t_correlation = greycoprops(pixel_frequency, 'correlation')[0][0]
    t_contrast = greycoprops(pixel_frequency, 'contrast')[0][0]
    t_energy = greycoprops(pixel_frequency, 'energy')[0][0]
    t_homogeneity = greycoprops(pixel_frequency, 'homogeneity')[0][0]
    t_entropy = skimage.measure.shannon_entropy(pixel_frequency)

    for row in range(2, sheet.max_row + 1):
        cell = sheet.cell(row, 1)
        file_name = cell.value
        cell = sheet.cell(row, 2)
        maximum_probability = cell.value
        cell = sheet.cell(row, 3)
        correlation = cell.value
        cell = sheet.cell(row, 4)
        contrast = cell.value
        cell = sheet.cell(row, 5)
        energy = cell.value
        cell = sheet.cell(row, 6)
        homogeneity = cell.value
        cell = sheet.cell(row, 7)
        entropy = cell.value
        c_distance = ((abs(maximum_probability-t_maximum_probability)/(abs(maximum_probability)+abs(t_maximum_probability)) )+
                      (abs(correlation-t_correlation)/(abs(correlation)+abs(t_correlation)))+
                      (abs(contrast-t_contrast)/(abs(contrast)+abs(t_contrast) ))+
                      (abs(energy- t_energy)/(abs(energy)+abs(t_energy)))+
                      (abs(homogeneity-t_homogeneity)/(abs(homogeneity)+abs(t_homogeneity)))+
                      (abs(entropy-t_entropy)/(abs(entropy)+abs(t_entropy))))
        item = {'FileName' : file_name, 'distance' : c_distance}
        result_list.append(item)

    result_list.sort(key=itemgetter('distance'))


    print(len(result_list))

    file_name_list = []
    count = 0
    for file in result_list:
        file_name_list.append(file['FileName'])
        count+=1;
        if count == 10:
            break
    win = root



    myvar = Label(win, text="Similar Image : ")
    myvar.text = "Similar Image : "
    myvar.grid(row=1, column=0)
    COLUMNS = 6
    image_count = 7
    #myvar = Label(win, text = "result").grid(row=2,col=3)
    for infile in path.glob('*.png'):

        if infile.name in file_name_list:

            if image_count == 12:
                image_count += 1
            image_count += 1

            r, c = divmod(image_count - 1, COLUMNS)
            im = Image.open(infile)
            resized = im.resize((120, 120), Image.ANTIALIAS)
            tkimage = ImageTk.PhotoImage(resized)
            myvar = Label(win, image=tkimage)
            myvar.image = tkimage
            myvar.grid(row=r, column=c)
def asm_feature(matrix_coocurrence):
    asm = greycoprops(matrix_coocurrence, 'ASM')
    return "ASM = ", asm