예제 #1
0
    def ShowImage(self):

        polygoncolor = (255, 0, 0)
        currpolygoncolor = (255, 255, 0)

        if self.displaymode_choice.GetSelection() == 0:
            self.img_shown = imagesk.double2mono8(self.bgcenter, donormalize=True)
        else:
            self.img_shown = imagesk.double2mono8(self.bgdev, donormalize=True)

        if self.currpolygon.shape[0] >= 1:
            points = [[self.currpolygon[0, 0], self.currpolygon[0, 1]]]
            pointcolors = [(currpolygoncolor[0] / 255.0, currpolygoncolor[1] / 255.0, currpolygoncolor[2] / 255.0)]
        else:
            points = []
            pointcolors = []

        lines = []
        for j in range(self.currpolygon.shape[0] - 1):
            lines.append(
                [
                    self.currpolygon[j, 0],
                    self.currpolygon[j, 1],
                    self.currpolygon[j + 1, 0],
                    self.currpolygon[j + 1, 1],
                    currpolygoncolor,
                ]
            )

        if self.showpolygons_checkbox.GetValue():
            for i in range(len(self.polygons)):
                for j in range(self.polygons[i].shape[0] - 1):
                    lines.append(
                        [
                            self.polygons[i][j, 0],
                            self.polygons[i][j, 1],
                            self.polygons[i][j + 1, 0],
                            self.polygons[i][j + 1, 1],
                            polygoncolor,
                        ]
                    )

        (lines, linecolors) = imagesk.separate_linesegs_colors(lines)

        self.img_wind.update_image_and_drawings(
            "fixbg",
            self.img_shown,
            format="MONO8",
            linesegs=lines,
            lineseg_colors=linecolors,
            points=points,
            point_colors=pointcolors,
        )

        self.img_wind.Refresh(eraseBackground=False)
예제 #2
0
    def redraw(self,eraseBackground=False):
        """Scale data and draw on window."""

        if (not hasattr(self,'ellipse')) or \
           (not hasattr(self.ellipse,'hasItem')):
            return

        ind = self.spinner.GetValue()
        if not self.ellipse.hasItem(ind):
            blank = num.ones( (params.zoom_window_pix,
                               params.zoom_window_pix), num.uint8 )*127
            self.window.update_image_and_drawings(self.name,blank,format='MONO8')
        else:
            # get box around ellipse
            valx = self.ellipse[ind].center.x - params.zoom_window_pix/2
            valx = max( valx, 0 )
            valx = min( valx, self.data.shape[1] - params.zoom_window_pix )
            valy = self.ellipse[ind].center.y - params.zoom_window_pix/2
            valy = max( valy, 0 )
            valy = min( valy, self.data.shape[0] - params.zoom_window_pix )
            self.offset = (valx,valy)
            zoomaxes = [self.offset[0],self.offset[0]+params.zoom_window_pix-1,
                        self.offset[1],self.offset[1]+params.zoom_window_pix-1]
            linesegs = draw_ellipses([self.ellipse[ind],],
                                     colors=[params.colors[ind%len(params.colors)],])
            im = imagesk.double2mono8(self.data,donormalize=False)
            linesegs,im = imagesk.zoom_linesegs_and_image(linesegs,im,zoomaxes)
            (linesegs,linecolors) = imagesk.separate_linesegs_colors(linesegs)
            self.window.update_image_and_drawings(self.name,im,format='MONO8',
                                                  linesegs=linesegs,lineseg_colors=linecolors)
            self.window.Refresh( eraseBackground=eraseBackground )
예제 #3
0
    def redraw(self,eraseBackground=False):
        """Scale data and draw on window."""

        ind = self.spinner.GetValue()

        if self.ellipse_size is None:
            wind_size = DEFAULT_WIND_SIZE
        else:
            wind_size = self.ellipse_size
        
        if not self.ellipses.hasItem(ind):
            blank = num.ones( (self.data.shape[0],self.data.shape[1]), num.uint8 )*127
            self.window.update_image_and_drawings(self.name,blank,format='MONO8')
        else:
            # get box around ellipse
            valx = self.ellipses[ind].center.x - self.ellipse_size/2
            valx = max( valx, 0 )
            valx = min( valx, self.data.shape[1] - self.ellipse_size )
            valy = self.ellipses[ind].center.y - self.ellipse_size/2
            valy = max( valy, 0 )
            valy = min( valy, self.data.shape[0] - self.ellipse_size )
            self.offset = (valx,valy)
            zoomaxes = [self.offset[0],self.offset[0]+self.ellipse_size-1,
                        self.offset[1],self.offset[1]+self.ellipse_size-1]
            linesegs = draw_ellipses([self.ellipses[ind],],
                                     colors=[params.colors[ind%len(params.colors)],])
            im = imagesk.double2mono8(self.data,donormalize=False)
            linesegs,im = imagesk.zoom_linesegs_and_image(linesegs,im,zoomaxes)
            (linesegs,linecolors) = imagesk.separate_linesegs_colors(linesegs)
            self.window.update_image_and_drawings(self.name,im,format='MONO8',
                                                  linesegs=linesegs,lineseg_colors=linecolors)
            self.window.Refresh( eraseBackground=eraseBackground )
