Beispiel #1
0
 def test_savetiff(self):
     testfile = path.join(thisdir, 'coretestdata', 'testsave.tiff')
     #create a few different data types
     testb = ImageArray(np.zeros((4, 5), dtype=bool))  #bool
     testb[0, :] = True
     testui = ImageArray(np.arange(20).reshape(4, 5))  #int32
     testi = ImageArray(np.copy(testui) - 10)
     testf = ImageArray(np.linspace(-1, 1, 20).reshape(4, 5))  #float64
     for im in [testb, testui, testi, testf]:
         im['a'] = [1, 2, 3]
         im['b'] = 'abc'  #add some test metadata
         im.filename = testfile
         im.save()
         n = ImageArray(testfile)
         self.n = n
         self.assertTrue(
             all([n['a'][i] == im['a'][i] for i in range(len(n['a']))]))
         self.assertTrue(n['b'] == im['b'])
         self.assertTrue(
             'ImageArray.dtype'
             in n.metadata.keys())  #check the dtype metdata got added
         self.assertTrue(im.dtype == n.dtype)  #check the datatype
         self.im = im
         self.n = n
         self.assertTrue(np.allclose(im, n))  #check the data
Beispiel #2
0
 def setUp(self):
     #random array shape 3,4
     self.arr = np.array([[0.41674764, 0.66100043, 0.91755303, 0.33796703],
                          [0.06017535, 0.1440342, 0.34441777, 0.9915282],
                          [0.2984083, 0.9167951, 0.73820304, 0.7655299]])
     self.imarr = ImageArray(np.copy(self.arr))  #ImageArray object
     self.imarrfile = ImageArray(
         os.path.join(thisdir, 'coretestdata/im1_annotated.png'))
Beispiel #3
0
 def test_filename(self):
     im = ImageArray(np.linspace(0, 1, 12).reshape(3, 4))
     fpath = os.path.join(thisdir, 'coretestdata/im1_annotated.png')
     self.assertTrue(os.path.normpath(self.imarrfile.filename)\
                     == os.path.normpath(fpath))
     im = ImageArray(np.linspace(0, 1, 12).reshape(3, 4))
     im['Loaded from']
     im.filename
     self.assertTrue(im.filename == '',
                     '{}, {}'.format(self.imarr.shape, im.filename))
Beispiel #4
0
 def test_load_kwargs(self):
     #metadata keyword arg
     t = ImageArray(self.arr, metadata={'a': 5, 'b': 7})
     self.assertTrue('a' in t.metadata.keys() and 'b' in t.metadata.keys())
     self.assertTrue(t.metadata['a'] == 5)
     #asfloat
     t = ImageArray(np.arange(12).reshape(3, 4), asfloat=True)
     self.assertTrue(t.dtype == np.float64, 'Initialising asfloat failed')
     self.assertTrue('Loaded from' in t.metadata.keys(),
                     'Loaded from should always be in metadata')
 def setUp(self):
     self.a = ImageArray(join(thisdir,
                              'coretestdata/im2_noannotations.png'))
     self.a1 = ImageArray(join(thisdir, 'coretestdata/im1_annotated.png'))
     self.a2 = STXMImage(
         join(thisdir, "..", "..", "..", "sample-data",
              "Sample_Image_2017-10-15_100.hdf5"))
     self.a3 = STXMImage(
         join(thisdir, "..", "..", "..", "sample-data",
              "Sample_Image_2017-10-15_101.hdf5"))
Beispiel #6
0
 def test_load_from_png(self):
     subpath = os.path.join("coretestdata", "im1_annotated.png")
     fpath = os.path.join(thisdir, subpath)
     anim = ImageArray(fpath)
     self.assertTrue(
         os.path.normpath(anim.metadata['Loaded from']) == os.path.normpath(
             fpath))
     cwd = os.getcwd()
     os.chdir(thisdir)
     anim = ImageArray(subpath)
     #check full path is in loaded from metadata
     self.assertTrue(
         os.path.normpath(
             anim.metadata['Loaded from']) == os.path.normpath(fpath),
         'Full path not in metadata: {}'.format(anim["Loaded from"]))
     os.chdir(cwd)
