Ejemplo n.º 1
0
    def preprocess_image(self, i):
        downscale = self.downscale
        lab_frame_image = freeimage.read(self.timepoint_list[i].image_path('bf'))
        lab_frame_image = lab_frame_image.astype(numpy.float32)
        height, width = lab_frame_image.shape[:2]

        try:
            metadata = self.timepoint_list[i].position.experiment.metadata
            optocoupler = metadata['optocoupler']
        except KeyError:
            optocoupler = 1
        mode = process_images.get_image_mode(lab_frame_image, optocoupler=optocoupler)

        #### DownSample the image 
        if downscale > 0 and downscale != 1:#and set_name!='train':        
            #t_size = (int(width / downscale), int(height / downscale))  
            shrink_image = pyramid.pyr_down(lab_frame_image, downscale=downscale)
            #shrink_image = numpy.clip(shrink_image, 0, 40000)   
        else:
            shrink_image = lab_frame_image

        shrink_image = shrink_image.astype(numpy.float32)

        ## scale the image pixel value into a trainable range
        # map image image intensities in range (100, 2*mode) to range (0, 2)
        bf = colorize.scale(shrink_image, min=100, max=2*mode, output_max=2)
        # now shift range to (-1, 1)
        bf -= 1
        return bf
Ejemplo n.º 2
0
def output_aligned_image(image,
                         center_tck,
                         width_tck,
                         keypoints,
                         output_file,
                         t_out=[0.07, 0.15, 0.5, 0.95]):
    """ Make warped pictures and align the keypoints
    """
    #get the alignments for longitudinal_warp_spline
    t_in = calculate_keypoints(keypoints, center_tck)
    aligned_center, aligned_width = worm_spline.longitudinal_warp_spline(
        t_in, t_out, center_tck, width_tck=width_tck)

    #output the image
    warps = warps = worm_spline.to_worm_frame(image,
                                              aligned_center,
                                              width_tck=aligned_width,
                                              width_margin=0,
                                              standard_width=aligned_width)
    mask = worm_spline.worm_frame_mask(aligned_width, warps.shape)

    #change warps to an 8-bit image
    bit_warp = colorize.scale(warps).astype('uint8')
    #make an rgba image, so that the worm mask is applied
    rgba = np.dstack([bit_warp, bit_warp, bit_warp, mask])
    #save the image
    freeimage.write(rgba, output_file)
Ejemplo n.º 3
0
def make_composite_maskfile_batch(data_path,
                                  mask_path,
                                  save_path,
                                  data_str='',
                                  mask_str=''):
    data_fns = [
        data_f for data_f in sorted(os.listdir(data_path))
        if data_str in data_f
    ]

    print('importing data images')
    data_imgs = np.array([(freeimage.read(data_path + os.path.sep + data_f))
                          for data_f in data_fns])
    print('importing mask images')
    mask_imgs = np.array([
        freeimage.read(mask_path + os.path.sep + mask_f) > 0
        for data_f in data_fns for mask_f in sorted(os.listdir(mask_path))
        if data_f[0:15] in mask_f if mask_str in mask_f
    ])
    try:
        os.stat(save_path)
    except:
        os.mkdir(save_path)

    print('generating and saving composites')
    comp = np.zeros(np.shape(data_imgs[[0]]))
    print('got here')
    for d_img, m_img, data_f in zip(data_imgs, mask_imgs, data_fns):
        comp = colorize.scale(np.copy(d_img), output_max=254)
        comp[m_img] = 255
        #if data_f==data_fns[2]: return
        freeimage.write(
            comp.astype('uint8'),
            save_path + os.path.sep + data_f[:-4] + 'composite' + data_f[-4:])