예제 #4
0
    def redraw(self, eraseBackground=False):
        """Scale data and draw on window."""
        if self.window.GetRect().GetHeight() < 1: return

        ind = self.spinner.GetValue()

        if self.ellipse_size is None:
            wind_size = DEFAULT_WIND_SIZE
        else:
            wind_size = self.ellipse_size

        if not self.ellipses.hasItem(ind):
            blank = num.ones(
                (self.data.shape[0], self.data.shape[1]), num.uint8) * 127
            self.window.update_image_and_drawings(self.name,
                                                  blank,
                                                  format='MONO8')
        else:
            # get box around ellipse
            valx = self.ellipses[ind].center.x - self.ellipse_size / 2
            valx = max(valx, 0)
            valx = min(valx, self.data.shape[1] - self.ellipse_size)
            valy = self.ellipses[ind].center.y - self.ellipse_size / 2
            valy = max(valy, 0)
            valy = min(valy, self.data.shape[0] - self.ellipse_size)
            self.offset = (valx, valy)
            zoomaxes = [
                self.offset[0], self.offset[0] + self.ellipse_size - 1,
                self.offset[1], self.offset[1] + self.ellipse_size - 1
            ]
            linesegs = draw_ellipses(
                [self.ellipses[ind]],
                colors=[params.colors[ind % len(params.colors)]])

            # add tail, if checked
            if self.show_tail:
                ax = self.ellipse_size * num.cos(self.ellipses[ind].angle)
                ay = self.ellipse_size * num.sin(self.ellipses[ind].angle)
                linesegs.append([
                    self.ellipses[ind].center.x, self.ellipses[ind].center.y,
                    self.ellipses[ind].center.x - ax,
                    self.ellipses[ind].center.y - ay,
                    params.colors[ind % len(params.colors)]
                ])

            im = imagesk.double2mono8(self.data, donormalize=False)
            linesegs, im = imagesk.zoom_linesegs_and_image(
                linesegs, im, zoomaxes)
            (linesegs, linecolors) = imagesk.separate_linesegs_colors(linesegs)
            linewidths = (params.ellipse_thickness, ) * len(linesegs)
            self.window.update_image_and_drawings(self.name,
                                                  im,
                                                  format='MONO8',
                                                  linesegs=linesegs,
                                                  lineseg_colors=linecolors,
                                                  lineseg_widths=linewidths)
            self.window.Refresh(eraseBackground=eraseBackground)
    def update_image_and_drawings(self, source_name, img, **kwargs):
        """Override superclass's version to support zooming."""

        if self.current_source != source_name:
            # add some hackery to allow variable image shapes
            # as long as they're identified with a new source name
            self.full_image_numpy = None
            self.id_val = None

        if img.dtype != num.dtype('uint8'):
            img = double2mono8(img, donormalize=False)

        self.current_source = source_name
        self.current_img = img
        self.current_drawings = kwargs
        self.redraw()
예제 #6
0
    def redraw(self, eraseBackground=False):
        """Scale data and draw on window."""

        ind = self.spinner.GetValue()

        if self.ellipse_size is None:
            wind_size = DEFAULT_WIND_SIZE
        else:
            wind_size = self.ellipse_size

        if not self.ellipses.hasItem(ind):
            blank = num.ones(
                (self.data.shape[0], self.data.shape[1]), num.uint8) * 127
            self.window.update_image_and_drawings(self.name,
                                                  blank,
                                                  format='MONO8')
        else:
            # get box around ellipse
            valx = self.ellipses[ind].center.x - self.ellipse_size / 2
            valx = max(valx, 0)
            valx = min(valx, self.data.shape[1] - self.ellipse_size)
            valy = self.ellipses[ind].center.y - self.ellipse_size / 2
            valy = max(valy, 0)
            valy = min(valy, self.data.shape[0] - self.ellipse_size)
            self.offset = (valx, valy)
            zoomaxes = [
                self.offset[0], self.offset[0] + self.ellipse_size - 1,
                self.offset[1], self.offset[1] + self.ellipse_size - 1
            ]
            linesegs = draw_ellipses([
                self.ellipses[ind],
            ],
                                     colors=[
                                         params.colors[ind %
                                                       len(params.colors)],
                                     ])
            im = imagesk.double2mono8(self.data, donormalize=False)
            linesegs, im = imagesk.zoom_linesegs_and_image(
                linesegs, im, zoomaxes)
            (linesegs, linecolors) = imagesk.separate_linesegs_colors(linesegs)
            self.window.update_image_and_drawings(self.name,
                                                  im,
                                                  format='MONO8',
                                                  linesegs=linesegs,
                                                  lineseg_colors=linecolors)
            self.window.Refresh(eraseBackground=eraseBackground)
