Example #1
0
def hv_adjust_image_landmarks(image,
                              landmarks,
                              landmarks_match=None,
                              bregma_offset=None,
                              resolution=0.0194,
                              msize=40):
    '''
    TODO: merge part of this with the one for the landmarks
    landmarks are in allen reference space
    '''
    h, w = image.shape
    if bregma_offset is None:
        # then it is the center of the image
        bregma_offset = np.array([int(w / 2), int(h / 2)
                                  ])  # place bregma in the center of the image

    landmarks_im = allen_landmarks_to_image_space(landmarks.copy(),
                                                  bregma_offset, resolution)
    if landmarks_match is None:
        landmarks_match = landmarks_im
    import holoviews as hv
    from holoviews import opts, streams
    from holoviews.plotting.links import DataLink

    bounds = np.array([0, 0, w, h])
    im = hv.Image(image[::-1, :],
                  bounds=tuple(bounds.tolist())).opts(invert_yaxis=True,
                                                      cmap='gray')

    points = hv.Points(landmarks_match, vdims='color').opts(marker='+',
                                                            size=msize)
    point_stream = streams.PointDraw(data=points.columns(),
                                     add=False,
                                     num_objects=4,
                                     source=points,
                                     empty_value='black')
    table = hv.Table(points, ['x', 'y', 'name'],
                     'color').opts(title='Annotation location')
    DataLink(points, table)

    from bokeh.models import HoverTool
    hoverpts = HoverTool(tooltips=[("i", "$index")])

    widget = (im * points + table).opts(
        opts.Layout(merge_tools=False),
        opts.Points(invert_yaxis=True,
                    active_tools=['point_draw'],
                    color='color',
                    tools=[hoverpts],
                    width=int(w),
                    height=int(h)), opts.Table(editable=True))
    return widget, point_stream, landmarks_im
Example #2
0
def hv_adjust_reference_landmarks(landmarks, ccf_regions, msize=40):
    '''
    landmarks = {'x': [-1.95, 0, 1.95, 0],
                 'y': [-3.45, -3.45, -3.45, 3.2],
                 'name': ['OB_left', 'OB_center', 'OB_right', 'RSP_base'],
                 'color': ['#fc9d03', '#0367fc', '#fc9d03', '#fc4103']}
    landmarks = pd.DataFrame(landmarks)
    # adjust landmarks
    wid,landmark_wid = hv_adjust_reference_landmarks(landmarks,ccf_regions)
    wid # to display
    # use the following to retrieve (on another cell) 
    landmarks = pd.DataFrame(landmark_wid.data)[['x','y','name','color']]
    '''
    import holoviews as hv
    from holoviews import opts, streams
    from holoviews.plotting.links import DataLink
    referenceplt = hv_plot_allen_regions(ccf_regions).options(
        {'Curve': {
            'color': 'black',
            'width': 600
        }})

    points = hv.Points(landmarks, vdims='color').opts(marker='+', size=msize)
    point_stream = streams.PointDraw(data=points.columns(),
                                     add=False,
                                     num_objects=4,
                                     source=points,
                                     empty_value='black')
    table = hv.Table(points, ['x', 'y', 'name'],
                     'color').opts(title='Landmarks location')
    DataLink(points, table)
    widget = (referenceplt * points + table).opts(
        opts.Layout(merge_tools=False),
        opts.Points(invert_yaxis=True,
                    active_tools=['point_draw'],
                    color='color',
                    height=500,
                    tools=['hover'],
                    width=500), opts.Table(editable=True))
    return widget, point_stream
