def __ReadInputs__(image, phases, seedMethod, seedParam): if isinstance(image, basestring): imageFileName = image assert (os.path.isfile(imageFileName)) image = utilities.ReadTiff(imageFileName) else: assert (isinstance(image, np.ndarray)) assert (image.min() >= 0) memoryType = utilities.BestMemoryType(image.max()) image = image.astype(memoryType) assert (isinstance(phases, dict)) assert (isinstance(int(seedParam), int)) assert (seedMethod == "hMaxima" or seedMethod == "localMax") return image, phases, seedMethod, seedParam
def LabelContacts(mydict, imageSize): mykeys = mydict.keys() nLink = len(mykeys) memoryType = utilities.BestMemoryType(nLink) labeledLinks = np.zeros(imageSize, dtype=memoryType) for iLink in range(nLink): ind = mydict[mykeys[iLink]] X, Y, Z = np.unravel_index(ind, imageSize) labeledLinks[X, Y, Z] = iLink + 1 return labeledLinks
def TestVoxelize(raydirection): #mesh=BasicShapes.CreateCylinder((0,0,0),(1,0,0),15,100) mesh=BasicShapes.CreateSpline() voxelNumbers=(100,100,100) bounds=mesh.GetBounds() gridX=np.linspace(bounds[0],bounds[1],voxelNumbers[0]) gridY=np.linspace(bounds[3],bounds[2],voxelNumbers[1]) gridZ=np.linspace(bounds[5],bounds[4],voxelNumbers[2]) image=Voxelization.Voxelize(mesh,gridX,gridY,gridZ,raydirection=raydirection) Utilities.WriteTiff(100*(image.astype(np.uint8)),'TestVoxelizePython.tif') return image
def TestVirtualVoronoi(): voxelNumbers=(200,200,200) imageBounds = (0.0,1.0,0.0,1.0,0.0,1.0) nPoint=200 fiberRadius=0.05 anisotropy=3 randomSeed=0 image=virtMatGen.CreateVirtualVoronoiFoam(voxelNumbers=voxelNumbers,imageBounds=imageBounds, nPoint=nPoint,fiberRadius=fiberRadius, anisotropy=anisotropy,randomSeed=randomSeed) Utilities.WriteTiff(255*(image.astype(np.uint8)),'TestVoronoi.tif') return image
def PoresSegmentation(myImg, phases={'void': False}, structuringElement=np.ones((3, 3, 3)), seedMethod='hMaxima', seedParam=4, distanceType='ITKDanielson'): #Phases=dict, phases['myphase']=codeForMyPhaseInImage pores = np.zeros(myImg.shape, dtype=np.uint8) watershedLines = np.zeros(myImg.shape, dtype=np.bool) if distanceType == 'euclidean' or distanceType == 'ITKDanielson': memoryType = np.float16 elif distanceType == 'chamfer': memoryType = np.int8 distanceMap = np.zeros(myImg.shape, dtype=memoryType) labelShift = [0] for phaseName in phases.keys(): phaseCode = phases[phaseName] phaseImage = (myImg == np.uint8(phaseCode)).astype(np.bool) poresPhase, watershedLinesPhase, distanceMapPhase = PoresWatershedSegmentationOnePhase( phaseImage, structuringElement=structuringElement, seedMethod=seedMethod, seedParam=seedParam, distanceType=distanceType) phaseImage = phaseImage.astype(np.bool) memoryType = utilities.BestMemoryType(poresPhase.max() + pores.max()) pores = pores.astype(memoryType) pores[phaseImage] = ( poresPhase[phaseImage]).astype(memoryType) + labelShift[-1] * ( poresPhase[phaseImage] > 0).astype(memoryType) watershedLines[phaseImage] = watershedLinesPhase[phaseImage] distanceMap[phaseImage] = distanceMapPhase[phaseImage] del phaseImage, poresPhase, watershedLinesPhase, distanceMapPhase labelShift.append(pores.max()) #phaseBoundaries = SobelEdgeDetection(myImg) phaseBoundaries = imageAnalysis.FeatureExtraction.SobelEdgeDetection(myImg) watershedLines = np.logical_or(watershedLines, phaseBoundaries) porePhase = np.zeros(pores.max(), dtype=np.uint8) for i in range(len(labelShift) - 1): porePhase[np.arange(labelShift[i], labelShift[i + 1])] = int(phases[phases.keys()[i]]) return pores, watershedLines, distanceMap, porePhase
def TestVirtualGDL(): voxelNumbers=(500,500,200) fiberContent=0.1 fiberRadius=9 fiberLength=500 binderContent=0.1 anisotropy=5 randomSeed=0 image = virtMatGen.CreateVirtualGDL(voxelNumbers=voxelNumbers, fiberContent=fiberContent,fiberRadius=fiberRadius,fiberLength=fiberLength, binderContent=binderContent, anisotropy=anisotropy,randomSeed=randomSeed) Utilities.WriteTiff(100*(image.astype(np.uint8)),'TestBigGDL.tif') return image
def TestVirtualCCL(): voxelNumbers=(200,200,200) carbonGrainRadius=4 nCarbonGrain=5000 voidRadius=50 nVoid=200 nafionThickness=2 nafionCoveragePercentage=30 randomSeed=1 image = virtMatGen.CreateVirtualCatalystLayer(voxelNumbers=voxelNumbers, carbonGrainRadius=carbonGrainRadius,nCarbonGrain=nCarbonGrain, voidRadius=voidRadius,nVoid=nVoid, nafionThickness=nafionThickness,nafionCoveragePercentage=nafionCoveragePercentage, randomSeed=randomSeed) Utilities.WriteTiff(100*(image.astype(np.uint8)),'TestCCL.tif') return image
def MedianFilter(image,radius = (3,3,3)): """MedianFilter : see SimpleITK.Median :param image : numpy image :param radius: size of neighborhood used to take median :return: numpy image after filtering :Example: import VirtualMaterials as vmat filteredImage = vmat.ImageAnalysis.Filters.MedianFilter(image,radius = (3,3,3)) """ assert(image.min()>=0) memoryType = utils.BestMemoryType(image.max()) itkimage = sitk.GetImageFromArray(image.astype(memoryType)) itkimage = sitk.Median(itkimage,radius = radius) image=sitk.GetArrayFromImage(itkimage).astype(memoryType) return image
def OtsuThreshold(image, insideValue = 100, outsideValue = 0, numberOfHistogramBins = 128, maskOutput = True, maskValue = 255 ): """OtsuThreshold : see SimpleITK.OtsuThreshold :param image : numpy image :param insideValue: :param outsideValue: :param numberOfHistogramBins: :param maskOutput: :param maskValue: :return: numpy image after filtering :Example: import VirtualMaterials as vmat filteredImage = vmat.ImageAnalysis.Filters.OtsuThreshold(image, insideValue = 100, outsideValue = 0, numberOfHistogramBins = 128, maskOutput = True, maskValue = 255 ) """ assert(image.min()>=0) memoryType = memoryType = utils.BestMemoryType(image.max()) itkimage = sitk.GetImageFromArray(image.astype(memoryType)) #OTSU Threshold FILTER itkimage= sitk.OtsuThreshold( itkimage, np.uint8(insideValue), np.uint8(outsideValue), np.uint32(numberOfHistogramBins), bool(maskOutput), np.uint8(maskValue) ) image=sitk.GetArrayFromImage(itkimage).astype(memoryType) return image
def Threshold(image, lower=0.0,upper=1.0,outsideValue=0.0): """Threshold : see SimpleITK.Threshold :param image : numpy image :param lower: :param upper: :param outsideValue: :return: numpy image after filtering :Example: import VirtualMaterials as vmat filteredImage = vmat.ImageAnalysis.Filters.Threshold(image, lower=0.0,upper=1.0,outsideValue=0.0) """ assert(image.min()>=0) memoryType = utils.BestMemoryType(image.max()) itkimage = sitk.GetImageFromArray(image.astype(memoryType)) itkimage = sitk.Threshold(itkimage, lower=lower, upper=upper, outsideValue=outsideValue) image=sitk.GetArrayFromImage(itkimage).astype(memoryType) return image
def TestInterfaceGDLMPL(): interface=virtMatGen.CreateVirtualInterfaceGDLMPL(penetrationLength=30) Utilities.WriteTiff(50*(interface.astype(np.uint8)),'TestInterfaceGDLMPL_penetration30.tif') return interface
def PoresWatershedSegmentationOnePhase(phaseImage, structuringElement=np.ones((3, 3, 3)), distanceType='ITKDanielson', watershedAlgo='ITK', seedMethod='hMaxima', seedParam=4): #Calcul de la carte de distance distanceMap if distanceType == 'euclidean': memoryType = np.float16 distanceMap = ndimage.distance_transform_edt(phaseImage).astype( memoryType) elif distanceType == 'chamfer': memoryType = np.int8 distanceMap = ndimage.distance_transform_cdt( phaseImage, metric='chessboard').astype(memoryType) elif distanceType == 'ITKDanielson': memoryType = np.float16 itkimage = sitk.GetImageFromArray( np.logical_not(phaseImage).astype(np.uint8)) itkdistanceMap = sitk.DanielssonDistanceMap(itkimage) del itkimage distanceMap = sitk.GetArrayFromImage(itkdistanceMap).astype(memoryType) del itkdistanceMap #Choix des marqueurs pour la segmentation (centres des pores) : H-maxima : #maxima de la carte de distance dont les pics sont étêtés d'une hauteur h. Utilise #une recontruction morphologique pour construire la carte de distance étêtée. hMaximaLib = 'skimage' if seedMethod == 'localMax': seedParam = int(seedParam) local_maxi = feature.peak_local_max(distanceMap.astype(np.float), min_distance=seedParam, indices=False) elif seedMethod == 'hMaxima' and hMaximaLib == 'skimage' and seedParam > 0: hContrast = np.asarray(seedParam).astype(memoryType) reconstructed = morphology.reconstruction( distanceMap - hContrast, distanceMap).astype(memoryType) local_maxi = (distanceMap - reconstructed).astype(np.bool) del reconstructed elif seedMethod == 'hMaxima' and hMaximaLib == 'ITK' and seedParam > 0: hContrast = np.asarray(seedParam).astype(memoryType) itkSeedimage = sitk.GetImageFromArray( (distanceMap - hContrast).astype(np.float32)) itkMarkerImage = sitk.GetImageFromArray(distanceMap.astype(np.float32)) itkReconstructed = sitk.ReconstructionByDilation( itkSeedimage, itkMarkerImage) del itkMarkerImage, itkSeedimage reconstructed = sitk.GetArrayFromImage(itkReconstructed).astype( memoryType) del itkReconstructed local_maxi = ((distanceMap - reconstructed) > hContrast / 10).astype( np.bool) del reconstructed markers = ndimage.measurements.label(local_maxi, structure=structuringElement)[0] del local_maxi #Calcul des lignes de partage de niveau if watershedAlgo == 'Mahotas': _, watershedLines = mahotas.cwatershed( (distanceMap.max() - distanceMap).astype(np.int8), markers, Bc=structuringElement, return_lines=True) elif watershedAlgo == 'ITK': itkMarkers = sitk.GetImageFromArray(markers) itkDistance = sitk.GetImageFromArray(distanceMap.astype(np.float)) itkDistance = sitk.InvertIntensity(itkDistance) wsITK = sitk.MorphologicalWatershedFromMarkers(itkDistance, itkMarkers, markWatershedLine=True, fullyConnected=True) del itkMarkers, itkDistance # mask = itk.MaskImageFilter.IUC2IUC2IUC2.New(ws, fill) # overlay = itk.LabelOverlayImageFilter.IUC2IUC2IRGBUC2.New(reader, # mask, # UseBackground=True) ws = sitk.GetArrayFromImage(wsITK).astype(np.uint8) del wsITK watershedLines = (ws == 0).astype(np.bool) watershedLines[np.logical_not(phaseImage)] = False del markers #Labeler des pores séparés par les lignes de partage de niveau pores = ndimage.measurements.label(np.logical_and( phaseImage, np.logical_not(watershedLines)), structure=structuringElement)[0] pores[np.logical_not(phaseImage)] = 0 memoryType = utilities.BestMemoryType(pores.max()) pores = pores.astype(memoryType) return pores, watershedLines, distanceMap