예제 #7
0
    def OnInit( self ):
        
        rsrc = xrc.XmlResource(RSRC_FILE)
        self.frame = rsrc.LoadFrame(None,"FRAME")
        self.frame.Show()
        self.img_panel = xrc.XRCCTRL(self.frame,"PANEL")
        box = wx.BoxSizer( wx.VERTICAL )
        self.img_panel.SetSizer( box )
        self.img_wind = wxvideo.DynamicImageCanvas( self.img_panel, -1 )
        self.img_wind.set_resize(True)
        box.Add( self.img_wind, 1, wx.EXPAND )
        self.img_panel.SetAutoLayout( True )
        self.img_panel.Layout()

        wx.EVT_LEFT_DOWN(self.img_wind,self.MouseClick)
        #self.img_wind.Bind(wx.EVT_LEFT_DOWN,self.MouseClick)

        self.filename = '/home/kristin/FLIES/data/walking_arena/movie20071009_155327.sbfmf'
        self.movie = movies.Movie(self.filename,True)
        imd,stamp = self.movie.get_frame( 1 )
        print 'imd = ' + str(imd)
        print 'minv = ' + str(nx.min(imd))
        im8 = imagesk.double2mono8(imd)
        print 'im8 = ' + str(im8)
        print 'minv = ' + str(nx.min(im8))
        print 'im8.shape = ' + str(im8.shape)

        #im8 = nx.zeros((1024,1024),dtype=nx.uint8)

        point = [[500,500]]
        line = [[250,250,750,750]]
        pointcolors = [(1,0,0)]
        linecolors = [(1,1,0)]

        self.img_wind.update_image_and_drawings('camera',im8,format='MONO8',
                                                linesegs=line,points=point,
                                                point_colors=pointcolors,
                                                lineseg_colors=linecolors)
    
        return True
    def ShowImage(self):

        im, stamp = params.params.movie.get_frame( int(self.show_frame) )
        windowsize = [self.img_panel.GetRect().GetHeight(),self.img_panel.GetRect().GetWidth()]

        self.GetBgImage()
            
        if self.img_chosen == SHOW_UNFILTERED_OBSERVATIONS:
            obs_unfiltered = self.GetObsUnfiltered()
            plot_linesegs = ell.draw_ellipses(obs_unfiltered)
            
        elif self.img_chosen == SHOW_FILTERED_OBSERVATIONS:
            obs_filtered = self.GetObsFiltered()
            plot_linesegs = ell.draw_ellipses(obs_filtered)
            
        elif self.img_chosen == SHOW_SMALL_OBSERVATIONS:
            obs_unfiltered = self.GetObsUnfiltered()
            obs_small = []
            for obs in obs_unfiltered:
                if obs.area < params.params.minshape.area:
                    obs_small.append(obs)
            plot_linesegs = ell.draw_ellipses(obs_small)
            
        elif self.img_chosen == SHOW_LARGE_OBSERVATIONS:
            obs_unfiltered = self.GetObsUnfiltered()
            obs_large = []
            for obs in obs_unfiltered:
                if obs.area > params.params.maxshape.area:
                    obs_large.append(obs)
            plot_linesegs = ell.draw_ellipses(obs_large)

        elif self.img_chosen == SHOW_DELETED_OBSERVATIONS:
            (obs_unfiltered,diddelete) = self.GetObsUnfiltered('diddelete')
            obs_deleted = []
            for (i,v) in enumerate(diddelete):
                if v: obs_deleted.append(obs_unfiltered[i])
            plot_linesegs = ell.draw_ellipses(obs_deleted)

        elif self.img_chosen == SHOW_SPLIT_OBSERVATIONS:
            (obs_unfiltered,didsplit) = self.GetObsUnfiltered('didsplit')
            colors = []
            obs_split = []
            for (i,v) in enumerate(didsplit):
                if len(v)>1:
                    for j in v:
                        colors.append(params.params.colors[i % len(params.params.colors)])
                        obs_split.append(obs_unfiltered[j])
            plot_linesegs = ell.draw_ellipses(obs_split)

        elif self.img_chosen == SHOW_MERGED_OBSERVATIONS:
            (obs_unfiltered,didmerge) = self.GetObsUnfiltered('didmerge')
            colors = []
            obs_merge = []
            for (i,v) in enumerate(didmerge):
                if len(v)>1:
                  obs_merge.append(obs_unfiltered[i])
            plot_linesegs = ell.draw_ellipses(obs_merge)

        elif self.img_chosen == SHOW_LOWERED_OBSERVATIONS:
            (obs_unfiltered,didlowerthresh) = self.GetObsUnfiltered('didlowerthresh')
            obs_lowered = []
            for (i,v) in enumerate(didlowerthresh):
                if v: obs_lowered.append(obs_unfiltered[i])
            plot_linesegs = ell.draw_ellipses(obs_lowered)

        # MAXJUMP
        elif self.img_chosen == SHOW_MAXJUMP:

            # either grab or compute observations
            obs_filtered = self.GetObsFiltered()
            plot_linesegs = ell.draw_ellipses(obs_filtered)

            # draw circles
            for i,obs in enumerate(obs_filtered):
                plot_new_stuff = imagesk.draw_circle(obs.center.x,
                                                     obs.center.y,params.params.max_jump,
                                                     params.params.colors[i%len(params.params.colors)])
                plot_linesegs.extend(plot_new_stuff)
                

        elif self.img_chosen == SHOW_MOTIONMODEL:

            (target_prev,target_curr,target_pred) = self.GetTargetMotion()

            # show the next frame, if there is one
            nextframe = num.minimum(int(self.show_frame+1),params.params.n_frames-1)
            im, stamp = params.params.movie.get_frame(nextframe)

            # draw previous positions
            plot_linesegs = ell.draw_ellipses(target_prev)

            # draw current positions
            plot_new_stuff = ell.draw_ellipses(target_curr,colors=[[255,255,0]])
            plot_linesegs.extend(plot_new_stuff)

            # draw predicted positions
            plot_new_stuff = ell.draw_ellipses(target_pred)
            plot_linesegs.extend(plot_new_stuff)

            scaleunit = params.params.max_jump / params.params.DRAW_MOTION_SCALE
            parcolor = [0,255,0]
            perpcolor = [0,255,0]
            anglecolor = [0,0,255]

            for i in target_pred.iterkeys():
                # compute direction of motion
                vx = target_pred[i].center.x - target_curr[i].center.x
                vy = target_pred[i].center.y - target_curr[i].center.y
                thetamotion = num.arctan2(vy,vx)

                # angle
                theta = target_pred[i].angle
                
                # we want to choose to add pi if that makes difference from motion direction smaller
                dtheta = abs( ((theta - thetamotion + num.pi) % (2.*num.pi)) - num.pi )
                if dtheta > (num.pi/2.):
                    theta += num.pi

                # compute end points of parallel motion
                x0 = target_pred[i].center.x + scaleunit*num.cos(theta)
                x1 = target_pred[i].center.x - scaleunit*num.cos(theta)
                y0 = target_pred[i].center.y + scaleunit*num.sin(theta)
                y1 = target_pred[i].center.y - scaleunit*num.sin(theta)

                # add parallel motion annotation line
                plot_new_stuff = imagesk.draw_line(x0+1,y0+1,x1+1,y1+1,parcolor)
                plot_linesegs.extend(plot_new_stuff)

                # compute end points of perpendicular motion
                x0 = target_pred[i].center.x + scaleunit*num.cos(num.pi/2.+theta)
                x1 = target_pred[i].center.x - scaleunit*num.cos(num.pi/2.+theta)
                y0 = target_pred[i].center.y + scaleunit*num.sin(num.pi/2.+theta)
                y1 = target_pred[i].center.y - scaleunit*num.sin(num.pi/2.+theta)
                
                # add perpendicular motion annotation line
                plot_new_stuff = imagesk.draw_line(x0+1,y0+1,x1+1,y1+1,perpcolor)
                plot_linesegs.extend(plot_new_stuff)
                

                # compute end points of angular motion
                if params.params.ang_dist_wt > 0:
                    
                    dtheta = scaleunit*num.sqrt(1./params.params.ang_dist_wt)
                    if dtheta >= (num.pi/2.):
                        print 'dtheta is more than pi/2'
                    else:
                        theta0 = theta - dtheta
                        theta1 = theta + dtheta
                        
                        # draw arc
                        plot_new_stuff = imagesk.draw_arc(target_pred[i].center.x,
                                                          target_pred[i].center.y,
                                                          scaleunit/2,
                                                          theta0,theta1,
                                                          anglecolor)
                        plot_linesegs.extend(plot_new_stuff)
                   
        im = imagesk.double2mono8(im,donormalize=False)
        linesegs,im = imagesk.zoom_linesegs_and_image(plot_linesegs,im,self.zoomaxes)
        (linesegs,linecolors) = imagesk.separate_linesegs_colors(linesegs)
        
        self.img_wind.update_image_and_drawings('trackset',
                                                im,
                                                format='MONO8',
                                                linesegs=linesegs,
                                                lineseg_colors=linecolors
                                                )

        self.img_wind.Refresh(eraseBackground=False)

        self.frame_number_text.SetLabel('Frame %d'%self.show_frame)
