Exemplo n.º 1
0
    def load_image(self,
                   image_path,
                   nxs_prefix=None,
                   nxs_dataset=None,
                   nxs_index=None,
                   nxs_update_geometry=False,
                   stack='first'):
        '''load an image from a file.

        The image can be stored as a uint16 binary file (.raw) or in a nexus
        file (.nxs). With the nexus format, several arguments must be
        specified such as the prefix, the index and the dataset number (as str).
        :param str image_path: relative or absolute path to the file containing the image.
        :param str nxs_prefix: the nexus prefix hardcoded into the xml tree.
        :param str nxs_dataset: the dataset number.
        :param int nxs_index: the nexus index.
        :param bool nxs_update_geometry: if True the compute_TwoTh_Psi_arrays method is called after loading the image.
        :params str stack: indicates what to do if many images are present, \
        'first' (default) to keep only the first one, 'median' to compute \
        the median over the third dimension.
        '''
        self.image_path = image_path
        if image_path.endswith('.raw'):
            # check the use of [y, x] array instead of [x, y]
            rawdata = HST_read(self.image_path,
                               data_type=np.uint16,
                               dims=(560, 240, 1))
            if stack == 'first':
                image = rawdata[:, :, 0]
            elif stack == 'median':
                image = np.median(rawdata, axis=2)
            self.data = image.astype(np.float32).transpose()
            self.compute_corrected_image()
        elif image_path.endswith('.nxs'):
            import tables
            f = tables.openFile(image_path)
            root = f.root._v_groups.keys()[0]
            command = 'f.root.__getattr__(\"%s\")' % root
            rawdata = eval(
                command +
                '.scan_data.data_%s.read()' % nxs_dataset)  # xpad images
            delta = eval(
                'f.root.%s%d.DIFFABS.__getattr__(\'D13-1-CX1__EX__DIF.1-DELTA__#1\').raw_value.read()'
                % (nxs_prefix, nxs_index))
            gamma = 0.0  # eval('f.root.%s%d.DIFFABS.__getattr__(\'D13-1-CX1__EX__DIF.1-GAMMA__#1\').raw_value.read()' % (nxs_prefix, nxs_index))
            f.close()
            if stack == 'first':
                image = rawdata[0, :, :]
            elif stack == 'median':
                image = np.median(rawdata, axis=0)
            self.data = image
            print(self.data.shape)
            self.compute_corrected_image()
        if self.orientation == 'vertical':
            self.data = self.data.transpose()
            self.corr_data = self.corr_data.transpose()
            print('transposing data, shape is', self.corr_data.shape)
        if nxs_update_geometry:
            self.compute_TwoTh_Psi_arrays(diffracto_delta=delta,
                                          diffracto_gamma=gamma)
Exemplo n.º 2
0
 def load_image(self, image_path):
     print('loading image %s' % image_path)
     self.image_path = image_path
     if image_path.endswith('.tif'):
         self.data = TiffFile(image_path).asarray().T.astype(np.float32)
     elif image_path.endswith('.raw'):
         self.data = HST_read(self.image_path, data_type=self.data_type,
                              dims=(self.get_size_px()[0], self.get_size_px()[1], 1))[:, :, 0].astype(np.float32)
     else:
         print('unrecognized file format: %s' % image_path)
         return None
     assert self.data.shape == self.size
     self.compute_corrected_image()
Exemplo n.º 3
0
 def OnLoadImage(self, im_file):
     self.path = im_file
     print 'self.path=', self.path
     # read diffraction image
     if self.path.endswith('.edf'):
         # self.im = edf_readf(im_file, 2300)
         from scipy.signal import medfilt2d
         self.im = medfilt2d(edf_readf(im_file, 2300), 5)
         for i in range(2300):
             for j in range(2300):
                 if self.im[i, j] > 12000.: self.im[i, j] = 12000.
     elif self.path.endswith('.dat'):
         self.im = np.genfromtxt(im_file)
     else:
         # self.im = rawmar_read(im_file, 2300)
         from pymicro.file.file_utils import HST_read
         self.im = HST_read(im_file,
                            data_type=np.uint16,
                            dims=(2048, 2048, 1))[:, :, 0]
     self.statusbar.SetStatusText('Image loaded from %s ' % self.path)
