コード例 #1
0
ファイル: workspace.py プロジェクト: 0x00B1/CellProfiler
    def get_module_figure(self, module, image_set_number, parent=None):
        """Create a CPFigure window or find one already created"""
        import cellprofiler.gui.cpfigure as cpf
        import cellprofiler.measurements as cpmeas

        # catch any background threads trying to call display functions.
        assert not self.__in_background
        window_name = cpf.window_name(module)
        if self.measurements.has_feature(cpmeas.EXPERIMENT,
                                         cpmeas.M_GROUPING_TAGS):
            group_number = self.measurements[
                cpmeas.IMAGE, cpmeas.GROUP_NUMBER, image_set_number]
            group_index = self.measurements[
                cpmeas.IMAGE, cpmeas.GROUP_INDEX, image_set_number]
            title = "%s #%d, image cycle #%d, group #%d, group index #%d" % (
                module.module_name, module.module_num, image_set_number,
                group_number, group_index)
        else:
            title = "%s #%d, image cycle #%d" % (module.module_name,
                                                 module.module_num,
                                                 image_set_number)

        if self.__create_new_window:
            figure = cpf.CPFigureFrame(parent or self.__frame,
                                       name=window_name,
                                       title=title)
        else:
            figure = cpf.create_or_find(parent or self.__frame,
                                        name=window_name,
                                        title=title)

        if not figure in self.__windows_used:
            self.__windows_used.append(figure)

        return figure
コード例 #2
0
 def test_02_02_show_pixel_data_rgb(self):
     '''Make sure the values reported by show_pixel_data are the raw image
     values for RGB images.'''
     image = np.zeros((100, 100, 3))
     for y in range(image.shape[0]):
         image[y,:,:] = y / 200.0
     image[:,:,1] = image[:,:,1] / 2.
     image[:,:,2] = image[:,:,2] / 4.
     my_frame = cpfig.create_or_find(None, -1, subplots=(1,1),
                                     name="test_02_02_show_pixel_data_rgb")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=True)
     
     evt = matplotlib.backend_bases.MouseEvent('motion_notify_event',
                                               ax.figure.canvas, 
                                               x=0, y=10)
     evt.xdata = 0
     evt.ydata = 10
     evt.inaxes = my_frame.subplot(0, 0)
     my_frame.on_mouse_move_show_pixel_data(evt, 0, 0, 0, 0)
     expected = ["Red: %.4f"%(evt.ydata / 200.0),
                 "Green: %.4f"%(evt.ydata / 200.0 / 2.),
                 "Blue: %.4f"%(evt.ydata / 200.0 / 4.)]
     for field in expected:
         assert field in [str(f) for f in my_frame.status_bar.GetFields()], 'Did not find "%s" in StatusBar fields'%(field)
     my_frame.Destroy()
コード例 #3
0
ファイル: workspace.py プロジェクト: anntzer/CellProfiler
    def get_module_figure(self, module, image_set_number, parent=None):
        """Create a CPFigure window or find one already created"""
        import cellprofiler.gui.cpfigure as cpf

        # catch any background threads trying to call display functions.
        assert not self.__in_background

        window_name = cpf.window_name(module)
        title = "%s #%d, image cycle #%d" % (module.module_name,
                                             module.module_num,
                                             image_set_number)

        if self.__create_new_window:
            figure = cpf.CPFigureFrame(parent or self.__frame,
                                       name=window_name,
                                       title=title)
        else:
            figure = cpf.create_or_find(parent or self.__frame,
                                        name=window_name,
                                        title=title)

        if not figure in self.__windows_used:
            self.__windows_used.append(figure)

        return figure
コード例 #4
0
    def test_02_02_show_pixel_data_rgb(self):
        '''Make sure the values reported by show_pixel_data are the raw image
        values for RGB images.'''
        image = np.zeros((100, 100, 3))
        for y in range(image.shape[0]):
            image[y, :, :] = y / 200.0
        image[:, :, 1] = image[:, :, 1] / 2.
        image[:, :, 2] = image[:, :, 2] / 4.
        my_frame = cpfig.create_or_find(None,
                                        -1,
                                        subplots=(1, 1),
                                        name="test_02_02_show_pixel_data_rgb")
        ax = my_frame.subplot_imshow(0, 0, image, normalize=True)

        evt = matplotlib.backend_bases.MouseEvent('motion_notify_event',
                                                  ax.figure.canvas,
                                                  x=0,
                                                  y=10)
        evt.xdata = 0
        evt.ydata = 10
        evt.inaxes = my_frame.subplot(0, 0)
        my_frame.on_mouse_move_show_pixel_data(evt, 0, 0, 0, 0)
        expected = [
            "Red: %.4f" % (evt.ydata / 200.0),
            "Green: %.4f" % (evt.ydata / 200.0 / 2.),
            "Blue: %.4f" % (evt.ydata / 200.0 / 4.)
        ]
        for field in expected:
            assert field in [
                str(f) for f in my_frame.status_bar.GetFields()
            ], 'Did not find "%s" in StatusBar fields' % (field)
        my_frame.Destroy()
コード例 #5
0
    def test_02_01_show_pixel_data(self):
        '''Make sure the values reported by show_pixel_data are the raw image
        values for grayscale images.'''
        image = np.zeros((100, 100))
        for y in range(image.shape[0]):
            image[y, :] = y / 200.0
        my_frame = cpfig.create_or_find(None,
                                        -1,
                                        subplots=(1, 1),
                                        name="test_02_01_show_pixel_data")
        ax = my_frame.subplot_imshow(0, 0, image, normalize=True)

        evt = matplotlib.backend_bases.MouseEvent('motion_notify_event',
                                                  ax.figure.canvas,
                                                  x=0,
                                                  y=10)
        evt.xdata = 0
        evt.ydata = 10
        evt.inaxes = my_frame.subplot(0, 0)
        my_frame.on_mouse_move_show_pixel_data(evt, 0, 0, 0, 0)
        expected = "Intensity: %.4f" % (evt.ydata / 200.0)
        assert expected in [
            str(f) for f in my_frame.status_bar.GetFields()
        ], 'Did not find "%s" in StatusBar fields' % (expected)
        my_frame.Destroy()