예제 #9
0
    def get_sub_image( self, sub_type, framenumber ):
        """Do background subtraction and return a particular image type."""
        wx.BeginBusyCursor()
        try: wx.Yield()
        except: pass # sometimes complains about recursive Yield()
        
        # do background subtraction if necessary
        if sub_type in [params.SHOW_DISTANCE,params.SHOW_THRESH,
                        params.SHOW_CC,params.SHOW_ELLIPSES,
                        params.SHOW_BACKGROUND,params.SHOW_DEV,
                        params.SHOW_BG_AND_DIST]:
            (dfore,bw,cc,ncc) = self.sub_bg( framenumber )   # sets self.on, etc.
        else:
            if hasattr( self, 'dfore' ):
                dfore = self.dfore
                bw = self.bw
                cc = self.cc
                ncc = self.ncc
            else:
                dfore = None
                bw = None
                cc = None
                ncc = None

        line_segs = []
        line_clrs = []
        img_format = None

        # format image in "subtraction type"
        if sub_type == params.SHOW_BACKGROUND:
            cntr = self.centers[self.on] if self.varying_bg else self.center
            img_8 = imagesk.double2mono8(cntr,donormalize=False)
            img_format = 'MONO8'
            preview_range = (0,255)
        elif sub_type == params.SHOW_DISTANCE:
            img_8 = imagesk.double2mono8(dfore)
            img_format = 'MONO8'
            preview_range = (dfore.min(), dfore.max())
        elif sub_type == params.SHOW_THRESH:
            img_8 = imagesk.double2mono8(bw.astype(float))
            img_format = 'MONO8'
            preview_range = (0,1)
        elif sub_type == params.SHOW_NONFORE:
            isnotarena = (self.isarena == False)
            img_8 = imagesk.double2mono8(isnotarena.astype(float))
            img_format = 'MONO8'
            preview_range = (0,1)
        elif sub_type == params.SHOW_DEV:
            dev = self.devs[self.on] if self.varying_bg else self.dev
            mu = num.mean(dev)
            sig = num.std(dev)
            if sig == 0:
                img_8 = imagesk.double2mono8(dev)
                n1 = mu
                n2 = mu
            else:
                n1 = max(0,mu - 3.*sig)
                n2 = mu + 3.*sig
                img_8 = imagesk.double2mono8(dev.clip(n1,n2))
            img_format = 'MONO8'
            preview_range = (n1,n2)
        elif sub_type == params.SHOW_CC:
            img_8,clim = colormap_image(cc)
            img_format = 'RGB8'
            preview_range = clim
        elif sub_type == params.SHOW_ELLIPSES:
            # find ellipse observations
            obs = find_ellipses(dfore,cc,ncc,False)
            im, stamp = params.movie.get_frame( int(framenumber) )
            img_8 = imagesk.double2mono8(im,donormalize=False)
            plot_linesegs = draw_ellipses(obs)
            (linesegs,linecolors) = \
                imagesk.separate_linesegs_colors(plot_linesegs)
            img_8 = imagesk.double2mono8(im,donormalize=False)
            img_format = 'MONO8'
            preview_range = (0,255)
            line_segs.extend( linesegs )
            line_clrs.extend( linecolors )
        elif sub_type == params.SHOW_BG_AND_DIST:
            cntr = self.centers[self.on] if self.varying_bg else self.center
            img = Image.fromarray(imagesk.double2mono8(cntr,donormalize=False)).convert('RGB')
            img.paste((0,255,0), None, Image.fromarray(imagesk.double2mono8(dfore)))
            img_8 = num.array(img)
            img_format = 'RGB8'
            preview_range = (0,255)
        elif sub_type in params.SHOW_EXPBGFGMODEL: 
            # check for expbgfgmodel
            if not params.use_expbgfgmodel or not hasattr(self,'expbgfgmodel') or \
            self.expbgfgmodel is None:
                resp = wx.MessageBox("No prior model loaded.","No prior model loaded",wx.OK)
            else:
                if sub_type == params.SHOW_EXPBGFGMODEL_LLR:
                    # read the current image, classify pixels
                    im, stamp = params.movie.get_frame( int(framenumber) )
                    llr = self.expbgfgmodel_llr(im)
                    img_8,clim = colormap_image(llr)
                    img_format = 'RGB'
                    preview_range = clim
                elif sub_type == params.SHOW_EXPBGFGMODEL_ISBACK:
                    im, stamp = params.movie.get_frame( int(framenumber) )
                    isback = self.thresh_expbgfgmodel_llr(im)
                    img_8 = imagesk.double2mono8(isback.astype(float))
                    img_format = 'MONO8'
                    preview_range = (0,1)
                elif sub_type == params.SHOW_EXPBGFGMODEL_BGMU:
                    img_8 = imagesk.double2mono8(self.expbgfgmodel.bg_mu,donormalize=False)
                    img_format = 'MONO8'
                    preview_range = (0,255)
                elif sub_type == params.SHOW_EXPBGFGMODEL_FGMU:
                    img_8 = imagesk.double2mono8(self.expbgfgmodel.fg_mu,donormalize=False)
                    img_format = 'MONO8'
                    preview_range = (0,255)
                elif sub_type == params.SHOW_EXPBGFGMODEL_BGSIGMA:
                    mu = num.mean(self.expbgfgmodel.bg_sigma)
                    sig = num.std(self.expbgfgmodel.bg_sigma)
                    if sig == 0:
                        n1 = mu
                        n2 = mu
                        img_8 = imagesk.double2mono8(self.expbgfgmodel.bg_sigma)
                    else:
                        n1 = max(0,mu - 3.*sig)
                        n2 = mu + 3.*sig
                        img_8 = imagesk.double2mono8(self.expbgfgmodel.bg_sigma.clip(n1,n2))
                    img_format = 'MONO8'
                    preview_range = (n1,n2)
                elif sub_type == params.SHOW_EXPBGFGMODEL_FGSIGMA:
                    mu = num.mean(self.expbgfgmodel.fg_sigma)
                    sig = num.std(self.expbgfgmodel.fg_sigma)
                    if sig == 0:
                        img_8 = imagesk.double2mono8(self.expbgfgmodel.fg_sigma)
                        n1 = mu
                        n2 = mu
                    else:
                        n1 = max(0,mu - 3.*sig)
                        n2 = mu + 3.*sig
                        img_8 = imagesk.double2mono8(self.expbgfgmodel.fg_sigma.clip(n1,n2))
                    img_format = 'MONO8'
                    preview_range = (n1,n2)
                elif sub_type == params.SHOW_EXPBGFGMODEL_FRACFRAMESISBACK:
                    if not hasattr(self,'fracframesisback') or self.fracframesisback is None:
                        resp = wx.MessageBox("fracframesisback not yet computed","fracframesisback Not Computed",wx.OK)
                        return
                    img_8,clim = colormap_image(self.fracframesisback)
                    img_format = 'RGB8'
                    preview_range = clim
                elif sub_type == params.SHOW_EXPBGFGMODEL_MISSINGDATA:
                    if not hasattr(self,'fracframesisback') or self.fracframesisback is None:
                        resp = wx.MessageBox("fracframesisback not yet computed","fracframesisback Not Computed",wx.OK)
                        return
                    missingdata = self.fracframesisback <= params.min_frac_frames_isback
                    img_8 = imagesk.double2mono8(missingdata.astype(float))
                    img_format = 'MONO8'
                    preview_range = (0,1)

        wx.EndBusyCursor()

        return img_8, img_format, line_segs, line_clrs, dfore, bw, cc, ncc, preview_range
