def nearestNode(self, point): where = self.properTile(point) count = 0 # No. of tile-bands containing nodes iter = 1 # No. of tile-bands having been looked at nodes = self[where][:] while count < 2: # Initial check if iter==1: if nodes: count += 1 # Additional band of tiles addition = self.nextBand( ll=primitives.iPoint(where.x-iter, where.y-iter), ur=primitives.iPoint(where.x+iter, where.y+iter)) if addition: nodes += addition count += 1 else: if count==1: break # No need to look for another band # Ready for the next round iter += 1 # Find the nearest node among collected nodes nearest = nodes[0] mindist = (nearest.position() - point)**2 for node in nodes[1:]: dd = (node.position() - point)**2 if dd < mindist: mindist = dd nearest = node return nearest
def nearestNode(self, point): where = self.properTile(point) count = 0 # No. of tile-bands containing nodes iter = 1 # No. of tile-bands having been looked at nodes = self[where][:] while count < 2: # Initial check if iter == 1: if nodes: count += 1 # Additional band of tiles addition = self.nextBand( ll=primitives.iPoint(where.x - iter, where.y - iter), ur=primitives.iPoint(where.x + iter, where.y + iter)) if addition: nodes += addition count += 1 else: if count == 1: break # No need to look for another band # Ready for the next round iter += 1 # Find the nearest node among collected nodes nearest = nodes[0] mindist = (nearest.position() - point)**2 for node in nodes[1:]: dd = (node.position() - point)**2 if dd < mindist: mindist = dd nearest = node return nearest
def __init__(self, array): prog = progress.getProgress("CategoryMap", progress.DEFINITE) n = 0 # array is a list of lists of Ints, which are pixel categories self.pxls = {} # list of pixels, keyed by category # TODO OPT: use iterator? for j in range(len(array)): sublist = array[j] for i in range(len(sublist)): if config.dimension() == 2: where = primitives.iPoint(i, j) category = sublist[i] try: self.pxls[category].append(where) except KeyError: self.pxls[category] = [where] elif config.dimension() == 3: subsublist = sublist[i] total = len(array) * len(sublist) * len(subsublist) for k in range(len(subsublist)): where = primitives.iPoint(i, j, k) category = subsublist[k] try: self.pxls[category].append(where) except KeyError: self.pxls[category] = [where] prog.setMessage("Got category for %d/%d voxels" % (n, total)) prog.setFraction(float(n) / total) n = n + 1 prog.finish()
def queryPixel(self, menuitem, x, y, z=0): # menu callback self.timestamp.increment() if config.dimension() == 2: self.point = primitives.iPoint(x, y) elif config.dimension() == 3: self.point = primitives.iPoint(x, y, z) switchboard.notify(self) # caught by GUI toolbox switchboard.notify('redraw')
def coords(self): if config.dimension() == 2: for j in range(self._isize[1]): for i in range(self._isize[0]): yield primitives.iPoint(i, j) if config.dimension() == 3: for k in range(self._isize[2]): for j in range(self._isize[1]): for i in range(self._isize[0]): yield primitives.iPoint(i, j, k)
def pixelFromPoint(self, where): xx = where.x / self._delta[0] if xx == 1.0 * self._isize[0]: xx = self._isize[0] - 1 yy = where.y / self._delta[1] if yy == 1.0 * self._isize[1]: yy = self._isize[1] - 1 if config.dimension() == 2: return primitives.iPoint(xx, yy) elif config.dimension() == 3: zz = where.z / self._delta[2] if zz == 1.0 * self._isize[2]: zz = self._isize[2] - 1 return primitives.iPoint(xx, yy, zz)
def pixelFromPoint(self, where): xx=where.x/self._delta[0] if xx==1.0*self._isize[0]: xx=self._isize[0]-1 yy=where.y/self._delta[1] if yy==1.0*self._isize[1]: yy=self._isize[1]-1 if config.dimension() == 2: return primitives.iPoint(xx,yy) elif config.dimension() == 3: zz=where.z/self._delta[2] if zz==1.0*self._isize[2]: zz=self._isize[2]-1 return primitives.iPoint(xx,yy,zz)
def read(self, filename): hklfile = file(filename, "r") ## TODO OPT: Use lineiter = iter(hklfile) instead of iter(lines). ## Then it's not necessary to create an array of lines. lines = hklfile.readlines() lineiter = iter(lines) line = lineiter.next() while not line.startswith('XCells'): line = lineiter.next() xcells = string.atoi(string.split(line)[1]) line = lineiter.next() ycells = string.atoi(string.split(line)[1]) line = lineiter.next() xstep = string.atof(string.split(line)[1]) line = lineiter.next() ystep = string.atof(string.split(line)[1]) line = lineiter.next() od = orientmapdata.OrientMap( primitives.iPoint(xcells, ycells), primitives.Point(xcells * xstep, ycells * ystep)) while not string.split(line)[0] == 'Phase': line = lineiter.next() prog = progress.getProgress(os.path.basename(filename), progress.DEFINITE) try: count = 0 npts = xcells * ycells for line in lineiter: vals = string.split(line) phase = vals[0] x = string.atof(vals[1]) y = string.atof(vals[2]) angles = map(string.atof, vals[5:8]) mad = string.atof(vals[8]) # mean angular deviation ij = primitives.iPoint(int(round(x / xstep)), ycells - 1 - int(round(y / ystep))) try: self.phaselists[phase].append(ij) except KeyError: self.phaselists[phase] = [ij] self.set_angle( od, ij, corientation.COrientBunge(*map(math.radians, angles))) prog.setFraction(float(count) / npts) prog.setMessage("%d/%d orientations" % (count, npts)) count += 1 if pbar.stopped(): return None finally: prog.finish() return od
def read(self, filename): hklfile = file(filename, "r") lineiter = iter(hklfile) line = lineiter.next() while not line.startswith('XCells'): line = lineiter.next() xcells = string.atoi(string.split(line)[1]) line = lineiter.next() ycells = string.atoi(string.split(line)[1]) line = lineiter.next() xstep = string.atof(string.split(line)[1]) line = lineiter.next() ystep = string.atof(string.split(line)[1]) line = lineiter.next() od = orientmapdata.OrientMap( primitives.iPoint(xcells, ycells), primitives.Point(xcells*xstep, ycells*ystep)) while not string.split(line)[0] == 'Phase': line = lineiter.next() prog = progress.getProgress(os.path.basename(filename), progress.DEFINITE) try: count = 0 npts = xcells*ycells for line in lineiter: vals = string.split(line) phase = vals[0] x = string.atof(vals[1]) y = string.atof(vals[2]) angles = map(string.atof, vals[5:8]) mad = string.atof(vals[8]) # mean angular deviation ij = primitives.iPoint( int(round(x/xstep)), ycells-1-int(round(y/ystep))) try: self.phaselists[phase].append(ij) except KeyError: self.phaselists[phase] = [ij] self.set_angle( od, ij, corientation.COrientBunge(*map(math.radians, angles))) prog.setFraction(float(count)/npts) prog.setMessage("%d/%d orientations" % (count, npts)) count += 1 if prog.stopped(): return None finally: prog.finish() return od
def Load(self): from ooflib.common import primitives OOF.File.Load.Data(filename=reference_file("ms_data", "saved_ms")) ms_0 = getMicrostructure("save_test") self.assertEqual(ms_0.sizeInPixels(), primitives.iPoint(10, 10, 10)) self.assertEqual(ms_0.size(), primitives.Point(2.5, 3.5, 4.5)) self.assertEqual(ms_0.sizeOfPixels(), (2.5 / 10, 3.5 / 10, 4.5 / 10))
def CreateMSFromImage(self): from ooflib.common import primitives OOF.Microstructure.Create_From_ImageFile( filenames=ThreeDImageDirectory(directory=reference_file( "ms_data", "jpeg"), sort=NumericalOrder()), microstructure_name=automatic, height=20.0, width=20.0, depth=20.0) OOF.Microstructure.Create_From_Image(name="new", width=automatic, height=automatic, image="jpeg:jpeg") ms_0 = getMicrostructure("jpeg") ms_1 = getMicrostructure("new") # Ensure images are separate objects. ms_1_image_id = id(ms_1.getImageContexts()[0]) # Make sure the image wasn't copied in the source microstructure. self.assertEqual(len(ms_0.imageNames()), 1) # Make sure the newly constructed microstructure is the right size. self.assertEqual(ms_1.sizeInPixels(), primitives.iPoint(100, 100, 100)) self.assertEqual(ms_1.size(), primitives.Point(20.0, 20.0, 20.0)) self.assertEqual(ms_1.sizeOfPixels(), (20.0 / 100, 20.0 / 100, 20.0 / 100)) OOF.Microstructure.Delete(microstructure="jpeg") # Ensure that after the originating microstructure has been # deleted, the derived one still has the same image. self.assert_("jpeg" in ms_1.imageNames()) self.assertEqual(ms_1_image_id, id(ms_1.getImageContexts()[0]))
def Create_From_Image(self): from ooflib.common import primitives OOF.Microstructure.Create_From_ImageFile(filename=reference_file( "ms_data", "small.ppm"), microstructure_name=automatic, height=20.0, width=20.0) OOF.Microstructure.Create_From_Image(name="new", width=automatic, height=automatic, image="small.ppm:small.ppm") ms_0 = getMicrostructure("small.ppm") ms_1 = getMicrostructure("new") # Ensure images are separate objects. imageclass = whoville.getClass('Image') ms_1_image_id = id(ms_1.getImageContexts()[0]) # Make sure the image wasn't copied in the source microstructure. self.assertEqual(len(ms_0.imageNames()), 1) # Make sure the newly constructed microstructure is the right size. self.assertEqual(ms_1.sizeInPixels(), primitives.iPoint(150, 150)) self.assertEqual(ms_1.size(), primitives.Point(20.0, 20.0)) self.assertEqual(ms_1.sizeOfPixels(), (20.0 / 150, 20.0 / 150)) OOF.Microstructure.Delete(microstructure="small.ppm") # Ensure that after the originating microstructure has been # deleted, the derived one still has the same image. self.assert_("small.ppm" in ms_1.imageNames()) self.assertEqual(ms_1_image_id, id(ms_1.getImageContexts()[0]))
def Create_From_Image(self): from ooflib.common import primitives OOF.Microstructure.Create_From_ImageFile( filename=os.path.join("ms_data","jpeg","slice.jpg.*"), microstructure_name=automatic, height=20.0, width=20.0, depth=20.0) OOF.Microstructure.Create_From_Image( name="new", width=automatic, height=automatic, image="slice.jpg.*:slice.jpg.*") ms_0 = getMicrostructure("slice.jpg.*") ms_1 = getMicrostructure("new") # Ensure images are separate objects. ms_1_image_id = id(ms_1.getImageContexts()[0]) # Make sure the image wasn't copied in the source microstructure. self.assertEqual(len(ms_0.imageNames()), 1) # Make sure the newly constructed microstructure is the right size. self.assertEqual(ms_1.sizeInPixels(), primitives.iPoint(100,100,100)) self.assertEqual(ms_1.size(), primitives.Point(20.0, 20.0, 20.0)) self.assertEqual(ms_1.sizeOfPixels(), (20.0/100, 20.0/100, 20.0/100)) OOF.Microstructure.Delete(microstructure="slice.jpg.*") # Ensure that after the originating microstructure has been # deleted, the derived one still has the same image. self.assert_("slice.jpg.*" in ms_1.imageNames()) self.assertEqual(ms_1_image_id, id(ms_1.getImageContexts()[0])) OOF.Microstructure.Delete(microstructure="new")
def Create_From_ImageFile(self): from ooflib.SWIG.image import oofimage from ooflib.common import primitives from ooflib.SWIG.common.IO import stringimage self.assertRaises( oofimage.ImageMagickError, OOF.Microstructure.Create_From_ImageFile, filename="nosuchfile", microstructure_name="nosuchfile", height=automatic, width=automatic) self.assertRaises( ooferror.ErrUserError, OOF.Microstructure.Create_From_ImageFile, filename=reference_file("ms_data","small.ppm"), microstructure_name="oops", height=-1.0, width=-1.0) OOF.Microstructure.Create_From_ImageFile( filename=reference_file("ms_data","small.ppm"), microstructure_name="small.ms", height=20.0, width=20.0) ms = getMicrostructure("small.ms") self.assertEqual(ms.size(), primitives.Point(20.0, 20.0)) self.assertEqual(ms.sizeInPixels(), primitives.iPoint(150,150)) self.assertEqual(ms.sizeOfPixels(), (20.0/150, 20.0/150)) ms_images = ms.imageNames() self.assertEqual(len(ms_images), 1) self.assert_("small.ppm" in ms_images) img = oofimage.getImage("small.ms:small.ppm") strimg = stringimage.StringImage(ms.sizeInPixels(), ms.size()) img.fillstringimage(strimg) outfile = file('hexstringimage.dat','w') print >> outfile, strimg.hexstringimage() outfile.close() assert filecmp.cmp('hexstringimage.dat', reference_file('ms_data','smallppm.hex')) os.remove("hexstringimage.dat")
def properTile(self, point): ix = int(point.x * self.scale[0]) iy = int(point.y * self.scale[1]) # When right or top skeleton edge was clicked .... if ix == self.size[0]: ix -= 1 if iy == self.size[1]: iy -= 1 ## if config.dimension() == 2: return primitives.iPoint(ix, iy)
def properTile(self, point): ix = int( point.x*self.scale[0] ) iy = int( point.y*self.scale[1] ) # When right or top skeleton edge was clicked .... if ix==self.size[0]: ix -= 1 if iy==self.size[1]: iy -= 1 ## if config.dimension() == 2: return primitives.iPoint(ix, iy)
def read(self, filepattern): dirname = os.path.dirname(filepattern) items = os.listdir(dirname) escaped_pattern = string.replace( re.escape(os.path.basename(filepattern)), "\\*", ".*?") files = [] for item in items: match = re.match(escaped_pattern, item) if match != None: span = match.span() if span[0] == 0 and span[1] == len(item): files.append(os.path.join(dirname, item)) prog = progress.getProgress(os.path.basename(filepattern), progress.DEFINITE) try: # Look at the just the first file to get some info z = 0 rows, npts = self.readfile(files[0], prog, z) nx = len(rows[0]) ny = len(rows) nz = len(files) dx = rows[0][1].position[0] - rows[0][0].position[0] dy = rows[1][0].position[1] - rows[0][0].position[1] dz = 1 pxlsize = primitives.Point(dx, dy, dz) size = rows[-1][-1].position + pxlsize od = orientmapdata.OrientMap(primitives.iPoint(nx, ny, nz), size) count = 0 for row in rows: count += 1 for datum in row: self.addDatum(od, datum, pxlsize, ny, count, npts, prog, nz) # now look at the rest of the files for file in files[1:]: z = z + dz rows, nrowpts = self.readfile(file, prog, z) npts = npts + nrowpts count = 0 for row in rows: count += 1 if len(row) != nx: raise ooferror.ErrUserError( "Orientation map data appears to be incomplete" ) for datum in row: self.addDatum(od, datum, pxlsize, ny, count, npts, prog, nz) finally: prog.finish() return od
def Load(self): from ooflib.common import primitives # The MS in this file is named "load_test", and is the same # as the "save_test" one, except for the name. OOF.File.Load.Data(filename=reference_file("ms_data", "saved_ms")) ms_0 = getMicrostructure("save_test") self.assertEqual(ms_0.sizeInPixels(), primitives.iPoint(10, 10)) self.assertEqual(ms_0.size(), primitives.Point(2.5, 3.5)) self.assertEqual(ms_0.sizeOfPixels(), (2.5 / 10, 3.5 / 10))
def Load(self): from ooflib.common import primitives # The MS in this file is named "load_test", and is the same # as the "save_test" one, except for the name. OOF.File.Load.Data(filename=reference_file("ms_data","saved_ms")) ms_0 = getMicrostructure("save_test") self.assertEqual(ms_0.sizeInPixels(), primitives.iPoint(10,10)) self.assertEqual(ms_0.size(), primitives.Point(2.5, 3.5)) self.assertEqual(ms_0.sizeOfPixels(), (2.5/10, 3.5/10 ))
def Load(self): OOF.Microstructure.New(name="load_test", width=100, height=100, depth=100, width_in_pixels=100, height_in_pixels=100, depth_in_pixels=100) OOF.File.Load.Image(filenames=ThreeDImageDirectory( directory=reference_file("ms_data", "jpeg"), sort=NumericalOrder()), microstructure="load_test", height=automatic, width=automatic, depth=automatic) ms = getMicrostructure("load_test") ms_images = ms.imageNames() self.assertEqual(len(ms_images), 1) self.assert_("jpeg" in ms_images) # Check a few pixel values im = imagecontext.imageContexts['load_test:jpeg'].getObject() self.assertEqual( im[primitives.iPoint(0, 0, 0)], color.RGBColor(0.054901960784313725, 0.996078431372549, 0.9921568627450981)) self.assertNotEqual(im[primitives.iPoint(0, 0, 0)], color.RGBColor(0.054901960, 0.0, 0.99215686)) # This voxel is selected in Direct_Pixel_Selection.Color in # pixel_test.py on Mac but not Linux. Apparently Mac and # Linux use different jpeg libraries which decompress images # differently. WTF? ## TODO: Check that problem is avoided if vtk on Mac is ## compiled with USE_SYSTEM_JPEG=OFF self.assertEqual( im[primitives.iPoint(16, 9, 99)], # Linux value color.RGBColor(0.3058823529411765, 0.9921568627450981, 0.7215686274509804) # Mac value # color.RGBColor( # 0.2901960784313726, # 1.0, # 0.7372549019607844) )
def read(self, filename): prog = progress.getProgress(os.path.basename(filename), progress.DEFINITE) rows, npts = self.readfile(filename, prog) try: nx = len(rows[0]) ny = len(rows) count = 0 for row in rows: count += 1 if len(row) != nx: raise ooferror.ErrUserError( "Orientation map data appears to be incomplete") # pixel size dx = rows[0][1].position[0] - rows[0][0].position[0] dy = rows[1][0].position[1] - rows[0][0].position[1] pxlsize = primitives.Point(dx, dy) # If we assume that the points are in the centers of the # pixels, then the actual physical size is one pixel bigger # than the range of the xy values. size = rows[-1][-1].position + pxlsize debug.fmsg("nx=", nx, "ny=", ny, "size=", size, "pxlsize=", pxlsize) if config.dimension() == 2: od = orientmapdata.OrientMap(primitives.iPoint(nx, ny), size) else: od = orientmapdata.OrientMap(primitives.iPoint(nx, ny, 1), size) count = 0 for row in rows: for datum in row: self.addDatum(od, datum, pxlsize, ny, count, npts, prog) finally: prog.finish() return od
def draw_image(self, image, offset, size): if image.sizeInPixels() == iPoint(0, 0): return pdfid = len(self.objects) self.objects.append(0) # Place-holder. newimage = PDFImageObject(pdfid, image, offset, size) self.images.append(newimage) self.current_layer.add_image(newimage) self.expand_range( Rectangle(offset, Coord(offset[0] + size[0], offset[1] + size[1])))
def nextBand(self, ll=None, ur=None): nodes = [] # Bottom j = ll.y for i in range(ll.x, ur.x+1): nodes += self[primitives.iPoint(i,j)][:] # Top j = ur.y for i in range(ll.x, ur.x+1): nodes += self[primitives.iPoint(i,j)][:] # Left i = ll.x for j in range(ll.y+1, ur.y): nodes += self[primitives.iPoint(i,j)][:] # Right i = ur.x for j in range(ll.y+1, ur.y): nodes += self[primitives.iPoint(i,j)][:] return nodes
def draw_image(self,image,offset,size): if image.sizeInPixels()==iPoint(0,0): return pdfid = len(self.objects) self.objects.append(0) # Place-holder. newimage = PDFImageObject(pdfid,image,offset,size) self.images.append(newimage) self.current_layer.add_image(newimage) self.expand_range(Rectangle(offset,Coord(offset[0]+size[0], offset[1]+size[1])))
def newMicrostructure_Parallel(menuitem, name, width, height, width_in_pixels, height_in_pixels): # Only for the back-end processes global _rank if _rank == 0: return ms = ooflib.common.microstructure.Microstructure( name, primitives.iPoint(width_in_pixels, height_in_pixels), primitives.Point(width, height))
def nextBand(self, ll=None, ur=None): nodes = [] # Bottom j = ll.y for i in range(ll.x, ur.x + 1): nodes += self[primitives.iPoint(i, j)][:] # Top j = ur.y for i in range(ll.x, ur.x + 1): nodes += self[primitives.iPoint(i, j)][:] # Left i = ll.x for j in range(ll.y + 1, ur.y): nodes += self[primitives.iPoint(i, j)][:] # Right i = ur.x for j in range(ll.y + 1, ur.y): nodes += self[primitives.iPoint(i, j)][:] return nodes
def __init__(self, array): # array is a list of lists of Ints, which are pixel categories self.pxls = {} # list of pixels, keyed by category for j, sublist in enumerate(array): if config.dimension() == 2: for i, category in enumerate(sublist): where = primitives.iPoint(i, j) try: self.pxls[category].append(where) except KeyError: self.pxls[category] = [where] elif config.dimension() == 3: for i, subsublist in enumerate(sublist): for k, category in enumerate(subsublist): where = primitives.iPoint(k, i, j) try: self.pxls[category].append(where) except KeyError: self.pxls[category] = [where]
def draw_shaped_image(self, image, offset, size, shapecolor): ## No longer used in OOF if image.sizeInPixels() == iPoint(0, 0): return pdfid = len(self.objects) self.objects.append(0) # Place-holder newimage = PDFShapedImageObject(pdfid, image, offset, size, shapecolor) self.images.append(newimage) self.current_layer.add_image(newimage) self.expand_range( Rectangle(offset, Coord(offset[0] + size[0], offset[1] + size[1])))
def draw_shaped_image(self,image,offset,size,shapecolor): ## No longer used in OOF if image.sizeInPixels()==iPoint(0,0): return pdfid = len(self.objects) self.objects.append(0) # Place-holder newimage = PDFShapedImageObject(pdfid,image,offset,size,shapecolor) self.images.append(newimage) self.current_layer.add_image(newimage) self.expand_range(Rectangle(offset,Coord(offset[0]+size[0], offset[1]+size[1])) )
def draw_alpha_image(self, bitmap, offset, size): if bitmap.sizeInPixels()==iPoint(0,0): return pdfid = len(self.objects) self.objects.append(0) # Place-holder maskcolor = bitmap.getBG() newimage = PDFShapedImageObject(pdfid,bitmap,offset,size,maskcolor) self.images.append(newimage) self.current_layer.add_image(newimage) self.current_layer.set_alpha(bitmap.getTintAlpha()) self.expand_range(Rectangle(offset,Coord(offset[0]+size[0], offset[1]+size[1])) )
def draw_alpha_image(self, bitmap, offset, size): if bitmap.sizeInPixels() == iPoint(0, 0): return pdfid = len(self.objects) self.objects.append(0) # Place-holder maskcolor = bitmap.getBG() newimage = PDFShapedImageObject(pdfid, bitmap, offset, size, maskcolor) self.images.append(newimage) self.current_layer.add_image(newimage) self.current_layer.set_alpha(bitmap.getTintAlpha()) self.expand_range( Rectangle(offset, Coord(offset[0] + size[0], offset[1] + size[1])))
def addDatum(self, od, datum, pxlsize, ny, count, npts, prog, nz=0): prog.setMessage("Processing orientations %d/%d" % (count,npts)) if config.dimension() == 2: ij = primitives.iPoint( int(round(datum.position[0]/pxlsize[0])), ny-1-int(round(datum.position[1]/pxlsize[1]))) elif config.dimension() == 3: ij = primitives.iPoint( int(round(datum.position[0]/pxlsize[0])), ny-1-int(round(datum.position[1]/pxlsize[1])), nz-1-int(round(datum.position[2]/pxlsize[2]))) try: self.phaselists[datum.phasename].append(ij) except KeyError: self.phaselists[datum.phasename] = [ij] self.set_angle(od, ij, datum.euler()) prog.setMessage("%d/%d orientations" % (count,npts)) prog.setFraction(float(count)/npts) count += 1 if prog.stopped(): return None
def updateButtonCB(self, button): debug.mainthreadTest() self.updatebutton.set_sensitive(0) x = int(self.xtext.get_text()) y = int(self.ytext.get_text()) z = int(self.ztext.get_text()) msOrImage = self.gfxwindow().topmost('Microstructure', 'Image') size = msOrImage.sizeInPixels() if x < 0 or x >= size.x or y < 0 or y >= size.y \ or z < 0 or z >= size.z: # illegal point self.update() # restore original values return self.toolbox.menu.QueryDirectly(voxel=primitives.iPoint(x, y, z))
def newMicrostructure_Parallel(menuitem, name, width, height, width_in_pixels, height_in_pixels): # Only for the back-end processes global _rank if _rank == 0: return ms = ooflib.common.microstructure.Microstructure( name, primitives.iPoint(width_in_pixels, height_in_pixels), primitives.Point(width, height) )
def newMicrostructure(menuitem, name, width, height, width_in_pixels, height_in_pixels): if width<=0 or height<=0 or width_in_pixels<=0 or height_in_pixels<=0: raise ooferror.ErrUserError("Negative size values are not allowed.") if parallel_enable.enabled(): # For the rear-end guys microstructureIPC.msmenu.New_Parallel(name=name, width=width, height=height, width_in_pixels=width_in_pixels, height_in_pixels=height_in_pixels) # Serial mode & #0 in parallel mode ms = ooflib.common.microstructure.Microstructure( name, primitives.iPoint(width_in_pixels, height_in_pixels), primitives.Point(width, height) )
def newMicrostructure(menuitem, name, width, height, width_in_pixels, height_in_pixels): if width <= 0 or height <= 0 or width_in_pixels <= 0 or height_in_pixels <= 0: raise ooferror.ErrUserError( "Negative size values are not allowed.") if parallel_enable.enabled(): # For the rear-end guys microstructureIPC.msmenu.New_Parallel( name=name, width=width, height=height, width_in_pixels=width_in_pixels, height_in_pixels=height_in_pixels) # Serial mode & #0 in parallel mode ms = ooflib.common.microstructure.Microstructure( name, primitives.iPoint(width_in_pixels, height_in_pixels), primitives.Point(width, height))
def Create_From_ImageFile(self): from ooflib.image import oofimage3d from ooflib.common import primitives from ooflib.SWIG.common.IO import stringimage self.assertRaises(ooferror.ErrUserError, OOF.Microstructure.Create_From_ImageFile, filename="nosuchfile", microstructure_name="nosuchfile", height=automatic, width=automatic, depth=automatic) self.assertRaises(ooferror.ErrUserError, OOF.Microstructure.Create_From_ImageFile, filename=os.path.join("ms_data", "jpeg", "slice.jpg.*"), microstructure_name="oops", height=-1.0, width=-1.0, depth=-1.0) OOF.Microstructure.Create_From_ImageFile( filename=os.path.join("ms_data", "jpeg", "slice.jpg.*"), microstructure_name="slice.jpg.*", height=20.0, width=20.0, depth=20.0) ms = getMicrostructure("slice.jpg.*") self.assertEqual(ms.size(), primitives.Point(20.0, 20.0, 20.0)) self.assertEqual(ms.sizeInPixels(), primitives.iPoint(100, 100, 100)) self.assertEqual(ms.sizeOfPixels(), (20.0 / 100, 20.0 / 100, 20.0 / 100)) ms_images = ms.imageNames() self.assertEqual(len(ms_images), 1) self.assert_("slice.jpg.*" in ms_images) img = oofimage3d.getImage("slice.jpg.*:slice.jpg.*") ## strimg = stringimage.StringImage(ms.sizeInPixels(), ms.size()) ## img.fillstringimage(strimg) ## outfile = file('hexstringimage.dat','w') ## print >> outfile, strimg.hexstringimage() ## outfile.close() ## assert filecmp.cmp('hexstringimage.dat', ## os.path.join('ms_data','smallppm.hex')) ## os.remove("hexstringimage.dat") OOF.Microstructure.Delete(microstructure="slice.jpg.*")
def up(self, x, y, shift, ctrl): msOrImage = self.gfxwindow().topmost('Microstructure', 'Image') if msOrImage: if config.dimension() == 3: canvas = self.toolbox.gfxwindow().oofcanvas view = canvas.get_view() pt = canvas.display2Physical(view, x, y) if pt is not None: self.toolbox.menu.Query(point=pt, view=view) else: pt = primitives.iPoint(x, y) self.toolbox.menu.Query(point=pt) # p = self.gfxwindow().oofcanvas.screen_coords_to_3D_coords(x,y) # if p is not None: # where = msOrImage.pixelFromPoint( # primitives.Point(p[0],p[1],p[2])); # if where is not None: # self.toolbox.menu.Query(x=where[0], y=where[1], z=where[2]) else: for plugin in self.plugins: plugin.nonsense()
def Create_From_ImageFile(self): from ooflib.SWIG.image import oofimage from ooflib.common import primitives from ooflib.SWIG.common.IO import stringimage self.assertRaises(oofimage.ImageMagickError, OOF.Microstructure.Create_From_ImageFile, filename="nosuchfile", microstructure_name="nosuchfile", height=automatic, width=automatic) self.assertRaises(ooferror.ErrUserError, OOF.Microstructure.Create_From_ImageFile, filename=reference_file("ms_data", "small.ppm"), microstructure_name="oops", height=-1.0, width=-1.0) OOF.Microstructure.Create_From_ImageFile( filename=reference_file("ms_data", "small.ppm"), microstructure_name="small.ms", height=20.0, width=20.0) ms = getMicrostructure("small.ms") self.assertEqual(ms.size(), primitives.Point(20.0, 20.0)) self.assertEqual(ms.sizeInPixels(), primitives.iPoint(150, 150)) self.assertEqual(ms.sizeOfPixels(), (20.0 / 150, 20.0 / 150)) ms_images = ms.imageNames() self.assertEqual(len(ms_images), 1) self.assert_("small.ppm" in ms_images) img = oofimage.getImage("small.ms:small.ppm") strimg = stringimage.StringImage(ms.sizeInPixels(), ms.size()) img.fillstringimage(strimg) outfile = file('hexstringimage.dat', 'w') print >> outfile, strimg.hexstringimage() outfile.close() assert filecmp.cmp('hexstringimage.dat', reference_file('ms_data', 'smallppm.hex')) os.remove("hexstringimage.dat")
def Create_From_ImageFile(self): from ooflib.image import oofimage3d from ooflib.common import primitives from ooflib.SWIG.common.IO import stringimage self.assertRaises( ooferror.ErrUserError, OOF.Microstructure.Create_From_ImageFile, filename="nosuchfile", microstructure_name="nosuchfile", height=automatic, width=automatic, depth=automatic) self.assertRaises( ooferror.ErrUserError, OOF.Microstructure.Create_From_ImageFile, filename=os.path.join("ms_data","jpeg","slice.jpg.*"), microstructure_name="oops", height=-1.0, width=-1.0, depth=-1.0) OOF.Microstructure.Create_From_ImageFile( filename=os.path.join("ms_data","jpeg","slice.jpg.*"), microstructure_name="slice.jpg.*", height=20.0, width=20.0, depth=20.0) ms = getMicrostructure("slice.jpg.*") self.assertEqual(ms.size(), primitives.Point(20.0, 20.0, 20.0)) self.assertEqual(ms.sizeInPixels(), primitives.iPoint(100,100,100)) self.assertEqual(ms.sizeOfPixels(), (20.0/100, 20.0/100, 20.0/100)) ms_images = ms.imageNames() self.assertEqual(len(ms_images), 1) self.assert_("slice.jpg.*" in ms_images) img = oofimage3d.getImage("slice.jpg.*:slice.jpg.*") ## strimg = stringimage.StringImage(ms.sizeInPixels(), ms.size()) ## img.fillstringimage(strimg) ## outfile = file('hexstringimage.dat','w') ## print >> outfile, strimg.hexstringimage() ## outfile.close() ## assert filecmp.cmp('hexstringimage.dat', ## os.path.join('ms_data','smallppm.hex')) ## os.remove("hexstringimage.dat") OOF.Microstructure.Delete(microstructure="slice.jpg.*")
def setup(self): sighs = self.image.GetDimensions() # subtract 1 because of padding self._sizeInPixels = primitives.iPoint(sighs[0]-1, sighs[1]-1, sighs[2]-1)
def _read(self, tslfile, prog): data, hexgrid = self.readData(tslfile, prog) npts = len(data) rows = list(getrows(data)) # sorts data if hexgrid is None: # readData didn't set hexgrid. The grid is hexagonal if # the first two rows don't start at the same x. hexgrid = rows[0][0].position[0] != rows[1][0].position[0] if hexgrid: # Throw out every other row. reporter.warn( "Converting hexagonal lattice to rectangular" " by discarding alternate rows.") rows = rows[::2] # discard odd numbered rows nx = len(rows[0]) ny = len(rows) count = 0 for row in rows: count += 1 if len(row) != nx: raise ooferror.ErrUserError( "Orientation map data appears to be incomplete.\n" "len(row 0)=%d len(row %d)=%d" % (nx, count, len(row))) # TSL puts the origin at the top left, so it's using a left # handed coordinate system! If flip_y==True, fix that. Also, # make sure there are no negative x or y values. ymax = rows[-1][0].position[1] ymin = rows[0][0].position[1] xmax = rows[0][-1].position[0] xmin = rows[0][0].position[0] for row in rows: for point in row: if self.flip_x: point.position[0] = xmax - point.position[0] else: point.position[0] = point.position[0] - xmin if self.flip_y: point.position[1] = ymax - point.position[1] else: point.position[1] = point.position[1] - ymin # If flipped, the rows are still ordered top to bottom, but # the coordinates increase bottom to top. # pixel size dx = abs(rows[0][1].position[0] - rows[0][0].position[0]) dy = abs(rows[0][0].position[1] - rows[1][0].position[1]) pxlsize = primitives.Point(dx, dy) width = abs(rows[0][0].position[0] - rows[0][-1].position[0]) height = abs(rows[0][0].position[1] - rows[-1][0].position[1]) # If we assume that the points are in the centers of the # pixels, then the actual physical size is one pixel bigger # than the range of the xy values. size = primitives.Point(width, height) + pxlsize od = orientmapdata.OrientMap(primitives.iPoint(nx, ny), size) prog.setMessage("%d/%d orientations" % (0, npts)) count = 0 for row in rows: for datum in row: ij = primitives.iPoint( int(round(datum.position[0]/pxlsize[0])), int(round(datum.position[1]/pxlsize[1]))) try: self.phaselists[datum.phasename].append(ij) except KeyError: self.phaselists[datum.phasename] = [ij] self.set_angle(od, ij, datum.euler()) prog.setMessage("%d/%d orientations" % (count,npts)) prog.setFraction(float(count)/npts) count += 1 if prog.stopped(): return None prog.finish() return od
def binaryRead(self, parser): b = parser.getBytes(iPointParameter.structlen) vals = struct.unpack(iPointParameter.structfmt, b) return primitives.iPoint(*vals)
def writeMicrostructure(datafile, mscontext): ms = mscontext.getObject() mscontext.begin_reading() try: datafile.startCmd(OOF.LoadData.Microstructure.New) datafile.argument('name', ms.name()) datafile.argument('size', ms.size()) datafile.argument('isize', ms.sizeInPixels()) datafile.endCmd() for ioplugin in _ioplugins: ioplugin(datafile, mscontext) ## for image in ms.getImageContexts(): ## image.writeImage(datafile) # Store pixel attributes by storing category definitions. for grpname in ms.groupNames(): grp = ms.findGroup(grpname) datafile.startCmd(OOF.LoadData.Microstructure.PixelGroup) datafile.argument('microstructure', ms.name()) datafile.argument('group', grpname) datafile.argument('meshable', grp.is_meshable()) datafile.endCmd() # Create the actual active areas themselves. for aaname in ms.activeAreaNames(): datafile.startCmd(OOF.LoadData.Microstructure.NewActiveArea) datafile.argument('microstructure', ms.name()) datafile.argument('name', aaname) datafile.endCmd() categories = ms.getCategoryMapRO() # Save categories datafile.startCmd(OOF.LoadData.Microstructure.Categories) datafile.argument('microstructure', ms.name()) datafile.argument('categories', categories) datafile.endCmd() # Find representative pixels for each category TODO 3.1: The # underlying code no longer uses representative pixels. There # may be a more efficient way to do this using # attributeVectorSet. Do this when moving to C. reppxls = {} i = 0 if config.dimension() == 2: for row in categories: j = 0 for ctgry in row: reppxls[ctgry] = primitives.iPoint(j, i) j += 1 i += 1 elif config.dimension() == 3: for slab in categories: j = 0 for row in slab: k = 0 for ctgry in row: reppxls[ctgry] = primitives.iPoint(j, i, k) k += 1 j += 1 i += 1 # Save definitions of pixel categories for i in range(pixelattribute.nAttributes()): reg = pixelattribute.getRegistration(i) # debug.fmsg("Writing category data for", reg.name()) reg.writeGlobalData(datafile, ms) for category in range(len(reppxls)): reppxl = reppxls[category] datafile.startCmd( getattr(OOF.LoadData.Microstructure.DefineCategory, reg.name())) datafile.argument('microstructure', ms.name()) datafile.argument('category', category) if reg.writeData(datafile, ms, reppxl): datafile.endCmd() # debug.fmsg("wrote data for category", category) else: datafile.discardCmd() # debug.fmsg("oops, nothing written for category", category) datafile.startCmd(OOF.LoadData.Microstructure.EndCategories) datafile.argument('microstructure', ms.name()) datafile.endCmd() #Interface branch #Note that materials that are not assigned to pixels do not get saved #when the microstructure is saved, if we rely on the above mechanism #(reg.writeGlobalData is not called for these materials). for ioplugin in _ioplugins_last: ioplugin(datafile, mscontext) finally: mscontext.end_reading()
imageGeoFilter = vtk.vtkImageDataGeometryFilter() imageGeoFilter.SetInput(indexedImage) imageGeoFilter.SetExtent(imageBounds) imagePoints = imageGeoFilter.GetOutput() imagePoints.Update() # needed to calulate normal and area polygon = vtk.vtkPolygon() triangle = vtk.vtkTriangle() normal = [0.0,0.0,0.0] pt=[0.0,0.0,0.0] # loop over voxels and add faces that border different pixel groups to polydata for i in xrange(indexedImage.GetNumberOfCells()): voxel = indexedImage.GetCell(i) p = voxel.GetPoints().GetPoint(0) point = primitives.iPoint(p[0]-x0,p[1]-y0,p[2]-z0) value = indexedImage.GetScalarComponentAsFloat(point[0],point[1],point[2],0) for j in xrange(6): point2 = point+dirs[j] if point2[0] >= imageBounds[0] and point2[0] <= imageBounds[1]-1 and point2[1] >= imageBounds[2] and point2[1] <= imageBounds[3]-1 and point2[2] >= imageBounds[4] and point2[2] <= imageBounds[5]-1: value2 = indexedImage.GetScalarComponentAsFloat(point2[0],point2[1],point2[2],0) if value2 != value: # only add face for the given value, so that we don't # get double faces and so that the normal points # outward. face=voxel.GetFace(j) quadpoints = vtk.vtkPoints() # We have to explicity make the quad because, very annoyingly, # the order of points in the voxels and pixels returned by # vtkImageData are not compatible with the quads used for # polydata.
def _read(self, datafile, prog): # readData gets data from the file, but does no processing data = self.readData(datafile, prog) rows = list(getrows(data)) # sorts data # The grid is hexagonal if the first two rows don't start at the same x. if rows[0][0].position[0] != rows[1][0].position[0]: # Throw out every other row. reporter.warn( "Converting hexagonal lattice to rectangular" " by discarding alternate rows.") rows = rows[::2] # discard odd numbered rows # Check that all rows are the same length, and flip the # coordinates if requested. nx = len(rows[0]) ny = len(rows) ymax = rows[-1][0].position[1] ymin = rows[0][0].position[1] xmax = rows[0][-1].position[0] xmin = rows[0][0].position[0] count = 0 for row in rows: count += 1 if len(row) != nx: raise ooferror.ErrUserError( "Orientation map data appears to be incomplete.\n" "len(row 0)=%d len(row %d)=%d" % (nx, count, len(row))) for point in row: if self.flip_x: point.position[0] = xmax - point.position[0] else: point.position[0] = point.position[0] - xmin if self.flip_y: point.position[1] = ymax - point.position[1] else: point.position[1] = point.position[1] - ymin # pixel size dx = abs(rows[0][1].position[0] - rows[0][0].position[0]) dy = abs(rows[0][0].position[1] - rows[1][0].position[1]) pxlsize = primitives.Point(dx, dy) width = abs(rows[0][0].position[0] - rows[0][-1].position[0]) height = abs(rows[0][0].position[1] - rows[-1][0].position[1]) # If we assume that the points are in the centers of the # pixels, then the actual physical size is one pixel bigger # than the range of the xy values. size = primitives.Point(width, height) + pxlsize npts = len(rows)*len(rows[0]) od = orientmapdata.OrientMap(primitives.iPoint(nx, ny), size*self.scale_factor) prog.setMessage("%d/%d orientations" % (0, npts)) count = 0 for row in rows: for datum in row: ij = primitives.iPoint( int(round(datum.position[0]/pxlsize[0])), int(round(datum.position[1]/pxlsize[1]))) for groupname in datum.groups: try: self.groupmembers[groupname].append(ij) except KeyError: self.groupmembers[groupname] = [ij] if self.angle_units == 'Degrees': offset = math.radians(self.angle_offset) angleargs = datum.angletuple else: # angle units are Radians offset = self.angle_offset # All Orientation subclasses that take angle args # assume that they're in degrees. They have a # static radians2Degrees method that converts the # angle args from radians to degrees. angleargs = self.angle_type.radians2Degrees( *datum.angletuple) # Create an instance of the Orientation subclass. orient = self.angle_type(*angleargs) if self.angle_offset != 0: orient = orient.rotateXY(self.angle_offset) # Insert this point into the OrientMap object. self.set_angle(od, ij, orient.corient) prog.setMessage("%d/%d orientations" % (count, npts)) prog.setFraction(float(count)/npts) count += 1 if prog.stopped(): return None return od
def writeMicrostructure(datafile, mscontext): ms = mscontext.getObject() mscontext.begin_reading() try: datafile.startCmd(OOF.LoadData.Microstructure.New) datafile.argument("name", ms.name()) datafile.argument("size", ms.size()) datafile.argument("isize", ms.sizeInPixels()) datafile.endCmd() for ioplugin in _ioplugins: ioplugin(datafile, mscontext) ## for image in ms.getImageContexts(): ## image.writeImage(datafile) # Store pixel attributes by storing category definitions. for grpname in ms.groupNames(): grp = ms.findGroup(grpname) datafile.startCmd(OOF.LoadData.Microstructure.PixelGroup) datafile.argument("microstructure", ms.name()) datafile.argument("group", grpname) datafile.argument("meshable", grp.is_meshable()) datafile.endCmd() # Create the actual active areas themselves. for aaname in ms.activeAreaNames(): datafile.startCmd(OOF.LoadData.Microstructure.NewActiveArea) datafile.argument("microstructure", ms.name()) datafile.argument("name", aaname) datafile.endCmd() categories = ms.getCategoryMapRO() # Save categories datafile.startCmd(OOF.LoadData.Microstructure.Categories) datafile.argument("microstructure", ms.name()) datafile.argument("categories", categories) datafile.endCmd() # Find representative pixels for each category reppxls = {} i = 0 if config.dimension() == 2: for row in categories: j = 0 for ctgry in row: reppxls[ctgry] = primitives.iPoint(j, i) j += 1 i += 1 elif config.dimension() == 3: for slab in categories: j = 0 for row in slab: k = 0 for ctgry in row: reppxls[ctgry] = primitives.iPoint(k, j, i) k += 1 j += 1 i += 1 # Save definitions of pixel categories for i in range(pixelattribute.nAttributes()): reg = pixelattribute.getRegistration(i) reg.writeGlobalData(datafile, ms) for category in range(len(reppxls)): reppxl = reppxls[category] datafile.startCmd(getattr(OOF.LoadData.Microstructure.DefineCategory, reg.name())) datafile.argument("microstructure", ms.name()) datafile.argument("category", category) if reg.writeData(datafile, ms, reppxl): datafile.endCmd() else: datafile.discardCmd() datafile.startCmd(OOF.LoadData.Microstructure.EndCategories) datafile.argument("microstructure", ms.name()) datafile.endCmd() # Interface branch # Note that materials that are not assigned to pixels do not get saved # when the microstructure is saved, if we rely on the above mechanism # (reg.writeGlobalData is not called for these materials). for ioplugin in _ioplugins_last: ioplugin(datafile, mscontext) finally: mscontext.end_reading()
def _read(self, datafile, prog): # readData gets data from the file, but does no processing data = self.readData(datafile, prog) rows = list(getrows(data)) # sorts data # The grid is hexagonal if the first two rows don't start at the same x. if rows[0][0].position[0] != rows[1][0].position[0]: # Throw out every other row. reporter.warn("Converting hexagonal lattice to rectangular" " by discarding alternate rows.") rows = rows[::2] # discard odd numbered rows # Check that all rows are the same length, and flip the # coordinates if requested. nx = len(rows[0]) ny = len(rows) ymax = rows[-1][0].position[1] ymin = rows[0][0].position[1] xmax = rows[0][-1].position[0] xmin = rows[0][0].position[0] count = 0 for row in rows: count += 1 if len(row) != nx: raise ooferror.ErrUserError( "Orientation map data appears to be incomplete.\n" "len(row 0)=%d len(row %d)=%d" % (nx, count, len(row))) for point in row: if self.flip_x: point.position[0] = xmax - point.position[0] else: point.position[0] = point.position[0] - xmin if self.flip_y: point.position[1] = ymax - point.position[1] else: point.position[1] = point.position[1] - ymin # pixel size dx = abs(rows[0][1].position[0] - rows[0][0].position[0]) dy = abs(rows[0][0].position[1] - rows[1][0].position[1]) pxlsize = primitives.Point(dx, dy) width = abs(rows[0][0].position[0] - rows[0][-1].position[0]) height = abs(rows[0][0].position[1] - rows[-1][0].position[1]) # If we assume that the points are in the centers of the # pixels, then the actual physical size is one pixel bigger # than the range of the xy values. size = primitives.Point(width, height) + pxlsize npts = len(rows) * len(rows[0]) od = orientmapdata.OrientMap(primitives.iPoint(nx, ny), size * self.scale_factor) prog.setMessage("%d/%d orientations" % (0, npts)) count = 0 for row in rows: for datum in row: ij = primitives.iPoint( int(round(datum.position[0] / pxlsize[0])), int(round(datum.position[1] / pxlsize[1]))) for groupname in datum.groups: try: self.groupmembers[groupname].append(ij) except KeyError: self.groupmembers[groupname] = [ij] if self.angle_units == 'Degrees': offset = math.radians(self.angle_offset) angleargs = datum.angletuple else: # angle units are Radians offset = self.angle_offset # All Orientation subclasses that take angle args # assume that they're in degrees. They have a # static radians2Degrees method that converts the # angle args from radians to degrees. angleargs = self.angle_type.radians2Degrees( *datum.angletuple) # Create an instance of the Orientation subclass. orient = self.angle_type(*angleargs) if self.angle_offset != 0: orient = orient.rotateXY(self.angle_offset) # Insert this point into the OrientMap object. self.set_angle(od, ij, orient.corient) prog.setMessage("%d/%d orientations" % (count, npts)) prog.setFraction(float(count) / npts) count += 1 if prog.stopped(): return None return od
def _read(self, tslfile, prog): data, hexgrid = self.readData(tslfile, prog) npts = len(data) rows = list(getrows(data)) # sorts data if hexgrid is None: # readData didn't set hexgrid. The grid is hexagonal if # the first two rows don't start at the same x. hexgrid = rows[0][0].position[0] != rows[1][0].position[0] if hexgrid: # Throw out every other row. reporter.warn("Converting hexagonal lattice to rectangular" " by discarding alternate rows.") rows = rows[::2] # discard odd numbered rows nx = len(rows[0]) ny = len(rows) count = 0 for row in rows: count += 1 if len(row) != nx: raise ooferror.ErrUserError( "Orientation map data appears to be incomplete.\n" "len(row 0)=%d len(row %d)=%d" % (nx, count, len(row))) # TSL puts the origin at the top left, so it's using a left # handed coordinate system! If flip_y==True, fix that. Also, # make sure there are no negative x or y values. ymax = rows[-1][0].position[1] ymin = rows[0][0].position[1] xmax = rows[0][-1].position[0] xmin = rows[0][0].position[0] for row in rows: for point in row: if self.flip_x: point.position[0] = xmax - point.position[0] else: point.position[0] = point.position[0] - xmin if self.flip_y: point.position[1] = ymax - point.position[1] else: point.position[1] = point.position[1] - ymin # If flipped, the rows are still ordered top to bottom, but # the coordinates increase bottom to top. # pixel size dx = abs(rows[0][1].position[0] - rows[0][0].position[0]) dy = abs(rows[0][0].position[1] - rows[1][0].position[1]) pxlsize = primitives.Point(dx, dy) width = abs(rows[0][0].position[0] - rows[0][-1].position[0]) height = abs(rows[0][0].position[1] - rows[-1][0].position[1]) # If we assume that the points are in the centers of the # pixels, then the actual physical size is one pixel bigger # than the range of the xy values. size = primitives.Point(width, height) + pxlsize od = orientmapdata.OrientMap(primitives.iPoint(nx, ny), size) prog.setMessage("%d/%d orientations" % (0, npts)) count = 0 for row in rows: for datum in row: ij = primitives.iPoint( int(round(datum.position[0] / pxlsize[0])), int(round(datum.position[1] / pxlsize[1]))) try: self.phaselists[datum.phasename].append(ij) except KeyError: self.phaselists[datum.phasename] = [ij] self.set_angle(od, ij, datum.euler()) prog.setMessage("%d/%d orientations" % (count, npts)) prog.setFraction(float(count) / npts) count += 1 if prog.stopped(): return None prog.finish() return od
imageGeoFilter.SetInput(indexedImage) imageGeoFilter.SetExtent(imageBounds) imagePoints = imageGeoFilter.GetOutput() imagePoints.Update() # needed to calulate normal and area polygon = vtk.vtkPolygon() triangle = vtk.vtkTriangle() normal = [0.0,0.0,0.0] pt=[0.0,0.0,0.0] # loop over voxels and add faces that border different pixel groups to polydata for i in xrange(indexedImage.GetNumberOfCells()): voxel = indexedImage.GetCell(i) p = voxel.GetPoints().GetPoint(0) point = primitives.iPoint(p[0],p[1],p[2]) value = indexedImage.GetScalarComponentAsFloat(point[0],point[1],point[2],0) for j in xrange(6): point2 = point+dirs[j] if point2[0] >= imageBounds[0] and point2[0] <= imageBounds[1]-1 and point2[1] >= imageBounds[2] and point2[1] <= imageBounds[3]-1 and point2[2] >= imageBounds[4] and point2[2] <= imageBounds[5]-1: value2 = indexedImage.GetScalarComponentAsFloat(point2[0],point2[1],point2[2],0) if value2 != value: # only add face for the given value, so that we don't # get double faces and so that the normal points # outward. face=voxel.GetFace(j) quadpoints = vtk.vtkPoints() # We have to explicity make the quad because, very annoyingly, # the order of points in the voxels and pixels returned by # vtkImageData are not compatible with the quads used for # polydata.