コード例 #6
0
    def create_or_find_figure(self,
                              title=None,
                              subplots=None,
                              window_name=None):
        """Create a matplotlib figure window or find one already created"""
        import cellprofiler.gui.cpfigure as cpf

        # catch any background threads trying to call display functions.
        assert not self.__in_background

        if title == None:
            title = self.__module.module_name

        if window_name == None:
            window_name = cpf.window_name(self.__module)

        if self.__create_new_window:
            figure = cpf.CPFigureFrame(self,
                                       title=title,
                                       name=window_name,
                                       subplots=subplots)
        else:
            figure = cpf.create_or_find(self.__frame,
                                        title=title,
                                        name=window_name,
                                        subplots=subplots)
        if not figure in self.__windows_used:
            self.__windows_used.append(figure)
        return figure
コード例 #7
0
    def get_module_figure(self, module, image_set_number, parent=None):
        """Create a CPFigure window or find one already created"""
        import cellprofiler.gui.cpfigure as cpf
        import cellprofiler.measurements as cpmeas

        # catch any background threads trying to call display functions.
        assert not self.__in_background
        window_name = cpf.window_name(module)
        if self.measurements.has_feature(cpmeas.EXPERIMENT,
                                         cpmeas.M_GROUPING_TAGS):
            group_number = self.measurements[cpmeas.IMAGE, cpmeas.GROUP_NUMBER,
                                             image_set_number]
            group_index = self.measurements[cpmeas.IMAGE, cpmeas.GROUP_INDEX,
                                            image_set_number]
            title = "%s #%d, image cycle #%d, group #%d, group index #%d" % (
                module.module_name, module.module_num, image_set_number,
                group_number, group_index)
        else:
            title = "%s #%d, image cycle #%d" % (
                module.module_name, module.module_num, image_set_number)

        if self.__create_new_window:
            figure = cpf.CPFigureFrame(parent or self.__frame,
                                       name=window_name,
                                       title=title)
        else:
            figure = cpf.create_or_find(parent or self.__frame,
                                        name=window_name,
                                        title=title)

        if not figure in self.__windows_used:
            self.__windows_used.append(figure)

        return figure
コード例 #8
0
    def create_or_find_figure(self,title=None,subplots=None,window_name = None):
        """Create a matplotlib figure window or find one already created"""
        import cellprofiler.gui.cpfigure as cpf

        # catch any background threads trying to call display functions.
        assert not self.__in_background 

        if title==None:
            title=self.__module.module_name
            
        if window_name == None:
            window_name = cpf.window_name(self.__module)
            
        if self.__create_new_window:
            figure = CPFigureFrame(self, 
                                   title=title,
                                   name = window_name,
                                   subplots = subplots)
        else:
            figure = cpf.create_or_find(self.__frame, title = title, 
                                        name = window_name, 
                                        subplots = subplots)
        if not figure in self.__windows_used:
            self.__windows_used.append(figure)
        return figure
コード例 #9
0
 def test_01_01_imshow_raw(self):
     """Make sure the image drawn by imshow matches the input image."""
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y, :] = y / 200.0
     my_frame = cpfig.create_or_find(self.frame, -1, subplots=(1, 1), name="test_01_01_imshow_raw")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     # assert (((ax.get_array()-image) < 0.000001).all()), 'Monochrome input image did not match subplot image.'
     my_frame.Destroy()
コード例 #10
0
 def test_01_02_imshow_raw_rgb(self):
     """Make sure the image drawn by imshow matches the input RGB image."""
     image = np.zeros((100, 100, 3))
     for y in range(image.shape[0]):
         image[y, :, :] = y / 200.0
     my_frame = cpfig.create_or_find(None, -1, subplots=(1, 1), name="test_01_02_imshow_raw_rgb")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     # shown_im = ax.get_array().astype(float) / 255.0
     # np.testing.assert_almost_equal(shown_im, image, decimal=2)
     my_frame.Destroy()
コード例 #11
0
 def test_01_01_imshow_raw(self):
     '''Make sure the image drawn by imshow matches the input image.'''
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y,:] = y / 200.0
     my_frame = cpfig.create_or_find(self.frame, -1, subplots=(1,1), 
                                     name="test_01_01_imshow_raw")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     # assert (((ax.get_array()-image) < 0.000001).all()), 'Monochrome input image did not match subplot image.'
     my_frame.Destroy()
コード例 #12
0
    def test_03_02_menu_order2(self):
        '''Make sure that the subplots submenus are presented in the right order
        after they are redrawn as a result of menu handlers 
        (e.g. change_contrast)'''
        f = cpfig.create_or_find(None,
                                 -1,
                                 subplots=(2, 2),
                                 name="test_03_02_menu_order2")

        img = np.random.uniform(.5, .6, size=(5, 5, 3))

        f.subplot_histogram(0, 0, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_imshow(0, 1, img, "rgb2")
        f.subplot_imshow(1, 1, img, "rgb3")

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s' % (i + 1)

        menu = f.get_imshow_menu((1, 0))
        for item in menu.MenuItems:
            if item.Label == 'Image contrast':
                for item in item.SubMenu.MenuItems:
                    if item.Label == 'Raw':
                        event = wx.PyCommandEvent(wx.EVT_MENU.typeId, item.Id)
                        f.GetEventHandler().ProcessEvent(event)
                        self.app.ProcessPendingEvents()

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s' % (i + 1)

        menu = f.get_imshow_menu((1, 1))
        for item in menu.MenuItems:
            if item.Label == 'Image contrast':
                for item in item.SubMenu.MenuItems:
                    if item.Label == 'Log normalized':
                        event = wx.PyCommandEvent(wx.EVT_MENU.typeId, item.Id)
                        f.GetEventHandler().ProcessEvent(event)
                        self.app.ProcessPendingEvents()

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s' % (i + 1)

        menu = f.get_imshow_menu((0, 1))
        for item in menu.MenuItems:
            if item.Label == 'Channels':
                for item in item.SubMenu.MenuItems:
                    if item.Label == cpfig.COLOR_NAMES[0]:
                        event = wx.PyCommandEvent(wx.EVT_MENU.typeId, item.Id)
                        f.GetEventHandler().ProcessEvent(event)
                        self.app.ProcessPendingEvents()

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s' % (i + 1)
        f.Destroy()
コード例 #13
0
 def test_01_02_imshow_raw_rgb(self):
     '''Make sure the image drawn by imshow matches the input RGB image.'''
     image = np.zeros((100, 100, 3))
     for y in range(image.shape[0]):
         image[y,:,:] = y / 200.0
     my_frame = cpfig.create_or_find(None, -1, subplots=(1,1),
                                     name = "test_01_02_imshow_raw_rgb")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     # shown_im = ax.get_array().astype(float) / 255.0
     # np.testing.assert_almost_equal(shown_im, image, decimal=2)
     my_frame.Destroy()
コード例 #14
0
    def test_01_03_imshow_normalized(self):
        """Make sure the image drawn by imshow is normalized."""
        image = np.zeros((100, 100))
        for y in range(image.shape[0]):
            image[y, :] = y / 200.0
        my_frame = cpfig.create_or_find(None, -1, subplots=(1, 1), name="test_01_03_imshow_normalized")
        ax = my_frame.subplot_imshow(0, 0, image, normalize=True)

        normed = (image - np.min(image)) / np.max(image)
        # np.testing.assert_almost_equal(ax.get_array(), normed, decimal=2)
        my_frame.Destroy()
コード例 #15
0
 def test_04_02_no_sharexy_and_sharex_or_y(self):
     """Make sure we can't specify sharex or sharey and sharexy"""
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y, :] = y / 200.0
     my_frame = cpfig.create_or_find(self.frame, -1, subplots=(1, 2), name="test_04_01_sharexy")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     raised = False
     try:
         ax2 = my_frame.subplot_imshow(0, 1, image, normalize=False, sharex=ax, sharexy=ax)
     except Exception, e:
         raised = True