예제 #10
0
 def get_image_to_show(self):
     if self.displaymode_choice.GetSelection() == 0:
         return imagesk.double2mono8(self.bgcenter, donormalize=True)
     else:
         return imagesk.double2mono8(self.bgdev, donormalize=True)
예제 #11
0
    def get_sub_image(self, sub_type, framenumber):
        """Do background subtraction and return a particular image type."""
        wx.BeginBusyCursor()
        try:
            wx.Yield()
        except:
            pass  # sometimes complains about recursive Yield()

        # do background subtraction if necessary
        if sub_type in [
                params.SHOW_DISTANCE, params.SHOW_THRESH, params.SHOW_CC,
                params.SHOW_ELLIPSES, params.SHOW_BACKGROUND, params.SHOW_DEV,
                params.SHOW_BG_AND_DIST
        ]:
            (dfore, bw, cc,
             ncc) = self.sub_bg(framenumber)  # sets self.on, etc.
        else:
            if hasattr(self, 'dfore'):
                dfore = self.dfore
                bw = self.bw
                cc = self.cc
                ncc = self.ncc
            else:
                dfore = None
                bw = None
                cc = None
                ncc = None

        line_segs = []
        line_clrs = []
        img_format = None

        # format image in "subtraction type"
        if sub_type == params.SHOW_BACKGROUND:
            cntr = self.centers[self.on] if self.varying_bg else self.center
            img_8 = imagesk.double2mono8(cntr, donormalize=False)
            img_format = 'MONO8'
            preview_range = (0, 255)
        elif sub_type == params.SHOW_DISTANCE:
            img_8 = imagesk.double2mono8(dfore)
            img_format = 'MONO8'
            preview_range = (dfore.min(), dfore.max())
        elif sub_type == params.SHOW_THRESH:
            img_8 = imagesk.double2mono8(bw.astype(float))
            img_format = 'MONO8'
            preview_range = (0, 1)
        elif sub_type == params.SHOW_NONFORE:
            isnotarena = (self.isarena == False)
            img_8 = imagesk.double2mono8(isnotarena.astype(float))
            img_format = 'MONO8'
            preview_range = (0, 1)
        elif sub_type == params.SHOW_DEV:
            dev = self.devs[self.on] if self.varying_bg else self.dev
            mu = num.mean(dev)
            sig = num.std(dev)
            if sig == 0:
                img_8 = imagesk.double2mono8(dev)
                n1 = mu
                n2 = mu
            else:
                n1 = max(0, mu - 3. * sig)
                n2 = mu + 3. * sig
                img_8 = imagesk.double2mono8(dev.clip(n1, n2))
            img_format = 'MONO8'
            preview_range = (n1, n2)
        elif sub_type == params.SHOW_CC:
            img_8, clim = colormap_image(cc)
            img_format = 'RGB8'
            preview_range = clim
        elif sub_type == params.SHOW_ELLIPSES:
            # find ellipse observations
            obs = find_ellipses(dfore, cc, ncc, False)
            im, stamp = params.movie.get_frame(int(framenumber))
            img_8 = imagesk.double2mono8(im, donormalize=False)
            plot_linesegs = draw_ellipses(obs)
            (linesegs,linecolors) = \
                imagesk.separate_linesegs_colors(plot_linesegs)
            img_8 = imagesk.double2mono8(im, donormalize=False)
            img_format = 'MONO8'
            preview_range = (0, 255)
            line_segs.extend(linesegs)
            line_clrs.extend(linecolors)
        elif sub_type == params.SHOW_BG_AND_DIST:
            cntr = self.centers[self.on] if self.varying_bg else self.center
            img = Image.fromarray(imagesk.double2mono8(
                cntr, donormalize=False)).convert('RGB')
            img.paste((0, 255, 0), None,
                      Image.fromarray(imagesk.double2mono8(dfore)))
            img_8 = num.array(img)
            img_format = 'RGB8'
            preview_range = (0, 255)
        elif sub_type in params.SHOW_EXPBGFGMODEL:
            # check for expbgfgmodel
            if not params.use_expbgfgmodel or not hasattr(self,'expbgfgmodel') or \
            self.expbgfgmodel is None:
                resp = wx.MessageBox("No prior model loaded.",
                                     "No prior model loaded", wx.OK)
            else:
                if sub_type == params.SHOW_EXPBGFGMODEL_LLR:
                    # read the current image, classify pixels
                    im, stamp = params.movie.get_frame(int(framenumber))
                    llr = self.expbgfgmodel_llr(im)
                    img_8, clim = colormap_image(llr)
                    img_format = 'RGB'
                    preview_range = clim
                elif sub_type == params.SHOW_EXPBGFGMODEL_ISBACK:
                    im, stamp = params.movie.get_frame(int(framenumber))
                    isback = self.thresh_expbgfgmodel_llr(im)
                    img_8 = imagesk.double2mono8(isback.astype(float))
                    img_format = 'MONO8'
                    preview_range = (0, 1)
                elif sub_type == params.SHOW_EXPBGFGMODEL_BGMU:
                    img_8 = imagesk.double2mono8(self.expbgfgmodel.bg_mu,
                                                 donormalize=False)
                    img_format = 'MONO8'
                    preview_range = (0, 255)
                elif sub_type == params.SHOW_EXPBGFGMODEL_FGMU:
                    img_8 = imagesk.double2mono8(self.expbgfgmodel.fg_mu,
                                                 donormalize=False)
                    img_format = 'MONO8'
                    preview_range = (0, 255)
                elif sub_type == params.SHOW_EXPBGFGMODEL_BGSIGMA:
                    mu = num.mean(self.expbgfgmodel.bg_sigma)
                    sig = num.std(self.expbgfgmodel.bg_sigma)
                    if sig == 0:
                        n1 = mu
                        n2 = mu
                        img_8 = imagesk.double2mono8(
                            self.expbgfgmodel.bg_sigma)
                    else:
                        n1 = max(0, mu - 3. * sig)
                        n2 = mu + 3. * sig
                        img_8 = imagesk.double2mono8(
                            self.expbgfgmodel.bg_sigma.clip(n1, n2))
                    img_format = 'MONO8'
                    preview_range = (n1, n2)
                elif sub_type == params.SHOW_EXPBGFGMODEL_FGSIGMA:
                    mu = num.mean(self.expbgfgmodel.fg_sigma)
                    sig = num.std(self.expbgfgmodel.fg_sigma)
                    if sig == 0:
                        img_8 = imagesk.double2mono8(
                            self.expbgfgmodel.fg_sigma)
                        n1 = mu
                        n2 = mu
                    else:
                        n1 = max(0, mu - 3. * sig)
                        n2 = mu + 3. * sig
                        img_8 = imagesk.double2mono8(
                            self.expbgfgmodel.fg_sigma.clip(n1, n2))
                    img_format = 'MONO8'
                    preview_range = (n1, n2)
                elif sub_type == params.SHOW_EXPBGFGMODEL_FRACFRAMESISBACK:
                    if not hasattr(self, 'fracframesisback'
                                   ) or self.fracframesisback is None:
                        resp = wx.MessageBox(
                            "fracframesisback not yet computed",
                            "fracframesisback Not Computed", wx.OK)
                        return
                    img_8, clim = colormap_image(self.fracframesisback)
                    img_format = 'RGB8'
                    preview_range = clim
                elif sub_type == params.SHOW_EXPBGFGMODEL_MISSINGDATA:
                    if not hasattr(self, 'fracframesisback'
                                   ) or self.fracframesisback is None:
                        resp = wx.MessageBox(
                            "fracframesisback not yet computed",
                            "fracframesisback Not Computed", wx.OK)
                        return
                    missingdata = self.fracframesisback <= params.min_frac_frames_isback
                    img_8 = imagesk.double2mono8(missingdata.astype(float))
                    img_format = 'MONO8'
                    preview_range = (0, 1)

        wx.EndBusyCursor()

        return img_8, img_format, line_segs, line_clrs, dfore, bw, cc, ncc, preview_range