Beispiel #7
0
 def test_load_from_ImageFile(self):
     #uses the ImageFile.im attribute to set up ImageArray. Memory overlaps
     imfi = ImageFile(self.arr)
     imarr = ImageArray(imfi)
     self.assertTrue(np.array_equal(imarr, imfi.image),
                     'Initialising from ImageFile failed')
     self.assertTrue(shares_memory(imarr, imfi.image))
Beispiel #8
0
 def test_load_from_array(self):
     #from array
     self.assertTrue(np.array_equal(self.imarr, self.arr))
     #int type
     imarr = ImageArray(np.arange(12, dtype="int32").reshape(3, 4))
     self.assertTrue(
         imarr.dtype == np.dtype('int32'),
         "Failed to set correct dtype - actual dtype={}".format(
             imarr.dtype))
Beispiel #9
0
    def switch_index(self, saturation_end=True, saturation_value=True):
        """Given a stack of boolean masks representing a hystersis loop find the stack index of the saturation field for each pixel.

        Take the final mask as all switched (or the first mask if saturation_end
        is False). Work back through the masks taking the first time a pixel
        switches as its coercive field (ie the last time it switches before
        reaching saturation).
        Elements that start switched at the lowest measured field or never
        switch are given a zero index.

        At the moment it's set up to expect masks to be false when the sample is saturated
        at a high field

        Keyword Arguments:
            saturation_end(bool):
                True if the last image is closest to the fully saturated state.
                False if you want the first image
            saturation_value(bool):
                if True then a pixel value True means that switching has occured
                (ie magnetic saturation would be all True)

        Returns:
            switch_ind: MxN ndarray of int
                index that each pixel switches at
            switch_progession: MxNx(P-1) ndarray of bool
                stack of masks showing when each pixel saturates

        """
        ms = self.clone
        if not saturation_end:
            ms = ms.reverse()
        # arr1 = ms[0].astype(float) #find out whether True is at begin or end
        # arr2 = ms[-1].astype(float)
        # if np.average(arr1)>np.average(arr2): #OK so it's bright at the start
        if not saturation_value:
            self.imarray = np.invert(
                ms.imarray)  # Now it's bright (True) at end
        switch_ind = np.zeros(ms[0].shape, dtype=int)
        switch_prog = self.clone
        switch_prog.imarray = np.zeros(self.shape, dtype=bool)
        del switch_prog[-1]
        for m in reversed(range(len(ms) - 1)):  # go from saturation backwards
            already_done = np.copy(switch_ind).astype(
                dtype=bool)  # only change switch_ind if it hasn't already
            condition = np.logical_and(not ms[m], ms[m + 1])
            condition = np.logical_and(condition, np.invert(already_done))
            condition = [condition, np.logical_not(condition)]
            choice = [np.ones(switch_ind.shape) * m,
                      switch_ind]  # index or leave as is
            switch_ind = np.select(condition, choice)
            switch_prog[m] = already_done
        if not saturation_end:
            switch_ind = -switch_ind + len(self) - 1  # should check this!
            switch_prog.reverse()
        switch_ind = ImageArray(switch_ind.astype(int))
        return switch_ind, switch_prog
 def test_save(self):
     testfile = path.join(thisdir, 'coretestdata', 'testsave.png')
     keys = self.imarr.keys()
     self.imarr.save(filename=testfile)
     load = ImageArray(testfile, asfloat=True)
     #del load["Loaded from"]
     self.assertTrue(all([k in keys for k in load.keys()]),
                     'problem saving metadata')
     self.assertTrue(np.allclose(self.imarr, load, atol=0.001))
     os.remove(testfile)  #tidy up
