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
def test_output_empty(self): result = greycomatrix(self.image, [10], [0], 4) np.testing.assert_array_equal(result[:, :, 0, 0], np.zeros((4, 4), dtype=np.uint32)) result = greycomatrix(self.image, [10], [0], 4, normed=True) np.testing.assert_array_equal(result[:, :, 0, 0], np.zeros((4, 4), dtype=np.uint32))
def get_textural_features(img, isMultidirectional=False, distance=1): '''Extract GLCM feature vector from image Args: img: input image. isMultidirectional: Controls whether co-occurence should be calculated in other directions (ie 45 degrees, 90 degrees and 135 degrees). distance: Distance between pixels for co-occurence. Returns: features: if isMultidirectional=False, this is a 4 element vector of [dissimilarity, correlation,homogeneity, energy]. If not it is a 16 element vector containing each of the above properties in each direction. ''' if(isMultidirectional): img = img_as_ubyte(rgb2gray(img)) glcm = greycomatrix(img, [distance], [0, 0.79, 1.57, 2.36], 256, symmetric=True, normed=True) dissimilarity_1 = greycoprops(glcm, 'dissimilarity')[0][0] dissimilarity_2 = greycoprops(glcm, 'dissimilarity')[0][1] dissimilarity_3 = greycoprops(glcm, 'dissimilarity')[0][2] dissimilarity_4 = greycoprops(glcm, 'dissimilarity')[0][3] correlation_1 = greycoprops(glcm, 'correlation')[0][0] correlation_2 = greycoprops(glcm, 'correlation')[0][1] correlation_3 = greycoprops(glcm, 'correlation')[0][2] correlation_4 = greycoprops(glcm, 'correlation')[0][3] homogeneity_1 = greycoprops(glcm, 'homogeneity')[0][0] homogeneity_2 = greycoprops(glcm, 'homogeneity')[0][1] homogeneity_3 = greycoprops(glcm, 'homogeneity')[0][2] homogeneity_4 = greycoprops(glcm, 'homogeneity')[0][3] energy_1 = greycoprops(glcm, 'energy')[0][0] energy_2 = greycoprops(glcm, 'energy')[0][1] energy_3 = greycoprops(glcm, 'energy')[0][2] energy_4 = greycoprops(glcm, 'energy')[0][3] feature = np.array([dissimilarity_1, dissimilarity_2, dissimilarity_3,\ dissimilarity_4, correlation_1, correlation_2, correlation_3, correlation_4,\ homogeneity_1, homogeneity_2, homogeneity_3, homogeneity_4, energy_1,\ energy_2, energy_3, energy_4]) return feature else: img = img_as_ubyte(rgb2gray(img)) glcm = greycomatrix(img, [distance], [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
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
def glide(image, w, d, theta, levels=16, step=2): image = np.pad(image, int(w/2), mode='reflect') M, N = image.shape # map_homo = np.zeros((M, N)) # map_iner = np.zeros((M, N)) # map_clsh = np.zeros((M, N)) map_Q1 = np.zeros((M, N)) map_Q2 = np.zeros((M, N)) map_Q4 = np.zeros((M, N)) for m in xrange(0, M, step): print m for n in xrange(0, N, step): window = image[m:m+w, n:n+w] P = greycomatrix( window, d, theta*np.pi/180, levels, symmetric=True, normed=True, ).mean(axis=(2,3)) / float(len(d) * len(theta)) mu = np.mean(window) # map_homo[m:m+step, n:n+step] = homogeneity(P) # map_iner[m:m+step, n:n+step] = inertia(P) # map_clsh[m:m+step, n:n+step] = clustershade(P) map_Q1[m:m+step, n:n+step] = Q1(P) map_Q2[m:m+step, n:n+step] = Q2(P) map_Q4[m:m+step, n:n+step] = Q4(P) # return map_homo, map_iner, map_clsh return map_Q1, map_Q2, map_Q4
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(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 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]
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 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
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 compute(self, image): glcm = feature.greycomatrix(image, self.distance, self.angle, 256, symmetric = True, normed = True) #Calculating and normalizing the histogram x = itemfreq(glcm.ravel()) hist = x[:, 1]/sum(x[:, 1]) return hist
def glcm(image, angles, dists): """ Extract features from the image. Args: image: An image read in by cv2.imread(...) angles: A list containing angles, e.g. [0, 45, 90, 135] dists: A list containing pixel distances, e.g. [0, 1, 2, 3] Returns: A gray-level co-occurrence matrix. """ if isinstance(image, list): glcms = [] for i in range(0, len(image)): glcms.append(greycomatrix(image[i], angles, dists, 256, symmetric=True, normed=True)) return glcms else: return greycomatrix(image, angles, dists, 256, symmetric=True, normed=True)
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 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
def test_output_symmetric_1(self): result = greycomatrix(self.image, [1], [np.pi / 2], 4, symmetric=True) assert result.shape == (4, 4, 1, 1) expected = np.array([[6, 0, 2, 0], [0, 4, 2, 0], [2, 2, 2, 2], [0, 0, 2, 0]], dtype=np.uint32) np.testing.assert_array_equal(result[:, :, 0, 0], expected)
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
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 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 test_normed_symmetric(self): result = greycomatrix(self.image, [1, 2, 3], [0, np.pi / 2, np.pi], 4, normed=True, symmetric=True) for d in range(result.shape[2]): for a in range(result.shape[3]): np.testing.assert_almost_equal(result[:, :, d, a].sum(), 1.0) np.testing.assert_array_equal(result[:, :, d, a], result[:, :, d, a].transpose())
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 calcDSC_IID135_D2(img, nbit=3): bshift=8-nbit pimg=(img>>bshift) res = greycomatrix(pimg, [1,3,5], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=(1<<nbit), symmetric=True) res = np.sum(res,3).astype(np.float64) idxDiag=np.tri(res.shape[0],res.shape[1]) dsc0=res[:,:,0] dsc1=res[:,:,1] dsc2=res[:,:,2] dsc=np.concatenate( [dsc0[idxDiag>0], dsc1[idxDiag>0], dsc2[idxDiag>0]] ) return dsc/np.sum(dsc)
def test_output_distance(self): im = np.array([[0, 0, 0, 0], [1, 0, 0, 1], [2, 0, 0, 2], [3, 0, 0, 3]], dtype=np.uint8) result = greycomatrix(im, [3], [0], 4, symmetric=False) expected = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=np.uint32) np.testing.assert_array_equal(result[:, :, 0, 0], expected)
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 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)
def test_output_angles(self): result = greycomatrix(self.image, [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], 4) assert result.shape == (4, 4, 1, 4) expected1 = np.array([[2, 2, 1, 0], [0, 2, 0, 0], [0, 0, 3, 1], [0, 0, 0, 1]], dtype=np.uint32) np.testing.assert_array_equal(result[:, :, 0, 0], expected1) expected2 = np.array([[1, 1, 3, 0], [0, 1, 1, 0], [0, 0, 0, 2], [0, 0, 0, 0]], dtype=np.uint32) np.testing.assert_array_equal(result[:, :, 0, 1], expected2) expected3 = np.array([[3, 0, 2, 0], [0, 2, 2, 0], [0, 0, 1, 2], [0, 0, 0, 0]], dtype=np.uint32) np.testing.assert_array_equal(result[:, :, 0, 2], expected3) expected4 = np.array([[2, 0, 0, 0], [1, 1, 2, 0], [0, 0, 2, 1], [0, 0, 0, 0]], dtype=np.uint32) np.testing.assert_array_equal(result[:, :, 0, 3], expected4)
def calcDSC_IID135_G2(img,nbit=3): bshift=8-nbit pimg=(img>>bshift) siz=pimg.shape pp=(siz[0]/2,siz[1]/2) res00 = greycomatrix(pimg[:pp[0],:pp[1]], [1,3,5], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=(1<<nbit), symmetric=True) res01 = greycomatrix(pimg[:pp[0],pp[1]:], [1,3,5], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=(1<<nbit), symmetric=True) res10 = greycomatrix(pimg[pp[0]:,:pp[1]], [1,3,5], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=(1<<nbit), symmetric=True) res11 = greycomatrix(pimg[pp[0]:,pp[1]:], [1,3,5], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=(1<<nbit), symmetric=True) dsc00 = np.sum(res00,3).astype(np.float) dsc01 = np.sum(res01,3).astype(np.float) dsc10 = np.sum(res10,3).astype(np.float) dsc11 = np.sum(res11,3).astype(np.float) idx2 = np.tri(dsc00.shape[0],dsc00.shape[1]) idx3 = np.zeros( (idx2.shape[0],idx2.shape[1],3) ) idx3[:,:,0]=idx2 idx3[:,:,1]=idx2 idx3[:,:,2]=idx2 dsc = np.concatenate( [dsc00[idx3>0], dsc01[idx3>0], dsc10[idx3>0], dsc11[idx3>0]] ) return dsc/np.sum(dsc)
def gclm_textures(regionmask: np.ndarray, intensity: np.ndarray, lengths=[1, 5, 20]): """ Compute GLCM features at given lengths Args: regionmask : binary background mask intensity : intensity image lengths : length scales """ # Contruct GCL matrix at given pixels lengths glcm = greycomatrix( img_as_ubyte((intensity * regionmask) / 255), distances=lengths, angles=[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], ) contrast = pd.DataFrame(np.mean(greycoprops(glcm, "contrast"), axis=1).tolist()).T contrast.columns = ["contrast_" + str(col) for col in lengths] dissimilarity = pd.DataFrame( np.mean(greycoprops(glcm, "dissimilarity"), axis=1).tolist() ).T dissimilarity.columns = ["dissimilarity_" + str(col) for col in lengths] homogeneity = pd.DataFrame( np.mean(greycoprops(glcm, "homogeneity"), axis=1).tolist() ).T homogeneity.columns = ["homogeneity_" + str(col) for col in lengths] ASM = pd.DataFrame(np.mean(greycoprops(glcm, "ASM"), axis=1).tolist()).T ASM.columns = ["asm_" + str(col) for col in lengths] energy = pd.DataFrame(np.mean(greycoprops(glcm, "energy"), axis=1).tolist()).T energy.columns = ["energy_" + str(col) for col in lengths] correlation = pd.DataFrame( np.mean(greycoprops(glcm, "correlation"), axis=1).tolist() ).T correlation.columns = ["correlation_" + str(col) for col in lengths] feat = pd.concat( [ contrast.reset_index(drop=True), dissimilarity.reset_index(drop=True), homogeneity.reset_index(drop=True), ASM.reset_index(drop=True), energy.reset_index(drop=True), correlation.reset_index(drop=True), ], axis=1, ) return feat
def testImage(image_list): global arr1 global flag arr1.clear() for index in range(len(image_list)): img = io.imread(image_list[index], as_grey=True) infile = cv2.imread(image_list[index]) infile = infile[:, :, 0] hues = (np.array(infile) / 255.) * 179 outimageHSV = np.array([[[b, 255, 255] for b in a] for a in hues]).astype(int) outimageHSV = np.uint8(outimageHSV) outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR) rgb = io.imread(image_list[index]) lab = color.rgb2lab(rgb) outimageBGR = lab for i in range(outimageBGR.shape[0]): for j in range(outimageBGR.shape[1]): sum = 0 for k in range(outimageBGR.shape[2]): sum = sum + outimageBGR[i][j][k] sum = sum / (3 * 255) if (i < img.shape[0] and j < img.shape[1]): img[i][j] = sum S = preprocessing.MinMaxScaler((0, 19)).fit_transform(img).astype(int) Grauwertmatrix = feature.greycomatrix( S, [1, 2, 3], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=20, symmetric=False, normed=True) arr1.append(feature.greycoprops(Grauwertmatrix, 'contrast')) arr1.append(feature.greycoprops(Grauwertmatrix, 'correlation')) arr1.append(feature.greycoprops(Grauwertmatrix, 'homogeneity')) arr1.append(feature.greycoprops(Grauwertmatrix, 'ASM')) arr1.append(feature.greycoprops(Grauwertmatrix, 'energy')) arr1.append(feature.greycoprops(Grauwertmatrix, 'dissimilarity')) arr1.append(Features.sumOfSquares(Grauwertmatrix)) arr1.append(Features.sumAverage(Grauwertmatrix)) arr1.append(Features.sumVariance(Grauwertmatrix)) arr1.append(Features.Entropy(Grauwertmatrix)) arr1.append(Features.sumEntropy(Grauwertmatrix)) arr1.append(Features.differenceVariance(Grauwertmatrix)) arr1.append(Features.differenceEntropy(Grauwertmatrix)) arr1.append(Features.informationMeasureOfCorelation1(Grauwertmatrix)) arr1.append(Features.informationMeasureOfCorelation2(Grauwertmatrix)) flag = 1
def get_texture_features_per_image(greyImage): g = greycomatrix(greyImage, [1, 2], [0, np.pi / 2]) contrast = greycoprops(g, 'contrast').ravel() dissimilarity = greycoprops(g, 'dissimilarity').ravel() homogeneity = greycoprops(g, 'homogeneity').ravel() energy = greycoprops(g, 'energy').ravel() correlation = greycoprops(g, 'correlation').ravel() return ','.join([str(val) for val in contrast]) + ',' + \ ','.join([str(val) for val in dissimilarity]) + ',' + \ ','.join([str(val) for val in homogeneity]) + ',' + \ ','.join([str(val) for val in energy]) + ',' + \ ','.join([str(val) for val in correlation])
def _greycoprops(imgpath, scale, prop): """Note that _imgprocess is not used; here we need gray integer img""" img = imread(imgpath) if scale == True: img = _scale(img) imgray = color.rgb2gray(img) imgray = img_as_ubyte(imgray) glcmat = greycomatrix(imgray, [1], [0], levels=256, symmetric=True, normed=True) return greycoprops(glcmat, prop)[0][0]
def algo2(image_name): rgb = cv2.imread(image_name) grayimage = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) im = clahe.apply(grayimage) Grauwertmatrix = feature.greycomatrix(im, distances=[1], angles=[0]) coprops = feature.greycoprops(Grauwertmatrix, 'energy') print(coprops[0][0])
def GLCM_FE(fileGLCM, image): glcm = greycomatrix(image, [1], [0], 256, symmetric=True, normed=True) xs = [] xs.append(greycoprops(glcm, 'dissimilarity')[0, 0]) xs.append(greycoprops(glcm, 'correlation')[0, 0]) xs.append(greycoprops(glcm, 'homogeneity')[0, 0]) xs.append(greycoprops(glcm, 'ASM')[0, 0]) xs.append(greycoprops(glcm, 'energy')[0, 0]) xs.append(greycoprops(glcm, 'correlation')[0, 0]) glcmElement = " ".join(str(x) for x in xs) glcmElement = glcmElement.replace(" ", ",") + '\n' fileGLCM.write(glcmElement)
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
def glcm(im): glcm = greycomatrix(im, [2, 8, 16], [0, np.pi / 2.0, np.pi * 3 / 4.0], 32, 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') return (cont, diss, h**o, eng, corr, ASM, glcm)
def CoOccuranceMatrix(imageSelected): cmmatrix = [] gray_image = imageSelected co_matrix = greycomatrix(gray_image, [1, 2, 4, 8], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=256) contrast = greycoprops(co_matrix, 'contrast').flatten() for i in range(16): cmmatrix.append(contrast[i]) return cmmatrix
def grayscale_comatrix(img_array): grayimg_array_8 = img_array glcm = feature.greycomatrix(grayimg_array_8, [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=256) feature_vals = [] featrue_params = ['contrast', 'dissimilarity', 'homogeneity', 'energy'] for param in featrue_params: feature_vals = np.append(feature_vals, feature.greycoprops(glcm, param)) normalized_vals = zscore(feature_vals) return normalized_vals
def GLCM(image, channel=3, bit_depth=8): if (channel == 3): GLCM_0 = greycomatrix(image[:, :, 0], [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=2**bit_depth) GLCM_1 = greycomatrix(image[:, :, 1], [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=2**bit_depth) GLCM_2 = greycomatrix(image[:, :, 2], [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=2**bit_depth) contrast_0 = greycoprops(GLCM_0, 'contrast').mean() contrast_1 = greycoprops(GLCM_1, 'contrast').mean() contrast_2 = greycoprops(GLCM_2, 'contrast').mean() dissim_0 = greycoprops(GLCM_0, 'dissimilarity').mean() dissim_1 = greycoprops(GLCM_1, 'dissimilarity').mean() dissim_2 = greycoprops(GLCM_2, 'dissimilarity').mean() correl_0 = greycoprops(GLCM_0, 'correlation').mean() correl_1 = greycoprops(GLCM_1, 'correlation').mean() correl_2 = greycoprops(GLCM_2, 'correlation').mean() homo_0 = greycoprops(GLCM_0, 'homogeneity').mean() homo_1 = greycoprops(GLCM_1, 'homogeneity').mean() homo_2 = greycoprops(GLCM_2, 'homogeneity').mean() return [ contrast_0, dissim_0, correl_0, homo_0, contrast_1, dissim_1, correl_1, homo_1, contrast_2, dissim_2, correl_2, homo_2 ] elif (channel == 1): GLCM_0 = greycomatrix(image, [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=2**bit_depth) contrast_0 = greycoprops(GLCM_0, 'contrast').mean() dissim_0 = greycoprops(GLCM_0, 'dissimilarity').mean() correl_0 = greycoprops(GLCM_0, 'correlation').mean() homo_0 = greycoprops(GLCM_0, 'homogeneity').mean() return [contrast_0, dissim_0, correl_0, homo_0] else: assert False, "ERROR: The function supports only 1 or 3-channel image formats."
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])
def GLCM_features(image_grayscale, texture_patches): #image - preprocessed image, pts_new - coordinates for patch texture, texture_patches - list of #print("patch", texture_patches[0]) # compute some GLCM properties each patch contrast = [] energy = [] homogeneity = [] dissimilarity = [] correlation = [] # for patch in texture_patches: glcm = greycomatrix(image_grayscale, [1], [0], 256, symmetric=True, normed=True) ##### ispravlajti parametre !!!!! # contrast.append(greycoprops(glcm, 'contrast')[0][0]) # energy.append(greycoprops(glcm, 'energy')[0][0]) # homogeneity.append(greycoprops(glcm, 'homogeneity')[0][0]) # dissimilarity.append(greycoprops(glcm, 'dissimilarity')[0, 0]) # correlation.append(greycoprops(glcm, 'correlation')[0][0]) # racunati feature samo za sliku (ne za patch) contrast=(greycoprops(glcm, 'contrast')[0][0]) energy=(greycoprops(glcm, 'energy')[0][0]) homogeneity=(greycoprops(glcm, 'homogeneity')[0][0]) dissimilarity=(greycoprops(glcm, 'dissimilarity')[0, 0]) correlation=(greycoprops(glcm, 'correlation')[0][0]) glcm_features = [contrast, energy, homogeneity, dissimilarity, correlation] print('contrast')#, contrast) print('energy')#, energy) print('homogeneity')#, homogeneity) print('dissimilarity')#, dissimilarity) print('correlation')#, correlation) # print(len(pts_new)) # print(len(texture_patches)) # print(len(contrast)) # print(len(energy)) # print(len(homogeneity)) # print(len(correlation)) return glcm_features #create the figure fig = plt.figure(figsize=(8, 8)) return fig
def glcm_properties(image): #recibe la imagen glcm = greycomatrix(image, distances=[1, 2, 3], angles=[0, np.pi / 4, np.pi / 2], symmetric=True, normed=True) Energia = greycoprops(glcm, 'energy') Corre = greycoprops(glcm, 'correlation') Contraste = greycoprops(glcm, 'contrast') #print("E",Energia) #print("H",Corre) #print("C",Contraste) return [Energia, Corre, Contraste]
def comatImg(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) d = 1 matrix = greycomatrix(gray, [d], [0], normed=True) props = np.zeros((6)) props[0] = greycoprops(matrix, 'contrast') props[1] = greycoprops(matrix, 'dissimilarity') props[2] = greycoprops(matrix, 'homogeneity') props[3] = greycoprops(matrix, 'energy') props[4] = greycoprops(matrix, 'correlation') props[5] = greycoprops(matrix, 'ASM') return props
def compute(self, image): glcm = feature.greycomatrix(image, self.distance, self.angle, 256, symmetric=True, normed=True) #Calculating and normalizing the histogram x = itemfreq(glcm.ravel()) hist = x[:, 1] / sum(x[:, 1]) return hist
def extract_texture(self, image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) glcm = greycomatrix(gray, [5], [0], 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') features = np.hstack((cont, diss, h**o, eng, corr, ASM)) features = np.vstack(features).squeeze() return (features) """
def grayscale_comatrix(img_array): # grayimg_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY) grayimg_array_8 = img_array // 8 glcm = feature.greycomatrix(grayimg_array_8, [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=32) feature_vals = [] featrue_params = ['contrast', 'dissimilarity', 'homogeneity', 'energy'] for param in featrue_params: feature_vals = np.append(feature_vals, feature.greycoprops(glcm, param)) normalized_vals = zscore(feature_vals) return normalized_vals
def energy_4x4(): image = np.array([[0, 0, 1, 1],\ [0, 0, 1, 1],\ [0, 2, 2, 2],\ [2, 2, 3, 3]],\ dtype=np.uint8) ray = [1] theta = [np.pi / 2.] levels = 4 result = greycomatrix(image, ray, theta, levels, symmetric=True) print pow(greycoprops(result, 'energy'), 2)
def img_2_glcm(img): #用rgb gray = color.rgb2gray(img) image = img_as_ubyte(gray) inds = np.digitize(image, bins) max_value = inds.max()+1 matrix_coocurrence = greycomatrix(inds, [1,2,4], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=max_value, normed=False, symmetric=False) # print(matrix_coocurrence) # print(matrix_coocurrence.shape) return matrix_coocurrence
def glcm_features_whole(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] temp_features = [dissimilarity, correlation,contrast,homogeneity,ASM,energy] return temp_features
def process(self): gray = cv2.cvtColor(self.image, cv2.COLOR_RGB2GRAY) bins = np.array([ 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255 ]) #16-bit inds = np.digitize(gray, bins) max_value = self.image.max() self.matrix_coocurrence = greycomatrix( inds, [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], levels=max_value + 1, normed=False, symmetric=False)
def _calc_features(_img, _feature_names): eprint("Calculating GLCM [ image.shape = {shape} ] ... ".format( shape=_img.shape)) _glcm = greycomatrix(_img, self.distances, self.degrees) return { _feature_name: {(_dist, _deg): greycoprops(_glcm, _feature_name)[_dist_idx][_deg_idx] for (_dist_idx, _dist), (_deg_idx, _deg) in keys_and_indices} for _feature_name in _feature_names }
def get_glcm(self, distance=(2, 8, 16), angle=(0, np.pi/4, np.pi/2, np.pi*3/4), prop_name=('contrast', 'dissimilarity', 'homogeneity', 'energy', 'correlation', 'ASM')): glcm_features = np.zeros(1) band_count = self.img_array_uint8.shape[2] for band_index in range(0, band_count): cur_glcm = greycomatrix(self.img_array_uint8[:, :, band_index], distance, angle, 256, symmetric=True, normed=True) for prop in prop_name: tmp_value = greycoprops(cur_glcm, prop) tmp_value = tmp_value.reshape(-1) glcm_features = np.concatenate((glcm_features, tmp_value), axis=0) glcm_features = np.delete(glcm_features, 0, axis=0) return glcm_features
def test_image_data_types(self): for dtype in [ np.uint16, np.uint32, np.uint64, np.int16, np.int32, np.int64 ]: img = self.image.astype(dtype) result = greycomatrix(img, [1], [np.pi / 2], 4, symmetric=True) assert result.shape == (4, 4, 1, 1) expected = np.array( [[6, 0, 2, 0], [0, 4, 2, 0], [2, 2, 2, 2], [0, 0, 2, 0]], dtype=np.uint32) np.testing.assert_array_equal(result[:, :, 0, 0], expected) return
def extract_texture(x): feature_name = lambda s, x, y: f"{s}_{str(x).zfill(2)}_{str(y)}" text = {} props = ['dissimilarity', 'contrast', 'homogeneity', 'energy', 'correlation'] angles = [0, np.pi/4, np.pi/2, np.pi*3/4] #4 angles glcm = greycomatrix(x , [1], angles) for f in props: for i in range(4): text[feature_name('text', f, i)] = greycoprops(glcm, f)[0][i] return pd.Series(text)
def extract(self, x): gray_image = cv2.cvtColor((x*255.).astype(np.uint8), cv2.COLOR_RGB2GRAY) glcm = greycomatrix(gray_image, [5], [0], 256, symmetric=True, normed=True) dissimilarity = greycoprops(glcm, 'dissimilarity')[0, 0] correlation = greycoprops(glcm, 'correlation')[0, 0] energy = greycoprops(glcm, 'energy')[0, 0] correlation = greycoprops(glcm, 'correlation')[0, 0] homogeneity = greycoprops(glcm, 'homogeneity')[0, 0] ASM = greycoprops(glcm, 'ASM')[0, 0] # normalize the histogram hist = np.array([dissimilarity,correlation,energy,homogeneity,ASM]).astype('float') hist /= (hist.sum() + 1e-7) return hist
def get_features(path): img = cv2.imread(path) img = imutils.resize(img, width=500) image = 255 * img image = numpy.where((image > 80) & (image < 160), 200, image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) glcm = greycomatrix(gray, [6], [0, numpy.pi / 4, numpy.pi / 2, 3 * numpy.pi / 4], 256, True, True) con = greycoprops(glcm, 'contrast')[0, 0] dis = greycoprops(glcm, 'dissimilarity')[0, 0] hom = greycoprops(glcm, 'homogeneity')[0, 0] cor = greycoprops(glcm, 'correlation')[0, 0] return con, dis, hom, cor
def gclm(img, position, angle, kernel=32,levels=256): import math patch = np.zeros((kernel,kernel)).astype('uint16') ux = int(max(0, int(round(position[1])) - kernel/2)) uy = int(max(0, int(round(position[0])) - kernel/2)) lx = int(min(img.shape[0], int(round(position[1])) + kernel/2)) ly = int(min(img.shape[1], int(round(position[0])) + kernel/2)) patch[:lx-ux,:ly-uy] = toGray(img)[ux:lx,uy:ly] glcm = greycomatrix(patch, [1], [math.radians(angle)], levels, symmetric=True, normed=False) summary = np.sum(glcm[:, :, 0, 0], axis=1) summary = np.insert(summary, 0, greycoprops(glcm, 'correlation')[0, 0]*100000.0) summary = np.insert(summary, 0, greycoprops(glcm, 'dissimilarity')[0, 0]) return summary
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 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