コード例 #16
0
    def test_03_02_menu_order2(self):
        '''Make sure that the subplots submenus are presented in the right order
        after they are redrawn as a result of menu handlers 
        (e.g. change_contrast)'''
        f = cpfig.create_or_find(None, -1, subplots=(2,2),
                                 name="test_03_02_menu_order2")

        img = np.random.uniform(.5, .6, size=(5, 5, 3))
        
        f.subplot_histogram(0, 0, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_imshow(0, 1, img, "rgb2")
        f.subplot_imshow(1, 1, img, "rgb3")
    
        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s'%(i+1)
            
        menu = f.get_imshow_menu((1,0))
        for item in menu.MenuItems:
            if item.Label == 'Image contrast':
                for item in item.SubMenu.MenuItems:
                    if item.Label == 'Raw':
                        event = wx.PyCommandEvent(wx.EVT_MENU.typeId, item.Id)
                        f.GetEventHandler().ProcessEvent(event)
                        self.app.ProcessPendingEvents()
    
        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s'%(i+1)
            
        menu = f.get_imshow_menu((1,1))
        for item in menu.MenuItems:
            if item.Label == 'Image contrast':
                for item in item.SubMenu.MenuItems:
                    if item.Label == 'Log normalized':
                        event = wx.PyCommandEvent(wx.EVT_MENU.typeId, item.Id)
                        f.GetEventHandler().ProcessEvent(event)
                        self.app.ProcessPendingEvents()
    
        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s'%(i+1)
            
        menu = f.get_imshow_menu((0,1))
        for item in menu.MenuItems:
            if item.Label == 'Channels':
                for item in item.SubMenu.MenuItems:
                    if item.Label == cpfig.COLOR_NAMES[0]:
                        event = wx.PyCommandEvent(wx.EVT_MENU.typeId, item.Id)
                        f.GetEventHandler().ProcessEvent(event)
                        self.app.ProcessPendingEvents()

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s'%(i+1)
        f.Destroy()
コード例 #17
0
 def test_01_03_imshow_normalized(self):
     '''Make sure the image drawn by imshow is normalized.'''
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y,:] = y / 200.0
     my_frame = cpfig.create_or_find(None, -1, subplots=(1,1),
                                     name = "test_01_03_imshow_normalized")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=True)
     
     normed = ((image - np.min(image)) / np.max(image))
     # np.testing.assert_almost_equal(ax.get_array(), normed, decimal=2)
     my_frame.Destroy()
コード例 #18
0
    def test_01_04_imshow_normalized_rgb(self):
        """Make sure the RGB image drawn by imshow is normalized."""
        image = np.zeros((100, 100, 3))
        for y in range(image.shape[0]):
            image[y, :, :] = y / 200.0
        my_frame = cpfig.create_or_find(None, -1, subplots=(1, 1), name="test_01_04_imshow_normalized_rgb")
        ax = my_frame.subplot_imshow(0, 0, image, normalize=True)

        normed = (image - np.min(image)) / np.max(image)
        # shown_im = ax.get_array().astype(float) / 255.0
        # np.testing.assert_almost_equal(normed, shown_im, decimal=2)
        my_frame.Destroy()