예제 #12
0
    def ShowCurrentFrame( self, framenumber=None ):
        """Grab current frame, draw on it, and display in GUI.
        Also update zoom-ellipse windows, if present."""
	if not params.interactive: return
        if not self.alive: return
        if not hasattr( self, 'movie' ) or self.movie is None: return
        if self.start_frame < 0: return

        # get frame
        if framenumber is None:
            framenumber = self.start_frame
        try:
            frame, self.last_timestamp = self.movie.get_frame( framenumber )
            if num.isnan(self.last_timestamp):
                self.last_timestamp = float(framenumber) / float(params.DEFAULT_FRAME_RATE)
        except movies.NoMoreFramesException:
            self.n_frames = self.movie.get_n_frames()
            self.start_frame = min(self.start_frame,self.n_frames-1)
            self.slider.SetScrollbar( self.start_frame,1,self.n_frames-1,100 )
            return
        except IndexError: # framenumber out of range
            return

	# set frame number display
        self.framenumber_text.SetValue( "%05d"%(self.start_frame) )

	# draw_frame is the frame number relative to when tracking was started
        dodrawann = self.ann_file.IsAnnData() and \
            framenumber >= self.ann_file.firstframetracked and \
            framenumber <= self.ann_file.lastframetracked

        if dodrawann:

            # first frame of tail of trajectory
            tailframe = max(self.ann_file.firstframetracked,
                            framenumber-params.tail_length)
            dataframes = self.ann_file.get_frames(tailframe,framenumber)

            # update small ellipse windows
            if self.menu.IsChecked( xrc.XRCID("menu_settings_zoom") ):
                self.zoom_window.SetData(dataframes[-1],frame)
                self.zoom_window.Redraw()

        # dim frame
        if self.menu.IsChecked( xrc.XRCID("menu_playback_dim") ):
            frame = frame / 2

        # annotate image
        frame8 = imagesk.double2mono8(frame,donormalize=False)
        if self.menu.IsChecked( xrc.XRCID("menu_playback_show_ann") ) \
                and dodrawann:
            ellipses = dataframes[-1]
            old_pts = []
            for dataframe in dataframes:
                these_pts = []
                for ellipse in dataframe.itervalues():
                    these_pts.append( (ellipse.center.x, ellipse.center.y, ellipse.identity) )
                old_pts.append( these_pts )

            # draw on image
            linesegs = draw.annotate_image(ellipses,old_pts,
                                           self.ellipse_thickness)

            (linesegs,linecolors) = imagesk.separate_linesegs_colors(linesegs)
            self.img_wind.update_image_and_drawings('Ctraxmain',frame8,
                                                    format='MONO8',
                                                    linesegs=linesegs,
                                                    lineseg_colors=linecolors)
            self.num_flies_text.SetValue( "N. Flies: %02d"%len(ellipses) )
        else:
            self.num_flies_text.SetValue( "" )

            # scale image and display
            self.img_wind.update_image_and_drawings('Ctraxmain',frame8,
                                                    format='MONO8')

        self.img_wind.Refresh( eraseBackground=False )

        # update the slider
        self.slider.SetThumbPosition( framenumber )