Beispiel #11
0
 def test_user_attributes(self):
     self.imarr.abc = 'new att'
     self.assertTrue(hasattr(self.imarr, 'abc'))
     t = ImageArray(self.imarr)
     self.assertTrue(hasattr(t, 'abc'), 'problem copying new attributes')
     t = self.imarr.view(
         ImageArray)  #check array_finalize copies attribute over
     self.assertTrue(hasattr(t, 'abc'))
     t = self.imarr * np.random.random(self.imarr.shape)
     self.assertTrue(isinstance(t, ImageArray), 'problem with ufuncs')
     self.assertTrue(hasattr(t, 'abc'), "Ufunc lost attribute!")
Beispiel #12
0
 def test_save(self):
     testfile = path.join(thisdir, 'coretestdata', 'testsave')
     ext = ['.png', '.npy']
     keys = self.imarr.keys()
     for e in ext:
         self.imarr.save(filename=testfile + e)
         load = ImageArray(testfile + e)
         self.assertTrue(all([k in keys for k in load.keys()]),
                         'problem saving metadata')
         if e == '.npy':
             #tolerance is really poor for png whcih savees in 8bit format
             self.assertTrue(np.allclose(self.imarr, load),
                             'data not the same for extension {}'.format(e))
         os.remove(testfile + e)  #tidy up
Beispiel #13
0
 def test_other_funcs(self):
     """test imagefuncs add ons. the functions themselves are not checked
     and should include a few examples in the doc strings for testing"""
     self.assertTrue(hasattr(self.imarr, 'do_nothing'),
                     'imagefuncs not being added to dir')
     self.assertTrue(hasattr(self.imarr, 'img_as_float'),
                     'skimage funcs not being added to dir')
     im = self.imarr.do_nothing()  #see if it can run
     self.assertTrue(np.allclose(im, self.imarr), 'imagefuncs not working')
     self.assertFalse(shares_memory(im, self.imarr),
                      'imagefunc failed to clone')
     im0 = ImageArray(np.linspace(0, 1, 12).reshape(3, 4))
     im1 = im0.clone * 5
     im2 = im1.rescale_intensity()  #test skimage
     self.assertTrue(np.allclose(im2, im0), 'skimage func failed')
     self.assertFalse(shares_memory(im2, im1), 'skimage failed to clone')
     im3 = im1.exposure__rescale_intensity()  #test call with module name
     self.assertTrue(np.allclose(im3, im0),
                     'skimage call with module name failed')
Beispiel #14
0
 def index_to_field(self, index_map):
     """Convert an image of index values into an image of field values"""
     fieldvals = np.take(self.fields, index_map)
     return ImageArray(fieldvals)
Beispiel #15
0
def _load_ImageArray(f, **kargs):
    """Simple meothd to load an image array."""
    kargs.pop("img_num", None)
    return ImageArray(f, **kargs)
Beispiel #16
0
 def test_load_no_args(self):
     #Should be a 2d empty array
     t = ImageArray()
     self.assertTrue(len(t.shape) == 2)
     self.assertTrue(t.size == 0)
Beispiel #17
0
 def test_load_1d_data(self):
     t = ImageArray(np.arange(10) / 10.0)
     self.assertTrue(len(t.shape) == 2)  #converts to 2d
Beispiel #18
0
 def test_load_from_list(self):
     t = ImageArray([[1, 3], [3, 2], [4, 3]])
     self.assertTrue(np.array_equal(t, np.array([[1, 3], [3, 2], [4, 3]])),
                     'Initialising from list failed')
 def setUp(self):
     self.a = ImageArray(join(thisdir,
                              'coretestdata/im2_noannotations.png'))
     self.a1 = ImageArray(join(thisdir, 'coretestdata/im1_annotated.png'))
Beispiel #20
0
 def test_load_from_ImageArray(self):
     #from ImageArray
     t = ImageArray(self.imarr)
     self.assertTrue(shares_memory(self.imarr, t),
                     'no overlap on creating ImageArray from ImageArray')
Beispiel #21
0
 def testload(arg):
     ImageArray(arg)