Ejemplo n.º 4
0
def warp_image(spine_tck, width_tck, image_file, warp_file):
    """Warp an image of a worm to a specified place

    Parameters:
        spine_tck: parametric spline tck tuple corresponding to the centerline of the worm
        width_tck: non-parametric spline tck tuple corresponding to the widths of the worm
        image_file: path to the image to warp the worm from
        warp_file: path where the warped worm image should be saved to
    """

    image = freeimage.read(image_file)
    warp_file = pathlib.Path(warp_file)

    #730 was determined for the number of image samples to take perpendicular to the spine
    #from average length of a worm (as determined from previous tests)
    warped = resample.warp_image_to_standard_width(image, spine_tck, width_tck,
                                                   width_tck,
                                                   int(tck[0][-1] // 5))
    #warped = resample.sample_image_along_spline(image, spine_tck, 730)
    mask = resample.make_mask_for_sampled_spline(warped.shape[0],
                                                 warped.shape[1], width_tck)
    warped = colorize.scale(warped).astype('uint8')
    warped[~mask] = 255

    print("writing warped worm to :" + str(warp_file))
    #return warped
    if not warp_file.exists():
        warp_file.parent.mkdir(exist_ok=True)

    freeimage.write(
        warped, warp_file
    )  # freeimage convention: image.shape = (W, H). So take transpose.
Ejemplo n.º 5
0
 def normalized_bf_image(self, i):
     bf = freeimage.read(self.timepoint_list[i].image_path('bf'))
     mode = process_images.get_image_mode(bf, optocoupler=self.timepoint_list.optocoupler(i))
     # map image image intensities in range (100, 2*mode) to range (0, 2)
     bf = colorize.scale(bf, min=100, max=2*mode, output_max=2)
     # now shift range to (-1, 1)
     bf -= 1
     return bf
Ejemplo n.º 6
0
def plot(positions, values, radius, rw):
    colors = colorize.color_map(colorize.scale(values, output_max=1))
    circles = [
        Circle(x, y, radius, color, metadata=(x, y, value))
        for (x, y), color, value in zip(positions, colors, values)
    ]
    for c in circles:
        rw.image_scene.addItem(c)
    return circles
Ejemplo n.º 7
0
 def _feature_plot_data(worms, x_feature, y_feature, color_by='lifespan'):
     x_feature_vals = worms.get_feature(x_feature)
     y_feature_vals = worms.get_feature(y_feature)
     color_vals = colorize.scale(worms.get_feature(color_by), output_max=1)
     colors = colorize.color_map(color_vals, uint8=False)
     out = []
     for x, y, color in zip(x_feature_vals, y_feature_vals, colors):
         out.append((x, y, color))
     return out
Ejemplo n.º 8
0
def normalized_bf_image(timepoint):
    """Given a timepoint, return a normalized brightfield image."""
    bf = freeimage.read(timepoint.image_path('bf'))
    mode = process_images.get_image_mode(
        bf, optocoupler=timepoint.position.experiment.metadata['optocoupler'])
    # map image image intensities in range (100, 2*mode) to range (0, 2)
    bf = colorize.scale(bf, min=100, max=2 * mode, output_max=2)
    # now shift range to (-1, 1)
    bf -= 1
    return bf
Ejemplo n.º 9
0
def scale_image(image, mag='5x'):
    if mag is '10x':
        mask = tenX_mask(image.shape).astype(bool)
        bf = image[mask]
        mode = np.bincount(bf.flat)[1:].argmax() + 1
        bf = image.astype(np.float32)
        bf -= 200
        bf *= (24000 - 200) / (mode - 200)
        bf8 = colorize.scale(bf, min=600, max=26000, gamma=1, output_max=255)

    else:
        mode = np.bincount(image.flat)[1:].argmax() + 1
        bf = image.astype(np.float32)
        bf -= 200
        bf *= (24000 - 200) / (mode - 200)
        bf8 = colorize.scale(bf,
                             min=600,
                             max=26000,
                             gamma=0.72,
                             output_max=255)

    return bf8
Ejemplo n.º 10
0
def get_cost_image(image, optocoupler, image_gamma, center_tck, width_tck,
                   downscale, gradient_sigma, sigmoid_midpoint,
                   sigmoid_growth_rate, edge_weight):
    """Trace the edges of a worm and return a new center_tck and width_tck.

    Parameters:
        image: ndarray of the brightfield image
        optocoupler: optocoupler magnification (to correctly calculate the image
            vignette)
        center_tck: spline defining the pose of the worm.
        width_tck: spline defining the distance from centerline to worm edges.
        image_gamma: gamma value for intensity transform to highlight worm edges
        downscale: factor by which to downsample the image
        gradient_sigma: sigma for gaussian gradient to find worm edges
        sigmoid_midpoint: midpoint of edge_highlighting sigmoid function for
            gradient values, expressed as a percentile of the gradient value
            over the whole image.
        sigmoid_growth_rate: steepness of the sigmoid function.
        edge_weight: how much to weight image edge strength vs. distance from
            the average widths in the cost function.

    Returns: image defining the cost function for edge tracing
    """
    # normalize, warp, and downsample image
    image = process_images.pin_image_mode(image, optocoupler=optocoupler)
    image = colorize.scale(image,
                           min=600,
                           max=26000,
                           gamma=image_gamma,
                           output_max=1)
    warped = worm_spline.to_worm_frame(image,
                                       center_tck,
                                       width_tck,
                                       width_margin=40)
    warped = pyramid.pyr_down(warped, downscale=downscale)

    # calculate the edge costs
    gradient = ndimage.gaussian_gradient_magnitude(warped, gradient_sigma)
    gradient = sigmoid(gradient, numpy.percentile(gradient, sigmoid_midpoint),
                       sigmoid_growth_rate)
    gradient = gradient.max() - abs(gradient)

    # penalize finding edges away from the width along the worm
    widths = (interpolate.spline_interpolate(width_tck,
                                             warped.shape[0])) / downscale
    centerline_index = (warped.shape[1] - 1) / 2
    distance_from_centerline = abs(
        numpy.arange(0, warped.shape[1]) - centerline_index)
    distance_from_average = abs(
        numpy.subtract.outer(widths, distance_from_centerline))
    return edge_weight * gradient + distance_from_average
Ejemplo n.º 11
0
def warp_image(spine_tck, width_tck, image, warp_file):

    #image = freeimage.read(image_file)

    #730 was determined for the number of image samples to take perpendicular to the spine
    #from average length of a worm (as determined from previous tests)
    warped = resample.warp_image_to_standard_width(image, spine_tck, width_tck,
                                                   width_tck, 730)
    #warped = resample.sample_image_along_spline(image, spine_tck, warp_width)
    mask = resample.make_mask_for_sampled_spline(warped.shape[0],
                                                 warped.shape[1], width_tck)
    warped = colorize.scale(warped).astype('uint8')
    warped[~mask] = 255

    print("writing warped worm to :" + str(warp_file))
    #return warped
    freeimage.write(
        warped, warp_file
    )  # freeimage convention: image.shape = (W, H). So take transpose.
Ejemplo n.º 12
0
def convert_to_8bit(
    data_path,
    save_path,
    filter_str=''
):  #Scales based on the min and max OF EACH IMAGE!!! (NOT STANDARD ACROSS ALL); TODO EXTRA MODE FOR THIS)
    data_fns = [
        data_f for data_f in sorted(os.listdir(data_path))
        if filter_str in data_f
    ]
    data_imgs = np.array([
        freeimage.read(data_path + os.path.sep + data_f) for data_f in data_fns
    ])
    for data_f, d_img in zip(data_fns, data_imgs):
        converted_img = colorize.scale(np.copy(d_img),
                                       min=d_img.min(),
                                       max=d_img.max(),
                                       output_max=255).astype('uint8')
        freeimage.write(
            converted_img,
            save_path + os.path.sep + data_f[:-4] + '_8bit' + data_f[-4:])
Ejemplo n.º 13
0
def _timecourse_plot_data(worms,
                          feature,
                          min_age=-numpy.inf,
                          max_age=numpy.inf,
                          age_feature='age',
                          color_by='lifespan',
                          color_map=None):

    if color_map is None:
        color_map = lambda array: colorize.color_map(array, uint8=False)

    time_ranges = worms.get_time_range(feature, min_age, max_age, age_feature)
    if color_by is None:
        color_vals = [0] * len(time_ranges)
    else:
        color_vals = colorize.scale(worms.get_feature(color_by), output_max=1)
    colors = color_map(color_vals)
    out = []
    for time_range, color in zip(time_ranges, colors):
        x, y = time_range.T
        out.append((x, y, color))
    return out
Ejemplo n.º 14
0
def preprocess_image(timepoint, downscale):
    img_path = timepoint.image_path('bf')
    lab_frame_image = freeimage.read(img_path)
    lab_frame_image = lab_frame_image.astype(numpy.float32)
    height, width = lab_frame_image.shape[:2]
    objective, optocoupler, magnification, temp = get_metadata(timepoint)

    mode = process_images.get_image_mode(lab_frame_image,
                                         optocoupler=optocoupler)
    #### DownSample the image
    if downscale > 0 and downscale != 1:  #and set_name!='train':
        shrink_image = pyramid.pyr_down(lab_frame_image, downscale=downscale)
        #shrink_image = numpy.clip(shrink_image, 0, 40000)
    else:
        shrink_image = lab_frame_image

    shrink_image = shrink_image.astype(numpy.float32)

    ## scale the image pixel value into a trainable range
    # map image image intensities in range (100, 2*mode) to range (0, 2)
    bf = colorize.scale(shrink_image, min=100, max=2 * mode, output_max=2)
    # now shift range to (-1, 1)
    bf -= 1
    return bf