Exemplo n.º 4
0
import os, numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt, cm
from pymicro.file.file_utils import HST_read, HST_write, HST_info

data_dir = '../../examples/data'
scan_name = 'steel_431x431x246_uint8'
scan_path = os.path.join(data_dir, scan_name + '.raw')

print('reading volume...')
data = HST_read(scan_path, header_size=0)
plt.figure(1, figsize=(10, 5))
plt.subplot(121)
plt.imshow(data[:, :, 87].transpose(), interpolation='nearest', cmap=cm.gray)
print('rotating volume...')
data = ndimage.rotate(data, 15.5, axes=(1, 0), reshape=False)
plt.subplot(122)
plt.imshow(data[:, :, 87].transpose(), interpolation='nearest', cmap=cm.gray)
plt.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)
plt.savefig(scan_name + '_data.png')

print('binarizing volume...')
data_bin = np.where(np.greater(data, 100), 0, 255).astype(np.uint8)

print('labeling cavities...')
label_im, nb_labels = ndimage.label(data_bin)

plt.figure(2, figsize=(10, 5))
plt.subplot(121)
plt.imshow(data_bin[:, :, 87].transpose(), interpolation='nearest', cmap=cm.gray)
plt.subplot(122)
Exemplo n.º 5
0
data_dir = '../data'
scan = 'grain1_112x112x121_uint8.raw'
im_file = os.path.join(data_dir, scan)

# Create the 3D scene
base_name = os.path.splitext(__file__)[0]
s3d = Scene3D(display=False,
              ren_size=(800, 800),
              name=base_name,
              background=black)

# create a python Grain object from the image data
orientation = Orientation.from_rodrigues(np.array([0.3889, -0.0885, 0.3268]))
grain = Grain(1, orientation)
grain_data = HST_read(im_file,
                      header_size=0,
                      autoparse_filename=True,
                      verbose=True)
grain.position = ndimage.measurements.center_of_mass(grain_data, grain_data)
print('grain position: %s' % str(grain.position))
grain.volume = ndimage.measurements.sum(grain_data)  # label is 1.0 here
grain.add_vtk_mesh(grain_data, contour=False)

print('adding bounding box')
grain_bbox = box_3d(size=np.shape(grain_data), line_color=white)
print('adding grain with slip planes')

z_offsets = np.linspace(-50, 50, 6, endpoint=True)
print(z_offsets)
plane_origins = np.zeros((len(z_offsets), 3), dtype=float)
plane_origins[:, 2] = z_offsets
Exemplo n.º 6
0
import os, numpy as np
from pymicro.xray.detectors import Mar165
from pymicro.file.file_utils import HST_read
from matplotlib import pyplot as plt, cm

if __name__ == '__main__':
    mar = Mar165()  # create a mar object
    mar.ucen = 981  # position of the direct beam on the x axis
    mar.vcen = 1060  # position of the direct beam on the y axis
    mar.calib = 495. / 15.  # identified on (111) ring of CeO2 powder
    mar.correction = 'bg'
    mar.compute_TwoTh_Psi_arrays()

    # load background for correction
    mar.bg = HST_read('../data/c1_exptime_bgair_5.raw',
                      data_type=np.uint16,
                      dims=(2048, 2048, 1))[:, :, 0].astype(np.float32)
    # load image
    mar.load_image('../data/c1_exptime_air_5.raw')

    image_name = os.path.splitext(__file__)[0] + '.png'
    print 'writting %s' % image_name
    plt.imsave(image_name, mar.corr_data, vmin=0, vmax=2000)

    from matplotlib import image

    image.thumbnail(image_name, 'thumb_' + image_name, scale=200. / 2048)
from pymicro.crystal.microstructure import Microstructure

if __name__ == '__main__':
    '''
    This example first demonstrate how to plot a slice of a 3d image. Here
    we use a custom random colormap to display grains nicely.
    The example also shows how to modify the coordinate formatter to
    display the pixel value when moving the mouse above the plotted image.
    Run this example interactively to try it.
    '''
    display = False
    data_dir = '../data'
    scan_name = 'pure_Ti_216x216x141_uint16.raw'
    scan_path = os.path.join(data_dir, scan_name)
    # read only the first slice of the volume and make it a 2d array
    data = HST_read(scan_path, autoparse_filename=True, zrange=range(0, 1), verbose=True)[:, :, 0]

    rand_cmap = Microstructure.rand_cmap(N=2048, first_is_black=True)
    fig, ax = plt.subplots()
    ax = AxShowPixelValue(ax)
    ax.imshow(data.T, cmap=rand_cmap, interpolation='nearest', origin='upper')

    image_name = os.path.splitext(__file__)[0] + '.png'
    plt.savefig(image_name)
    print 'writting %s' % image_name

    from matplotlib import image

    image.thumbnail(image_name, 'thumb_' + image_name, 0.2)

    # display the plot in interactive mode
