def __init__(self, img): self.img = img#threadsHolding(img) #self.pixels = pixels print("Extracting LBP...") self.lbpR1P8 = normalize(np.float32(lbp.lbp(self.img, 1, 8, ignore_zeros=False))) self.lbpR2P16 = normalize(np.float32(lbp.lbp(self.img, 2, 16, ignore_zeros=False))) self.lbpR3P16 = normalize(np.float32(lbp.lbp(self.img, 3, 16, ignore_zeros=False))) #self.lbpR3P24 = normalize(np.float32(lbp.lbp(self.img, 3, 24, ignore_zeros=False))) self.lbpR1P8_R2P16 = np.float32(np.concatenate([self.lbpR1P8, self.lbpR2P16])) self.lbpR1P8_R3P16 = np.float32(np.concatenate([self.lbpR1P8, self.lbpR3P16])) self.lbpR2P16_R3P16 = np.float32(np.concatenate([self.lbpR2P16, self.lbpR3P16])) #self.lbpR1P8pic = np.float32(lbp.lbp_transform(self.img, 1, 8, ignore_zeros=False)) #self.lbpR2P16pic = np.float32(lbp.lbp_transform(self.img, 2, 16, ignore_zeros=False)) self.lbpR3P16pic = np.float32(lbp.lbp_transform(self.img, 3, 16, ignore_zeros=False)) #self.lbpR3P24pic = np.float32(lbp.lbp_transform(self.img, 3, 24, ignore_zeros=False)) '''
for imagename in image_targets: image_counter+=1 filename = args.trainingSetPath + imagename print 'Processing image: ', image_counter, filename # Abro la imagen en escala de grises image = mahotas.imread(filename, as_grey=True) if (args.featuresGray != ""): # Extraer histograma de grises gray_hist, bins = np.histogram(image.flatten(), 256, [0, 256]) gray_features[imagename] = gray_hist # if (args.featuresLbp != ""): # Extraer lbp (sobre la misma imagen del anterior, en escala de grises) radius = 3 points = 4 * radius # Number of points to be considered as neighbourers lbp_hist = lbp.lbp(image, radius, points, ignore_zeros=False) lbp_features[imagename] = lbp_hist # if (args.featuresSurf != ""): # Extraer surf (sobre la misma imagen del anterior, en escala de grises) surf_features = surf.surf(image)[:, 5:] surf_all_hist[imagename] = surf_features # # Abro la imagen en colores image = mahotas.imread(filename, as_grey=False) # if (args.featuresColor != ""): # Extraer histograma de colores color_hist, bins = np.histogram(image.flatten(), 256, [0, 256]) color_features[imagename] = color_hist # if (args.featuresHara != ""): # Extraer histograma haraclick (sobre la misma imagen del anterior, en colores) hara_hist = mahotas.features.haralick(image).mean(0)
def test_shape(): A = np.arange(32*32).reshape((32,32)) B = np.arange(64*64).reshape((64,64)) features0 = lbp(A, 3, 12) features1 = lbp(B, 3, 12) assert features0.shape == features1.shape
def test_histogram_large(): A = np.arange(32*32).reshape((32,32)) for r in (2,3,4,5): assert lbp(A,r,12).sum() == A.size
def test_nonzero(): A = np.arange(32*32).reshape((32,32)) features = lbp(A, 3, 12) features_ignore_zeros = lbp(A * (A> 256), 3, 12, ignore_zeros=True) assert features.sum() > 0 assert not np.all(features == features_ignore_zeros)
def computefeatures(img, featsets, progress=None, preprocessing=None, **kwargs): """ features = computefeatures(img,featsets,progress=None,**kwargs) Compute features defined by featsets on image img. featsets can be either a list of feature groups. Feature groups: -------------- + 'har': 13 Haralick features [in matslic] + 'har3d': 26 Haralick features (actually this works in 2D as well) + 'skl': Skeleton features [in matslic] (syn: 'skel') + 'img': Image features [in matslic] + 'hul': Hull features [in matslic] (syn: 'hull') + 'edg': Edge features [in matslic] (syn: 'edge') + 'zer': Zernike moments [in matslic] + 'tas' : Threshold Adjacency Statistics + 'pftas' : Parameter-free Threshold Adjacency Statistics Feature set names: + 'SLF7dna' + 'mcell': field level features + 'field+': all field level features. The exact exact number of features computed is liable to change (increase) in newer versions img can be a list of images. In this case, a two-dimensional feature vector will be returned, where f[i,j] is the j-th feature of the i-th image. Also, in this case, imgs will be unload after feature calculation. Parameters ---------- * *progress*: if progress is not None, then it should be an integer. Every *progress* images, an output message will be printed. * *preprocessing*: Whether to do preprocessing (default: True). If False and img.channeldata[procprotein|procdna] are empty, they are filled in using img.channeldata[protein|dna] respectively. * *options*: currently passed through to pyslic.preprocessimage """ if type(featsets) == str: featsets = _featsfor(featsets) if type(img) == list: features = [] for i, im in enumerate(img): f = computefeatures(im, featsets, progress=None, **kwargs) features.append(f) im.unload() if progress is not None and (i % progress) == 0: print "Processed %s images..." % i return numpy.array(features) regions = img.regions if regions is not None and regions.max() > 1 and "region" not in kwargs: precomputestats(img) return numpy.array( [ computefeatures(img, featsets, progress=progress, region=r, **kwargs) for r in xrange(1, regions.max() + 1) ] ) scale = img.scale if scale is None: scale = _Default_Scale is_surf = len(featsets) == 1 and featsets[0] in ("surf", "surf-ref", "surfp") if preprocessing is None: preprocessing = not is_surf if preprocessing: preprocessimage(img, kwargs.get("region"), options=kwargs.get("options", {})) else: if "procprotein" not in img.channeldata: img.channeldata["procprotein"] = img.get("protein") img.channeldata["resprotein"] = 0 * img.get("protein") if ("dna" in img.channeldata) and ("procdna" not in img.channeldata): img.channeldata["procdna"] = img.get("dna") features = numpy.array([]) protein = img.get("protein") procprotein = img.get("procprotein") resprotein = img.get("resprotein") dna = img.channeldata.get("dna") procdna = img.channeldata.get("procdna") if procprotein.size < _Min_image_size: if is_surf: return np.array([]) if featsets == _featsfor("SLF7dna"): return np.array([np.nan for i in xrange(90)]) if featsets == _featsfor("field-dna+"): return np.array([np.nan for i in xrange(173)]) raise ValueError lbppat = re.compile(r"lbp\(([0-9]+), ?([0-9]+)\)") for F in featsets: if F in ["edg", "edge"]: feats = edgefeatures(procprotein) elif F == "raw-har": feats = haralickfeatures(procprotein).mean(0) elif F[:3] == "har": img = procprotein har_scale = kwargs.get("haralick.scale", _Default_Haralick_Scale) if F == "har" and scale != har_scale: img = img.copy() img = ndimage.zoom(img, scale / _Default_Haralick_Scale) if len(F) > 3: rate = int(F[3]) if rate != 1: C = np.ones((rate, rate)) img = np.array(img, np.uint16) img = ndimage.convolve(img, C) img = img[::rate, ::rate] if not img.size: feats = np.zeros(13) else: bins = kwargs.get("haralick.bins", _Default_Haralick_Bins) if bins != 256: min = img.min() max = img.max() ptp = max - min if ptp: img = np.array((img - min).astype(float) * bins / ptp, np.uint8) feats = haralickfeatures(img) feats = feats.mean(0) elif F in ["hul", "hull"]: feats = hullfeatures(procprotein) elif F == "hullsize": feats = hullsizefeatures(procprotein) elif F == "hullsizedna": feats = hullsizefeatures(procdna) elif F == "img": feats = imgfeaturesdna(procprotein, procdna) elif F in ("obj-field", "obj-field-dna"): feats = imgfeaturesdna(procprotein, procdna, isfield=True) elif F == "mor": feats = morphologicalfeatures(procprotein) elif F == "nof": feats = noffeatures(procprotein, resprotein) elif F in ["skl", "skel"]: feats = imgskelfeatures(procprotein) elif F == "zer": feats = zernike(procprotein, 12, 34.5, scale) elif F == "tas": feats = tas(protein) elif F == "pftas": feats = pftas(procprotein) elif F == "overlap": feats = overlapfeatures(protein, dna, procprotein, procdna) elif lbppat.match(F): radius, points = lbppat.match(F).groups() feats = lbp(protein, int(radius), int(points)) elif F in ("surf", "surf-ref", "surfp"): if F == "surfp": from warnings import warn warn("surfp is deprecated. Use surf-ref", DeprecationWarning) if len(featsets) > 1: raise ValueError("pyslic.features.computefeatures: surf-ref must be computed on its own") if F == "surf": dna = None return surf_ref(protein, dna) else: raise Exception("Unknown feature set: %s" % F) features = numpy.r_[features, feats] return features
def computefeatures(img, featsets, progress=None, preprocessing=True, **kwargs): ''' features = computefeatures(img,featsets,progress=None,**kwargs) Compute features defined by featsets on image img. featsets can be either a list of feature groups. Feature groups: -------------- + 'har': 13 Haralick features [in matslic] + 'har3d': 26 Haralick features (actually this works in 2D as well) + 'skl': Skeleton features [in matslic] (syn: 'skel') + 'img': Image features [in matslic] + 'hul': Hull features [in matslic] (syn: 'hull') + 'edg': Edge features [in matslic] (syn: 'edge') + 'zer': Zernike moments [in matslic] + 'tas' : Threshold Adjacency Statistics + 'pftas' : Parameter-free Threshold Adjacency Statistics Feature set names: + 'SLF7dna' + 'mcell': field level features + 'field+': all field level features. The exact exact number of features computed is liable to change (increase) in newer versions img can be a list of images. In this case, a two-dimensional feature vector will be returned, where f[i,j] is the j-th feature of the i-th image. Also, in this case, imgs will be unload after feature calculation. Parameters ---------- * *progress*: if progress is not None, then it should be an integer. Every *progress* images, an output message will be printed. * *preprocessing*: Whether to do preprocessing (default: True). If False and img.channeldata[procprotein|procdna] are empty, they are filled in using img.channeldata[protein|dna] respectively. * *options*: currently passed through to pyslic.preprocessimage ''' if type(featsets) == str: featsets = _featsfor(featsets) if type(img) == list: features=[] for i,im in enumerate(img): f = computefeatures(im,featsets,progress=None,**kwargs) features.append(f) im.unload() if progress is not None and (i % progress) == 0: print 'Processed %s images...' % i return numpy.array(features) regions = img.regions if regions is not None and regions.max() > 1 and 'region' not in kwargs: precomputestats(img) return numpy.array([ computefeatures(img, featsets, progress=progress, region=r, **kwargs) for r in xrange(1,regions.max()+1)]) scale = img.scale if scale is None: scale = _Default_Scale if preprocessing: preprocessimage(img, kwargs.get('region',1), options=kwargs.get('options',{})) else: if not img.channeldata['procprotein']: img.channeldata['procprotein'] = img.get('protein') img.channeldata['resprotein'] = 0*img.get('protein') if not img.channeldata['procdna']: img.channeldata['procdna'] = img.get('dna') features = numpy.array([]) protein = img.get('protein') procprotein = img.get('procprotein') resprotein = img.get('resprotein') dna = img.channeldata.get('dna') procdna = img.channeldata.get('procdna') if procprotein.size < _Min_image_size: return np.array([np.nan for i in xrange(90)]) lbppat = re.compile(r'lbp\(([0-9]+), ?([0-9]+)\)') for F in featsets: if F in ['edg','edge']: feats = edgefeatures(procprotein) elif F == 'raw-har': feats = haralickfeatures(procprotein).mean(0) elif F[:3] == 'har': img = procprotein har_scale = kwargs.get('haralick.scale',_Default_Haralick_Scale) if F == 'har' and scale != har_scale: img = img.copy() img = ndimage.zoom(img, scale/_Default_Haralick_Scale) if len(F) > 3: rate = int(F[3]) if rate != 1: C = np.ones((rate,rate)) img = np.array(img,np.uint16) img = ndimage.convolve(img,C) img = img[::rate,::rate] if not img.size: feats = np.zeros(13) else: bins = kwargs.get('haralick.bins',_Default_Haralick_Bins) if bins != 256: min = img.min() max = img.max() ptp = max - min if ptp: img = np.array((img-min).astype(float) * bins/ptp, np.uint8) feats = haralickfeatures(img) feats = feats.mean(0) elif F == 'har3d': feats = haralickfeatures(procprotein) feats = numpy.r_[feats.mean(0),feats.ptp(0)] elif F in ['hul', 'hull']: feats = hullfeatures(procprotein) elif F == 'hullsize': feats = hullsizefeatures(procprotein) elif F == 'hullsizedna': feats = hullsizefeatures(procdna) elif F == 'img': feats = imgfeaturesdna(procprotein, procdna) elif F in ('obj-field', 'obj-field-dna'): feats = imgfeaturesdna(procprotein, procdna, isfield=True) elif F == 'mor': feats = morphologicalfeatures(procprotein) elif F == 'nof': feats = noffeatures(procprotein,resprotein) elif F in ['skl', 'skel']: feats = imgskelfeatures(procprotein) elif F == 'zer': feats = zernike(procprotein,12,34.5,scale) elif F == 'tas': feats = tas(protein) elif F == 'pftas': feats = pftas(procprotein) elif F == 'overlap': feats = overlapfeatures(protein, dna, procprotein, procdna) elif lbppat.match(F): radius,points = lbppat.match(F).groups() feats = lbp(protein, int(radius), int(points)) else: raise Exception('Unknown feature set: %s' % F) features = numpy.r_[features,feats] return features