def LoadAndCrop(video_dict,stretch={'width':1,'height':1},cropmethod='none'):
    
    #if batch processing, set file to first file to be processed
    if 'file' not in video_dict.keys():
        video_dict['file'] = video_dict['FileNames'][0]   
        print(video_dict['file'])
    
    #Upoad file and check that it exists
    video_dict['fpath'] = os.path.join(os.path.normpath(video_dict['dpath']), video_dict['file'])
    if os.path.isfile(video_dict['fpath']):
        print('file: {file}'.format(file=video_dict['fpath']))
        cap = cv2.VideoCapture(video_dict['fpath'])
    else:
        raise FileNotFoundError('{file} not found. Check that directory and file names are correct'.format(
            file=video_dict['fpath']))

    #Get maxiumum frame of file. Note that max frame is updated later if fewer frames detected
    cap_max = int(cap.get(7)) #7 is index of total frames
    print('total frames: {frames}'.format(frames=cap_max))

    #Set first frame
    cap.set(1,video_dict['start']) #first index references frame property, second specifies next frame to grab
    ret, frame = cap.read() 
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)   
    cap.release()
    print('dimensions: {x}'.format(x=frame.shape))

    #Make first image reference frame on which cropping can be performed
    image = hv.Image((np.arange(frame.shape[1]), np.arange(frame.shape[0]), frame))
    image.opts(width=int(frame.shape[1]*stretch['width']),
               height=int(frame.shape[0]*stretch['height']),
              invert_yaxis=True,cmap='gray',
              colorbar=True,
               toolbar='below',
              title="First Frame.  Crop if Desired")
    
    #Create polygon element on which to draw and connect via stream to poly drawing tool
    if cropmethod=='none':
        image.opts(title="First Frame")
        return image,None,video_dict
    
    if cropmethod=='Box':         
        box = hv.Polygons([])
        box.opts(alpha=.5)
        box_stream = streams.BoxEdit(source=box,num_objects=1)     
        return (image*box),box_stream,video_dict
    
    if cropmethod=='HLine':  
        points = hv.Points([])
        points.opts(active_tools=['point_draw'], color='white',size=1)
        pointerXY_stream = streams.PointerXY(x=0, y=0, source=image)
        pointDraw_stream = streams.PointDraw(source=points,num_objects=1)
            
        def h_track(x, y): #function to track pointer
            y = int(np.around(y))
            text = hv.Text(x, y, str(y), halign='left', valign='bottom')
            return hv.HLine(y) * text
        track=hv.DynamicMap(h_track, streams=[pointerXY_stream])
        
        def h_line(data): #function to draw line
            try:
                hline=hv.HLine(data['y'][0])
                return hline
            except:
                hline=hv.HLine(0)
                return hline
        line=hv.DynamicMap(h_line,streams=[pointDraw_stream])
        
        def h_text(data): #function to write ycrop value
            center=frame.shape[1]//2 
            try:
                y=int(np.around(data['y'][0]))
                htext=hv.Text(center,y+10,'ycrop: {x}'.format(x=y))
                return htext
            except:
                htext=hv.Text(center,10, 'ycrop: 0')
                return htext
        text=hv.DynamicMap(h_text,streams=[pointDraw_stream])
        
        return image*track*points*line*text,pointDraw_stream,video_dict   
def LoadAndCrop(dpath, file, stretch_w=1, stretch_h=1, cropmethod='none'):

    #Upoad file and check that it exists
    fpath = dpath + "/" + file
    if os.path.isfile(fpath):
        print('file: ' + fpath)
        cap = cv2.VideoCapture(fpath)
    else:
        raise FileNotFoundError(
            'File not found. Check that directory and file names are correct.')

    #Get maxiumum frame of file. Note that max frame is updated later if fewer frames detected
    cap_max = int(cap.get(7))  #7 is index of total frames
    print('total frames: ' + str(cap_max))

    #Retrieve first frame
    cap.set(
        1, 0
    )  #first index references frame property, second specifies next frame to grab
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cap.release()

    #Make first image reference frame on which cropping can be performed
    image = hv.Image(
        (np.arange(gray.shape[1]), np.arange(gray.shape[0]), gray))
    image.opts(width=int(gray.shape[1] * stretch_w),
               height=int(gray.shape[0] * stretch_h),
               invert_yaxis=True,
               cmap='gray',
               colorbar=True,
               toolbar='below',
               title="First Frame.  Crop if Desired")

    #Create polygon element on which to draw and connect via stream to poly drawing tool
    if cropmethod == 'none':
        image.opts(title="First Frame")
        return image, None, fpath

    if cropmethod == 'Box':
        box = hv.Polygons([])
        box.opts(alpha=.5)
        box_stream = streams.BoxEdit(source=box, num_objects=1)
        return (image * box), box_stream, fpath

    if cropmethod == 'HLine':
        points = hv.Points([])
        points.opts(active_tools=['point_draw'], color='white', size=1)
        pointerXY_stream = streams.PointerXY(x=0, y=0, source=image)
        pointDraw_stream = streams.PointDraw(source=points, num_objects=1)

        def h_track(x, y):  #function to track pointer
            y = int(np.around(y))
            text = hv.Text(x, y, str(y), halign='left', valign='bottom')
            return hv.HLine(y) * text

        track = hv.DynamicMap(h_track, streams=[pointerXY_stream])

        def h_line(data):  #function to draw line
            try:
                hline = hv.HLine(data['y'][0])
                return hline
            except:
                hline = hv.HLine(0)
                return hline

        line = hv.DynamicMap(h_line, streams=[pointDraw_stream])

        def h_text(data):  #function to write ycrop value
            center = gray.shape[1] // 2
            try:
                y = int(np.around(data['y'][0]))
                htext = hv.Text(center, y + 10, 'ycrop: {x}'.format(x=y))
                return htext
            except:
                htext = hv.Text(center, 10, 'ycrop: 0')
                return htext

        text = hv.DynamicMap(h_text, streams=[pointDraw_stream])

        return image * track * points * line * text, pointDraw_stream, fpath