예제 #13
0
    def ShowImage(self):

        if DEBUG_TRACKINGSETTINGS: print 'ShowImage ' + str(self.show_frame)

        try:
            wx.Yield()
        except:
            pass  # can be recursive sometimes in Windows
        wx.BeginBusyCursor()
        im, stamp = self.bg_imgs.movie.get_frame(int(self.show_frame))

        windowsize = [
            self.img_panel.GetRect().GetHeight(),
            self.img_panel.GetRect().GetWidth()
        ]

        self.GetBgImage()

        if self.img_chosen == SHOW_UNFILTERED_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_UNFILTERED_OBSERVATIONS'
            obs_unfiltered = self.GetObsUnfiltered()
            plot_linesegs = draw_ellipses(obs_unfiltered)

        elif self.img_chosen == SHOW_FILTERED_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_FILTERED_OBSERVATIONS'
            obs_filtered = self.GetObsFiltered()
            plot_linesegs = draw_ellipses(obs_filtered)

        elif self.img_chosen == SHOW_SMALL_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_SMALL_OBSERVATIONS'
            obs_unfiltered = self.GetObsUnfiltered()
            obs_small = []
            for obs in obs_unfiltered:
                if obs.area() < params.params.minshape.area:
                    obs_small.append(obs)
            plot_linesegs = draw_ellipses(obs_small)

        elif self.img_chosen == SHOW_LARGE_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_LARGE_OBSERVATIONS'
            obs_unfiltered = self.GetObsUnfiltered()
            obs_large = []
            for obs in obs_unfiltered:
                if obs.area() > params.params.maxshape.area:
                    obs_large.append(obs)
            plot_linesegs = draw_ellipses(obs_large)

        elif self.img_chosen == SHOW_DELETED_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_DELETED_OBSERVATIONS'
            (obs_unfiltered, obs_deleted) = self.GetObsUnfiltered('diddelete')
            plot_linesegs = draw_ellipses(obs_deleted)

        elif self.img_chosen == SHOW_SPLIT_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_SPLIT_OBSERVATIONS'
            (obs_unfiltered, obs_split) = self.GetObsUnfiltered('didsplit')
            plot_linesegs = draw_ellipses(obs_split)

        elif self.img_chosen == SHOW_MERGED_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_MERGED_OBSERVATIONS'
            (obs_unfiltered, obs_merge) = self.GetObsUnfiltered('didmerge')
            plot_linesegs = draw_ellipses(obs_merge)

        elif self.img_chosen == SHOW_LOWERED_OBSERVATIONS:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_LOWERED_OBSERVATIONS'
            (obs_unfiltered,
             obs_lowered) = self.GetObsUnfiltered('didlowerthresh')
            plot_linesegs = draw_ellipses(obs_lowered)

        # MAXJUMP
        elif self.img_chosen == SHOW_MAXJUMP:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_MAXJUMP'

            # either grab or compute observations
            obs_filtered = self.GetObsFiltered()
            plot_linesegs = draw_ellipses(obs_filtered)

            # draw circles
            for i, obs in enumerate(obs_filtered):
                plot_new_stuff = imagesk.draw_circle(
                    obs.center.x, obs.center.y, params.params.max_jump * 2.,
                    params.params.colors[i % len(params.params.colors)])
                plot_linesegs.extend(plot_new_stuff)
                plot_new_stuff = imagesk.draw_circle(
                    obs.center.x, obs.center.y, params.params.min_jump,
                    params.params.colors[i % len(params.params.colors)])
                plot_linesegs.extend(plot_new_stuff)

        elif self.img_chosen == SHOW_MOTIONMODEL:
            if DEBUG_TRACKINGSETTINGS: print 'SHOW_MOTIONMODEL'

            (target_prev, target_curr, target_pred) = self.GetTargetMotion()

            # show the next frame, if there is one
            nextframe = num.minimum(int(self.show_frame + 1),
                                    params.params.n_frames - 1)
            im, stamp = self.bg_imgs.movie.get_frame(nextframe)

            # draw previous positions
            plot_linesegs = draw_ellipses(target_prev)

            # draw current positions
            plot_new_stuff = draw_ellipses(target_curr)
            plot_linesegs.extend(plot_new_stuff)

            # draw predicted positions
            plot_new_stuff = draw_ellipses(target_pred)
            plot_linesegs.extend(plot_new_stuff)

            scaleunit = params.params.max_jump / params.params.DRAW_MOTION_SCALE
            parcolor = [0, 255, 0]
            perpcolor = [0, 255, 0]
            anglecolor = [0, 0, 255]

            for i in target_pred.iterkeys():
                # compute direction of motion
                vx = target_pred[i].center.x - target_curr[i].center.x
                vy = target_pred[i].center.y - target_curr[i].center.y
                thetamotion = num.arctan2(vy, vx)

                # angle
                theta = target_pred[i].angle

                # we want to choose to add pi if that makes difference from motion direction smaller
                dtheta = abs(((theta - thetamotion + num.pi) % (2. * num.pi)) -
                             num.pi)
                if dtheta > (num.pi / 2.):
                    theta += num.pi

                # compute end points of parallel motion
                x0 = target_pred[i].center.x + scaleunit * num.cos(theta)
                x1 = target_pred[i].center.x - scaleunit * num.cos(theta)
                y0 = target_pred[i].center.y + scaleunit * num.sin(theta)
                y1 = target_pred[i].center.y - scaleunit * num.sin(theta)

                # add parallel motion annotation line
                plot_new_stuff = imagesk.draw_line(x0 + 1, y0 + 1, x1 + 1,
                                                   y1 + 1, parcolor)
                plot_linesegs.extend(plot_new_stuff)

                # compute end points of perpendicular motion
                x0 = target_pred[i].center.x + scaleunit * num.cos(num.pi /
                                                                   2. + theta)
                x1 = target_pred[i].center.x - scaleunit * num.cos(num.pi /
                                                                   2. + theta)
                y0 = target_pred[i].center.y + scaleunit * num.sin(num.pi /
                                                                   2. + theta)
                y1 = target_pred[i].center.y - scaleunit * num.sin(num.pi /
                                                                   2. + theta)

                # add perpendicular motion annotation line
                plot_new_stuff = imagesk.draw_line(x0 + 1, y0 + 1, x1 + 1,
                                                   y1 + 1, perpcolor)
                plot_linesegs.extend(plot_new_stuff)

                # compute end points of angular motion
                if params.params.ang_dist_wt > 0:

                    dtheta = scaleunit * num.sqrt(
                        1. / params.params.ang_dist_wt)
                    if dtheta >= (num.pi / 2.):
                        print 'dtheta is more than pi/2'
                    else:
                        theta0 = theta - dtheta
                        theta1 = theta + dtheta

                        # draw arc
                        plot_new_stuff = imagesk.draw_arc(
                            target_pred[i].center.x, target_pred[i].center.y,
                            scaleunit / 2, theta0, theta1, anglecolor)
                        plot_linesegs.extend(plot_new_stuff)

        im = imagesk.double2mono8(im, donormalize=False)
        linesegs, im = imagesk.zoom_linesegs_and_image(plot_linesegs, im,
                                                       self.zoomaxes)
        (linesegs, linecolors) = imagesk.separate_linesegs_colors(linesegs)

        self.img_wind.update_image_and_drawings('trackset',
                                                im,
                                                format='MONO8',
                                                linesegs=linesegs,
                                                lineseg_colors=linecolors)
        self.img_wind.Refresh(eraseBackground=False)

        self.frame_number_text.SetLabel('Frame %d' % self.show_frame)

        if self.info == True:
            self.ShowInfo(None, None)

        wx.EndBusyCursor()

        if DEBUG_TRACKINGSETTINGS: sys.stdout.flush()
예제 #14
0
 def get_image_to_show(self):
     if self.displaymode_choice.GetSelection() == 0:
         return imagesk.double2mono8(self.bgcenter, donormalize=True)
     else:
         return imagesk.double2mono8(self.roi.astype(num.double) * 255,
                                     donormalize=False)