Exemplo n.º 8
0
from pymicro.file.file_utils import HST_read
from pymicro.view.vtk_utils import *
from pymicro.view.vtk_anim import vtkAnimationScene, vtkRotateActorAroundZAxis
from pymicro.crystal.lattice import HklPlane
from pymicro.crystal.microstructure import Orientation, Grain

from pymicro.examples import PYMICRO_EXAMPLES_DATA_DIR

data_dir = PYMICRO_EXAMPLES_DATA_DIR
scan = 'grain1_112x112x121_uint8.raw'
im_file = os.path.join(data_dir, scan)

print('create a python Grain object')
orientation = Orientation.from_rodrigues(np.array([0.3889, -0.0885, 0.3268]))
grain = Grain(1, orientation)
grain_data = HST_read(im_file, autoparse_filename=True, verbose=True)
grain.position = ndimage.measurements.center_of_mass(grain_data, grain_data)
grain.volume = ndimage.measurements.sum(grain_data)  # label is 1.0 here
grain.add_vtk_mesh(grain_data, contour=False)
# grain.save_vtk_repr() # save the grain mesh in vtk format

print('adding bounding box')
grain_bbox = box_3d(size=np.shape(grain_data), line_color=white)

print('adding grain with slip planes')
p1 = HklPlane(1, 1, 1)
p2 = HklPlane(1, 1, -1)
hklplanes = [p1]
grain_with_planes = add_grain_to_3d_scene(grain, hklplanes, show_orientation=True)
tr = vtk.vtkTransform()
tr.Translate(grain.position)
Exemplo n.º 9
0
from pymicro.view.vtk_utils import show_grains, box_3d, axes_actor, setup_camera, show_grains

if __name__ == '__main__':
    '''
    Create a 3d scene showing the grain map of a polycrystal. Each grain
    is colored with a random color.
    '''

    # create the 3D scene
    base_name = os.path.splitext(__file__)[0]
    s3d = Scene3D(display=False, ren_size=(800, 800), name=base_name)

    data_dir = '../data'
    scan_name = 'pure_Ti_216x216x141_uint16.raw'
    scan_path = os.path.join(data_dir, scan_name)
    data = HST_read(scan_path, autoparse_filename=True)
    size = data.shape
    print 'done reading, volume size is ', size

    # add all the grains
    grains = show_grains(data)
    s3d.add(grains)

    # add outline
    outline = box_3d(size=size, line_color=(0., 0., 0.))
    s3d.add(outline)

    # add axes actor
    axes = axes_actor(0.5 * size[0], fontSize=60)
    s3d.add(axes)
Exemplo n.º 10
0
from pymicro.file.file_utils import HST_info, HST_read

if __name__ == '__main__':
    '''
    Create a 3d scene showing tomographic data of a damaged PA6 sample.
    A map_data_wit_clip filter is used to display part of the interior in 3d.
    '''
    # Create the 3D scene
    base_name = os.path.splitext(__file__)[0]
    s3d = Scene3D(display=False, ren_size=(800, 800), name=base_name)

    # load the data
    data_dir = '../data'
    scan_name = 'pa6_teg11_e_crop.raw'
    scan_path = os.path.join(data_dir, scan_name)
    data = HST_read(scan_path, data_type='uint8', verbose=True)

    print 'adding the main actor'
    actor = map_data_with_clip(data, cell_data=True)
    actor.GetProperty().SetSpecular(.4)
    actor.GetProperty().SetSpecularPower(10)
    s3d.add(actor)

    print 'adding bounding box'
    outline = box_3d(size=data.shape)
    outline.GetProperty().SetColor(black)
    s3d.add(outline)

    print 'adding XYZ axes'
    axes = axes_actor(length=100, fontSize=60)
    axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetColor(grey)