コード例 #19
0
    def test_01_05_imshow_log_normalized(self):
        """Make sure the image drawn by imshow is log normalized."""
        image = np.zeros((100, 100))
        for y in range(image.shape[0]):
            image[y, :] = y / 200.0
        my_frame = cpfig.create_or_find(None, -1, subplots=(1, 1), name="test_01_05_imshow_log_normalized")
        ax = my_frame.subplot_imshow(0, 0, image, normalize="log")

        (min, max) = (image[image > 0].min(), image.max())
        normed = (np.log(image.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
        # np.testing.assert_almost_equal(normed, ax.get_array(), decimal=2)
        my_frame.Destroy()
コード例 #20
0
    def test_03_01_menu_order(self):
        '''Make sure that the subplots submenus are presented in the right order
        no matter what order they are drawn in.
        Also tests that the order is not affected after calling clf()'''
        f = cpfig.create_or_find(None,
                                 -1,
                                 subplots=(4, 2),
                                 name="test_03_01_menu_order")

        img = np.random.uniform(.5, .6, size=(5, 5, 3))

        f.subplot_histogram(0, 0, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_histogram(2, 0, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(3, 0, img, "rgb2")

        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_histogram(3, 1, [1, 1, 1, 2], 2, title="hist")

        def test_01_01_imshow_raw(self):
            '''Make sure the image drawn by imshow matches the input image.'''
            image = np.zeros((100, 100))
            for y in range(image.shape[0]):
                image[y, :] = y / 200.0
            my_frame = cpfig.create_or_find(self.frame,
                                            -1,
                                            subplots=(1, 1),
                                            name="test_01_01_imshow_raw")
            ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
            # assert (((ax.get_array()-image) < 0.000001).all()), 'Monochrome input image did not match subplot image.'
            my_frame.Destroy()

        f.clf()

        assert len(f.menu_subplots.MenuItems
                   ) == 0, 'Subplot menus should be empty after clf().'

        f.subplot_histogram(3, 1, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_histogram(2, 0, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_imshow(3, 0, img, "rgb2")
        f.subplot_histogram(0, 0, [1, 1, 1, 2], 2, title="hist")

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s' % (i + 1)

        f.Destroy()
コード例 #21
0
 def test_01_05_imshow_log_normalized(self):
     '''Make sure the image drawn by imshow is log normalized.'''
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y,:] = y / 200.0
     my_frame = cpfig.create_or_find(None, -1, subplots=(1,1),
                                     name = "test_01_05_imshow_log_normalized")
     ax = my_frame.subplot_imshow(0, 0, image, normalize='log')
     
     (min, max) = (image[image > 0].min(), image.max())
     normed = (np.log(image.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
     # np.testing.assert_almost_equal(normed, ax.get_array(), decimal=2)
     my_frame.Destroy()
コード例 #22
0
    def test_01_04_imshow_normalized_rgb(self):
        '''Make sure the RGB image drawn by imshow is normalized.'''
        image = np.zeros((100, 100, 3))
        for y in range(image.shape[0]):
            image[y, :, :] = y / 200.0
        my_frame = cpfig.create_or_find(
            None, -1, subplots=(1, 1), name="test_01_04_imshow_normalized_rgb")
        ax = my_frame.subplot_imshow(0, 0, image, normalize=True)

        normed = ((image - np.min(image)) / np.max(image))
        # shown_im = ax.get_array().astype(float) / 255.0
        # np.testing.assert_almost_equal(normed, shown_im, decimal=2)
        my_frame.Destroy()
コード例 #23
0
 def test_01_06_imshow_log_normalized_rgb(self):
     '''Make sure the RGB image drawn by imshow is log normalized.'''
     image = np.zeros((100, 100, 3))
     for y in range(image.shape[0]):
         image[y,:] = y / 200.0
     my_frame = cpfig.create_or_find(None, -1, subplots=(1,1),
                                     name="test_01_06_imshow_log_normalized_rgb")
     ax = my_frame.subplot_imshow(0, 0, image, normalize='log')
     
     (min, max) = (image[image > 0].min(), image.max())
     normed = (np.log(image.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
     # shown_im = ax.get_array().astype(float) / 255.0
     # np.testing.assert_almost_equal(normed, shown_im, decimal=2)
     my_frame.Destroy()
コード例 #24
0
 def test_04_02_no_sharexy_and_sharex_or_y(self):
     '''Make sure we can't specify sharex or sharey and sharexy'''
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y,:] = y / 200.0
     my_frame = cpfig.create_or_find(self.frame, -1, subplots=(1, 2),
                                     name="test_04_01_sharexy")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     raised = False
     try:
         ax2 = my_frame.subplot_imshow(0, 1, image, normalize=False,
                                       sharex=ax, sharexy=ax)
     except Exception, e:
         raised = True
コード例 #25
0
 def test_04_01_sharexy(self):
     """Make sure we can use the sharexy argument."""
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y, :] = y / 200.0
     my_frame = cpfig.create_or_find(self.frame, -1, subplots=(1, 2), name="test_04_01_sharexy")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     ax2 = my_frame.subplot_imshow(0, 1, image, normalize=False, sharexy=ax)
     xgroup = ax.get_shared_x_axes()
     assert ax in xgroup
     assert ax2 in xgroup
     ygroup = ax.get_shared_y_axes()
     assert ax in ygroup
     assert ax2 in ygroup
     my_frame.Destroy()
コード例 #26
0
 def test_04_01_sharexy(self):
     '''Make sure we can use the sharexy argument.'''
     image = np.zeros((100, 100))
     for y in range(image.shape[0]):
         image[y,:] = y / 200.0
     my_frame = cpfig.create_or_find(self.frame, -1, subplots=(1, 2),
                                     name="test_04_01_sharexy")
     ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
     ax2 = my_frame.subplot_imshow(0, 1, image, normalize=False, sharexy=ax)
     xgroup = ax.get_shared_x_axes()
     assert ax in xgroup
     assert ax2 in xgroup
     ygroup = ax.get_shared_y_axes()
     assert ax in ygroup
     assert ax2 in ygroup
     my_frame.Destroy()
コード例 #27
0
    def test_03_01_menu_order(self):
        '''Make sure that the subplots submenus are presented in the right order
        no matter what order they are drawn in.
        Also tests that the order is not affected after calling clf()'''
        f = cpfig.create_or_find(None, -1, subplots=(4,2),
                                 name="test_03_01_menu_order")

        img = np.random.uniform(.5, .6, size=(5, 5, 3))
        
        f.subplot_histogram(0, 0, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_histogram(2, 0, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(3, 0, img, "rgb2")

        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_histogram(3, 1, [1,1,1,2], 2, title="hist")
    
        def test_01_01_imshow_raw(self):
            '''Make sure the image drawn by imshow matches the input image.'''
            image = np.zeros((100, 100))
            for y in range(image.shape[0]):
                image[y,:] = y / 200.0
            my_frame = cpfig.create_or_find(self.frame, -1, subplots=(1,1), 
                                            name="test_01_01_imshow_raw")
            ax = my_frame.subplot_imshow(0, 0, image, normalize=False)
            # assert (((ax.get_array()-image) < 0.000001).all()), 'Monochrome input image did not match subplot image.'
            my_frame.Destroy()
            
        f.clf()

        assert len(f.menu_subplots.MenuItems) == 0, 'Subplot menus should be empty after clf().'
        
        f.subplot_histogram(3, 1, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_histogram(2, 0, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_imshow(3, 0, img, "rgb2")
        f.subplot_histogram(0, 0, [1,1,1,2], 2, title="hist")
    
        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s'%(i+1)
                        
        f.Destroy()
コード例 #28
0
 def on_run(self, event):
     image_set_list = cpi.ImageSetList()
     image_set = image_set_list.get_image_set(0)
     workspace = cpw.Workspace(self.pipeline,
                               self.module,
                               image_set,
                               cpo.ObjectSet(),
                               self.measurements,
                               image_set_list,
                               frame=self)
     self.module.show_window = True  # to make sure it saves display data
     self.module.run_as_data_tool(workspace)
     self.measurements.flush()
     fig = cpf.create_or_find(parent=self,
                              title="%s Output" % (self.module.module_name),
                              name="CellProfiler:DataTool:%s" % (self.module.module_name))
     self.module.display(workspace, fig)
     fig.Refresh()
コード例 #29
0
ファイル: datatoolframe.py プロジェクト: sammac/CellProfiler
 def on_run(self, event):
     image_set_list = cpi.ImageSetList()
     image_set = image_set_list.get_image_set(0)
     workspace = cpw.Workspace(self.pipeline,
                               self.module,
                               image_set,
                               cpo.ObjectSet(),
                               self.measurements,
                               image_set_list,
                               frame=self)
     self.module.show_window = True  # to make sure it saves display data
     self.module.run_as_data_tool(workspace)
     self.measurements.flush()
     fig = cpf.create_or_find(parent=self,
                              title="%s Output" % (self.module.module_name),
                              name="CellProfiler:DataTool:%s" %
                              (self.module.module_name))
     self.module.display(workspace, fig)
     fig.figure.canvas.draw()
コード例 #30
0
    def test_02_01_show_pixel_data(self):
        """Make sure the values reported by show_pixel_data are the raw image
        values for grayscale images."""
        image = np.zeros((100, 100))
        for y in range(image.shape[0]):
            image[y, :] = y / 200.0
        my_frame = cpfig.create_or_find(None, -1, subplots=(1, 1), name="test_02_01_show_pixel_data")
        ax = my_frame.subplot_imshow(0, 0, image, normalize=True)

        evt = matplotlib.backend_bases.MouseEvent("motion_notify_event", ax.figure.canvas, x=0, y=10)
        evt.xdata = 0
        evt.ydata = 10
        evt.inaxes = my_frame.subplot(0, 0)
        my_frame.on_mouse_move_show_pixel_data(evt, 0, 0, 0, 0)
        expected = "Intensity: %.4f" % (evt.ydata / 200.0)
        assert expected in [
            str(f) for f in my_frame.status_bar.GetFields()
        ], 'Did not find "%s" in StatusBar fields' % (expected)
        my_frame.Destroy()
コード例 #31
0
    def test_03_01_menu_order(self):
        '''Make sure that the subplots submenus are presented in the right order
        no matter what order they are drawn in.
        Also tests that the order is not affected after calling clf()'''
        f = cpfig.create_or_find(None,
                                 -1,
                                 subplots=(4, 2),
                                 name="test_03_01_menu_order")

        img = np.random.uniform(.5, .6, size=(5, 5, 3))

        f.subplot_histogram(0, 0, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_histogram(2, 0, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(3, 0, img, "rgb2")

        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_histogram(3, 1, [1, 1, 1, 2], 2, title="hist")

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s' % (i + 1)

        f.clf()

        assert len(f.menu_subplots.MenuItems
                   ) == 0, 'Subplot menus should be empty after clf().'

        f.subplot_histogram(3, 1, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_histogram(2, 0, [1, 1, 1, 2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_imshow(3, 0, img, "rgb2")
        f.subplot_histogram(0, 0, [1, 1, 1, 2], 2, title="hist")

        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s' % (i + 1)

        f.Destroy()
コード例 #32
0
ファイル: test_cpfigure.py プロジェクト: drmono/CellProfiler
    def test_03_01_menu_order(self):
        '''Make sure that the subplots submenus are presented in the right order
        no matter what order they are drawn in.
        Also tests that the order is not affected after calling clf()'''
        f = cpfig.create_or_find(None, -1, subplots=(4,2),
                                 name="test_03_01_menu_order")

        img = np.random.uniform(.5, .6, size=(5, 5, 3))
        
        f.subplot_histogram(0, 0, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_histogram(2, 0, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(3, 0, img, "rgb2")

        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_histogram(3, 1, [1,1,1,2], 2, title="hist")
    
        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s'%(i+1)
            
        f.clf()

        assert len(f.menu_subplots.MenuItems) == 0, 'Subplot menus should be empty after clf().'
        
        f.subplot_histogram(3, 1, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(2, 1, img, "rgb5")
        f.subplot_imshow(0, 1, img, "rgb3")
        f.subplot_imshow(1, 1, img, "rgb4")
        f.subplot_histogram(2, 0, [1,1,1,2], 2, title="hist")
        f.subplot_imshow(1, 0, img, "rgb1")
        f.subplot_imshow(3, 0, img, "rgb2")
        f.subplot_histogram(0, 0, [1,1,1,2], 2, title="hist")
    
        for i, item in enumerate(f.menu_subplots.MenuItems):
            assert item.Label == 'rgb%s'%(i+1)
                        
        f.Destroy()
コード例 #33
0
ファイル: workspace.py プロジェクト: manerotoni/CellProfiler
    def get_module_figure(self, module, image_set_number, parent=None):
        """Create a CPFigure window or find one already created"""
        import cellprofiler.gui.cpfigure as cpf

        # catch any background threads trying to call display functions.
        assert not self.__in_background

        window_name = cpf.window_name(module)
        title = "%s #%d, image cycle #%d" % (
            module.module_name, module.module_num, image_set_number)

        if self.__create_new_window:
            figure = cpf.CPFigureFrame(parent or self.__frame,
                                       name=window_name,
                                       title=title)
        else:
            figure = cpf.create_or_find(parent or self.__frame,
                                        name=window_name,
                                        title=title)

        if not figure in self.__windows_used:
            self.__windows_used.append(figure)

        return figure
コード例 #34
0
    def CheckProgress(self):
        import wx
        ''' Called when the CheckProgress Button is pressed. '''
        # get wells if available, otherwise use imagenumbers
        try:
            nRules = int(self.classifier.nRulesTxt.GetValue())
        except:
            logging.error('Unable to parse number of rules')
            return

        if not self.classifier.UpdateTrainingSet():
            self.PostMessage('Cross-validation canceled.')
            return
        
        db = dbconnect.DBConnect.getInstance()
        groups = [db.get_platewell_for_object(key) for key in self.classifier.trainingSet.get_object_keys()]

        t1 = time()
        dlg = wx.ProgressDialog('Computing cross validation accuracy...', '0% Complete', 100, self.classifier, wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME | wx.PD_CAN_ABORT)        
        base = 0.0
        scale = 1.0

        class StopXValidation(Exception):
            pass

        def progress_callback(amount):
            pct = min(int(100 * (amount * scale + base)), 100)
            cont, skip = dlg.Update(pct, '%d%% Complete'%(pct))
            self.classifier.PostMessage('Computing cross validation accuracy... %s%% Complete'%(pct))
            if not cont:
                raise StopXValidation

        # each round of xvalidation takes about (numfolds * (1 - (1 / num_folds))) time
        step_time_1 = (2.0 * (1.0 - 1.0 / 2.0))
        step_time_2 = (20.0 * (1.0 - 1.0 / 20.0))
        scale = step_time_1 / (10 * step_time_1 + step_time_2)

        xvalid_50 = []

        try:
            for i in range(10):
                # JK - Start Modification
                xvalid_50 += self.XValidate(
                    self.classifier.trainingSet.colnames, nRules, self.classifier.trainingSet.label_matrix,
                    self.classifier.trainingSet.values, 2, groups, progress_callback
                )
                # JK - End Modification

                # each round makes one "scale" size step in progress
                base += scale
            xvalid_50 = sum(xvalid_50) / 10.0

            # only one more step
            scale = 1.0 - base
            # JK - Start Modification
            xvalid_95 = self.XValidate(
                self.classifier.trainingSet.colnames, nRules, self.classifier.trainingSet.label_matrix,
                self.classifier.trainingSet.values, 20, groups, progress_callback
            )
            # JK - End Modification

            dlg.Destroy()
            figure = cpfig.create_or_find(self.classifier, -1, 'Cross-validation accuracy', subplots=(1,1), name='Cross-validation accuracy')
            sp = figure.subplot(0,0)
            sp.clear()
            sp.hold(True)
            sp.plot(range(1, nRules + 1), 1.0 - xvalid_50 / float(len(groups)), 'r', label='50% cross-validation accuracy')
            sp.plot(range(1, nRules + 1), 1.0 - xvalid_95[0] / float(len(groups)), 'b', label='95% cross-validation accuracy')
            chance_level = 1.0 / len(self.classifier.trainingSet.labels)
            sp.plot([1, nRules + 1], [chance_level, chance_level], 'k--', label='accuracy of random classifier')
            sp.legend(loc='lower right')
            sp.set_xlabel('Rule #')
            sp.set_ylabel('Accuracy')
            sp.set_xlim(1, max(nRules,2))
            sp.set_ylim(-0.05, 1.05)
            figure.Refresh()
            self.classifier.PostMessage('Cross-validation complete in %.1fs.'%(time()-t1))
        except StopXValidation:
            dlg.Destroy()
コード例 #35
0
    def run(self, workspace):
        """Run the module on the current data set
        
        workspace - has the current image set, object set, measurements
                    and the parent frame for the application if the module
                    is allowed to display. If the module should not display,
                    workspace.frame is None.
        """
        #
        # The object set holds "objects". Each of these is a container
        # for holding up to three kinds of image labels.
        #
        object_set = workspace.object_set
        #
        # Get the primary objects (the centers to be removed).
        # Get the string value out of primary_object_name.
        #
        primary_objects = object_set.get_objects(
            self.primary_objects_name.value)
        #
        # Get the cleaned-up labels image
        #
        primary_labels = primary_objects.segmented
        #
        # Do the same with the secondary object
        secondary_objects = object_set.get_objects(
            self.secondary_objects_name.value)
        secondary_labels = secondary_objects.segmented
        #
        # If one of the two label images is smaller than the other, we
        # try to find the cropping mask and we apply that mask to the larger
        #
        try:
            if any([
                    p_size < s_size for p_size, s_size in zip(
                        primary_labels.shape, secondary_labels.shape)
            ]):
                #
                # Look for a cropping mask associated with the primary_labels
                # and apply that mask to resize the secondary labels
                #
                secondary_labels = primary_objects.crop_image_similarly(
                    secondary_labels)
                tertiary_image = primary_objects.parent_image
            elif any([
                    p_size > s_size for p_size, s_size in zip(
                        primary_labels.shape, secondary_labels.shape)
            ]):
                primary_labels = secondary_objects.crop_image_similarly(
                    primary_labels)
                tertiary_image = secondary_objects.parent_image
            elif secondary_objects.parent_image != None:
                tertiary_image = secondary_objects.parent_image
            else:
                tertiary_image = primary_objects.parent_image
        except ValueError:
            # No suitable cropping - resize all to fit the secondary
            # labels which are the most critical.
            #
            primary_labels, _ = cpo.size_similarly(secondary_labels,
                                                   primary_labels)
            if secondary_objects.parent_image != None:
                tertiary_image = secondary_objects.parent_image
            else:
                tertiary_image = primary_objects.parent_image
                if tertiary_image is not None:
                    tertiary_image, _ = cpo.size_similarly(
                        secondary_labels, tertiary_image)
        #
        # Find the outlines of the primary image and use this to shrink the
        # primary image by one. This guarantees that there is something left
        # of the secondary image after subtraction
        #
        primary_outline = outline(primary_labels)
        tertiary_labels = secondary_labels.copy()
        primary_mask = np.logical_or(primary_labels == 0, primary_outline)
        tertiary_labels[primary_mask == False] = 0
        #
        # Get the outlines of the tertiary image
        #
        tertiary_outlines = outline(tertiary_labels) != 0
        #
        # Make the tertiary objects container
        #
        tertiary_objects = cpo.Objects()
        tertiary_objects.segmented = tertiary_labels
        tertiary_objects.parent_image = tertiary_image
        #
        # Relate tertiary objects to their parents & record
        #
        child_count_of_secondary, secondary_parents = \
            secondary_objects.relate_children(tertiary_objects)
        child_count_of_primary, primary_parents = \
            primary_objects.relate_children(tertiary_objects)

        if workspace.frame != None:
            import cellprofiler.gui.cpfigure as cpf
            #
            # Draw the primary, secondary and tertiary labels
            # and the outlines
            #
            window_name = "CellProfiler:%s:%d" % (self.module_name,
                                                  self.module_num)
            my_frame = cpf.create_or_find(
                workspace.frame,
                title="IdentifyTertiaryObjects, image cycle #%d" %
                (workspace.measurements.image_set_number),
                name=window_name,
                subplots=(2, 2))

            title = "%s, cycle # %d" % (self.primary_objects_name.value,
                                        workspace.image_set.number + 1)
            my_frame.subplot_imshow_labels(0, 0, primary_labels, title)
            my_frame.subplot_imshow_labels(1,
                                           0,
                                           secondary_labels,
                                           self.secondary_objects_name.value,
                                           sharex=my_frame.subplot(0, 0),
                                           sharey=my_frame.subplot(0, 0))
            my_frame.subplot_imshow_labels(0,
                                           1,
                                           tertiary_labels,
                                           self.subregion_objects_name.value,
                                           sharex=my_frame.subplot(0, 0),
                                           sharey=my_frame.subplot(0, 0))
            my_frame.subplot_imshow_bw(1,
                                       1,
                                       tertiary_outlines,
                                       "Outlines",
                                       sharex=my_frame.subplot(0, 0),
                                       sharey=my_frame.subplot(0, 0))
            my_frame.Refresh()
        #
        # Write out the objects
        #
        workspace.object_set.add_objects(tertiary_objects,
                                         self.subregion_objects_name.value)
        #
        # Write out the measurements
        #
        m = workspace.measurements
        #
        # The parent/child associations
        #
        for parent_objects_name, parents_of, child_count\
         in ((self.primary_objects_name, primary_parents,child_count_of_primary),
             (self.secondary_objects_name, secondary_parents, child_count_of_secondary)):
            m.add_measurement(self.subregion_objects_name.value,
                              cpmi.FF_PARENT % (parent_objects_name.value),
                              parents_of)
            m.add_measurement(
                parent_objects_name.value,
                cpmi.FF_CHILDREN_COUNT % (self.subregion_objects_name.value),
                child_count)
        object_count = np.max(tertiary_labels)
        #
        # The object count
        #
        cpmi.add_object_count_measurements(workspace.measurements,
                                           self.subregion_objects_name.value,
                                           object_count)
        #
        # The object locations
        #
        cpmi.add_object_location_measurements(
            workspace.measurements, self.subregion_objects_name.value,
            tertiary_labels)
        #
        # The outlines
        #
        if self.use_outlines.value:
            out_img = cpi.Image(tertiary_outlines.astype(bool),
                                parent_image=tertiary_image)
            workspace.image_set.add(self.outlines_name.value, out_img)
コード例 #36
0
    def CheckProgress(self):
        import wx
        ''' Called when the CheckProgress Button is pressed. '''
        # get wells if available, otherwise use imagenumbers
        try:
            nRules = int(self.classifier.nRulesTxt.GetValue())
        except:
            logging.error('Unable to parse number of rules')
            return

        if not self.classifier.UpdateTrainingSet():
            self.PostMessage('Cross-validation canceled.')
            return

        db = dbconnect.DBConnect.getInstance()
        groups = [
            db.get_platewell_for_object(key)
            for key in self.classifier.trainingSet.get_object_keys()
        ]

        t1 = time()
        dlg = wx.ProgressDialog(
            'Computing cross validation accuracy...', '0% Complete', 100,
            self.classifier, wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME
            | wx.PD_REMAINING_TIME | wx.PD_CAN_ABORT)
        base = 0.0
        scale = 1.0

        class StopXValidation(Exception):
            pass

        def progress_callback(amount):
            pct = min(int(100 * (amount * scale + base)), 100)
            cont, skip = dlg.Update(pct, '%d%% Complete' % (pct))
            self.classifier.PostMessage(
                'Computing cross validation accuracy... %s%% Complete' % (pct))
            if not cont:
                raise StopXValidation

        # each round of xvalidation takes about (numfolds * (1 - (1 / num_folds))) time
        step_time_1 = (2.0 * (1.0 - 1.0 / 2.0))
        step_time_2 = (20.0 * (1.0 - 1.0 / 20.0))
        scale = step_time_1 / (10 * step_time_1 + step_time_2)

        xvalid_50 = []

        try:
            for i in range(10):
                # JK - Start Modification
                xvalid_50 += self.XValidate(
                    self.classifier.trainingSet.colnames, nRules,
                    self.classifier.trainingSet.label_matrix,
                    self.classifier.trainingSet.values, 2, groups,
                    progress_callback)
                # JK - End Modification

                # each round makes one "scale" size step in progress
                base += scale
            xvalid_50 = sum(xvalid_50) / 10.0

            # only one more step
            scale = 1.0 - base
            # JK - Start Modification
            xvalid_95 = self.XValidate(
                self.classifier.trainingSet.colnames, nRules,
                self.classifier.trainingSet.label_matrix,
                self.classifier.trainingSet.values, 20, groups,
                progress_callback)
            # JK - End Modification

            dlg.Destroy()
            figure = cpfig.create_or_find(self.classifier,
                                          -1,
                                          'Cross-validation accuracy',
                                          subplots=(1, 1),
                                          name='Cross-validation accuracy')
            sp = figure.subplot(0, 0)
            sp.clear()
            sp.hold(True)
            sp.plot(range(1, nRules + 1),
                    1.0 - xvalid_50 / float(len(groups)),
                    'r',
                    label='50% cross-validation accuracy')
            sp.plot(range(1, nRules + 1),
                    1.0 - xvalid_95[0] / float(len(groups)),
                    'b',
                    label='95% cross-validation accuracy')
            chance_level = 1.0 / len(self.classifier.trainingSet.labels)
            sp.plot([1, nRules + 1], [chance_level, chance_level],
                    'k--',
                    label='accuracy of random classifier')
            sp.legend(loc='lower right')
            sp.set_xlabel('Rule #')
            sp.set_ylabel('Accuracy')
            sp.set_xlim(1, max(nRules, 2))
            sp.set_ylim(-0.05, 1.05)
            figure.Refresh()
            self.classifier.PostMessage('Cross-validation complete in %.1fs.' %
                                        (time() - t1))
        except StopXValidation:
            dlg.Destroy()
コード例 #37
0
 def run(self, workspace):
     """Run the module on the current data set
     
     workspace - has the current image set, object set, measurements
                 and the parent frame for the application if the module
                 is allowed to display. If the module should not display,
                 workspace.frame is None.
     """
     #
     # The object set holds "objects". Each of these is a container
     # for holding up to three kinds of image labels.
     #
     object_set = workspace.object_set
     #
     # Get the primary objects (the centers to be removed).
     # Get the string value out of primary_object_name.
     #
     primary_objects = object_set.get_objects(self.primary_objects_name.value)
     #
     # Get the cleaned-up labels image
     #
     primary_labels = primary_objects.segmented
     #
     # Do the same with the secondary object
     secondary_objects = object_set.get_objects(self.secondary_objects_name.value)
     secondary_labels = secondary_objects.segmented
     #
     # If one of the two label images is smaller than the other, we
     # try to find the cropping mask and we apply that mask to the larger
     #
     try:
         if any([p_size < s_size 
                 for p_size,s_size
                 in zip(primary_labels.shape, secondary_labels.shape)]):
             #
             # Look for a cropping mask associated with the primary_labels
             # and apply that mask to resize the secondary labels
             #
             secondary_labels = primary_objects.crop_image_similarly(secondary_labels)
             tertiary_image = primary_objects.parent_image
         elif any([p_size > s_size 
                 for p_size,s_size
                 in zip(primary_labels.shape, secondary_labels.shape)]):
             primary_labels = secondary_objects.crop_image_similarly(primary_labels)
             tertiary_image = secondary_objects.parent_image
         elif secondary_objects.parent_image != None:
             tertiary_image = secondary_objects.parent_image
         else:
             tertiary_image = primary_objects.parent_image
     except ValueError:
         # No suitable cropping - resize all to fit the secondary
         # labels which are the most critical.
         #
         primary_labels, _ = cpo.size_similarly(secondary_labels, primary_labels)
         if secondary_objects.parent_image != None:
             tertiary_image = secondary_objects.parent_image
         else:
             tertiary_image = primary_objects.parent_image
             if tertiary_image is not None:
                 tertiary_image, _ = cpo.size_similarly(secondary_labels, tertiary_image)
     #
     # Find the outlines of the primary image and use this to shrink the
     # primary image by one. This guarantees that there is something left
     # of the secondary image after subtraction
     #
     primary_outline = outline(primary_labels)
     tertiary_labels = secondary_labels.copy()
     primary_mask = np.logical_or(primary_labels == 0,
                                  primary_outline)
     tertiary_labels[primary_mask == False] = 0
     #
     # Get the outlines of the tertiary image
     #
     tertiary_outlines = outline(tertiary_labels)!=0
     #
     # Make the tertiary objects container
     #
     tertiary_objects = cpo.Objects()
     tertiary_objects.segmented = tertiary_labels
     tertiary_objects.parent_image = tertiary_image
     #
     # Relate tertiary objects to their parents & record
     #
     child_count_of_secondary, secondary_parents = \
         secondary_objects.relate_children(tertiary_objects)
     child_count_of_primary, primary_parents = \
         primary_objects.relate_children(tertiary_objects)
     
     if workspace.frame != None:
         import cellprofiler.gui.cpfigure as cpf
         #
         # Draw the primary, secondary and tertiary labels
         # and the outlines
         #
         window_name = "CellProfiler:%s:%d"%(self.module_name,self.module_num)
         my_frame=cpf.create_or_find(workspace.frame, 
                                     title="IdentifyTertiaryObjects, image cycle #%d"%(
             workspace.measurements.image_set_number), 
                                     name=window_name, subplots=(2,2))
         
         title = "%s, cycle # %d"%(self.primary_objects_name.value,
                                   workspace.image_set.number+1)
         my_frame.subplot_imshow_labels(0,0,primary_labels,title)
         my_frame.subplot_imshow_labels(1,0,secondary_labels, 
                                        self.secondary_objects_name.value,
                                        sharex = my_frame.subplot(0,0),
                                        sharey = my_frame.subplot(0,0))
         my_frame.subplot_imshow_labels(0, 1,tertiary_labels, 
                                        self.subregion_objects_name.value,
                                        sharex = my_frame.subplot(0,0),
                                        sharey = my_frame.subplot(0,0))
         my_frame.subplot_imshow_bw(1,1,tertiary_outlines, 
                                    "Outlines",
                                    sharex = my_frame.subplot(0,0),
                                    sharey = my_frame.subplot(0,0))
         my_frame.Refresh()
     #
     # Write out the objects
     #
     workspace.object_set.add_objects(tertiary_objects,
                                      self.subregion_objects_name.value)
     #
     # Write out the measurements
     #
     m = workspace.measurements
     #
     # The parent/child associations
     #
     for parent_objects_name, parents_of, child_count\
      in ((self.primary_objects_name, primary_parents,child_count_of_primary),
          (self.secondary_objects_name, secondary_parents, child_count_of_secondary)):
         m.add_measurement(self.subregion_objects_name.value,
                           cpmi.FF_PARENT%(parent_objects_name.value),
                           parents_of)
         m.add_measurement(parent_objects_name.value,
                           cpmi.FF_CHILDREN_COUNT%(self.subregion_objects_name.value),
                           child_count)
     object_count = np.max(tertiary_labels)
     #
     # The object count
     #
     cpmi.add_object_count_measurements(workspace.measurements,
                                        self.subregion_objects_name.value,
                                        object_count)
     #
     # The object locations
     #
     cpmi.add_object_location_measurements(workspace.measurements,
                                           self.subregion_objects_name.value,
                                           tertiary_labels)
     #
     # The outlines
     #
     if self.use_outlines.value:
         out_img = cpi.Image(tertiary_outlines.astype(bool),
                             parent_image = tertiary_image)
         workspace.image_set.add(self.outlines_name.value, out_img)