def im(self):
     im = self.cam.get_frame()
     for f in range(10):
         im = self.cam.get_frame()
     im = images.crop_and_mask(im, self.crop, self.mask)
     im = images.bgr_to_gray(im)
     images.save(im, self.log_direc + '{}_original.png'.format(self.i))
     return im
 def mean_im(self):
     ims = []
     for f in range(8):
         im = self.cam.get_frame()
         im = images.crop_and_mask(im, self.crop, self.mask)
         im = images.bgr_to_gray(im)
         ims.append(im)
     images.save(ims[0], self.log_direc + '{}_original.png'.format(self.i))
     mean_im = images.mean(ims)
     # mean_im = images.mask(mean_im, ring_mask)
     images.save(mean_im, self.log_direc + '{}_mean.png'.format(self.i))
     return mean_im
Beispiel #3
0
 def mean_im(self):
     ims = []
     for f in range(8):
         im = ~self.cam.get_frame()
         im = images.crop_and_mask(im, self.crop, self.mask)
         # if f == 0:
         #     ring_mask = images.inrange(images.bgr_to_lab(im), (0, 113, 0),
         #                                (255, 152, 255))
         im = images.bgr_to_gray(im)
         ims.append(im)
     images.save(ims[0], self.log_direc + '{}_original.png'.format(self.i))
     mean_im = images.mean(ims)
     # mean_im = images.mask(mean_im, ring_mask)
     images.save(mean_im, self.log_direc + '{}_mean.png'.format(self.i))
     return mean_im
def run():
    direc = "/media/data/Data/FirstOrder/Interfaces/RecordFluctuatingInterfaceJanuary2020/Quick/first_frames"
    savename = f"{direc}/data_new.hdf5"
    files = filehandling.get_directory_filenames(direc + '/*.png')
    ims = [images.load(f, 0) for f in tqdm(files, 'Loading images')]
    ims = [images.bgr_to_gray(im) for im in ims]
    circles = [images.find_circles(im, 27, 200, 7, 16, 16)
               for im in tqdm(ims, 'Finding Circles')]

    data = dataframes.DataStore(savename, load=False)
    for f, info in tqdm(enumerate(circles), 'Adding Circles'):
        data.add_tracking_data(f, info, ['x', 'y', 'r'])

    calc = statistics.PropertyCalculator(data)
    calc.order()

    lattice_spacing = 10
    x = np.arange(0, ims[0].shape[1], lattice_spacing)
    y = np.arange(0, ims[0].shape[0], lattice_spacing)
    x, y = np.meshgrid(x, y)

    # cgw = get_cgw(data.df.loc[0], 1.85) # k=1.85 looked the best
    cgw = get_cgw(data.df.loc[0], 1.85)

    fields = [coarse_order_field(data.df.loc[f], cgw, x, y)
              for f in tqdm(range(len(ims)), 'Calculating Fields')]

    field_threshold = get_field_threshold(fields, lattice_spacing, ims[0])

    contours = [find_contours(f, field_threshold)
                for f in tqdm(fields, 'Calculating contours')]

    # Multiply the contours by the lattice spacing and squeeze
    contours = [c.squeeze() * lattice_spacing for c in contours]

    # Close contours
    contours = [close_contour(c) for c in contours]

    # Convert to LineString
    contours = [LineString(c) for c in contours]

    # Select the line to query the points across
    print("Select the line to query points")
    ls = LineSelector(ims[0])
    p1, p2 = ls.points
    centre_line = get_extended_centre_line(p1, p2)

    # Distance between query points that determines one end of the frequency
    dL = data.df.loc[0].r.mean() / 10
    L = np.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)
    N_query = int(L/dL)
    xq, yq = np.linspace(p1[0], p2[0], N_query), np.linspace(p1[1], p2[1],
                                                             N_query)
    dL = np.sqrt((xq[1] - xq[0]) ** 2 + (yq[1] - yq[0]) ** 2)
    dists, crosses = zip(
        *[get_dists(xq, yq, c, centre_line) for c in tqdm(contours)])

    # plot_crosses(crosses, ims)

    # Select points from inside red edge to inside red edge across the centre
    # of the tray which is 200mm to convert pixels to mm
    PIX_2_mm = get_pix_2_mm(ims[0])

    plot_fft(dists, dL, PIX_2_mm, data.df.loc[0].r.mean(), cgw)
 def get_frame(self):
     im = self.cam.get_frame()
     im = images.crop_and_mask(im, self.crop, self.mask)
     im = images.bgr_to_gray(im)
     return im
def run(direc, lattice_spacing=5):
    files = filehandling.get_directory_filenames(direc + '/*.png')
    print(files)
    savename = direc + '/data.hdf5'

    N = len(files)

    # load images
    ims = [images.load(f, 0) for f in tqdm(files, 'Loading images')]

    images.display(ims[0])
    # Find Circles
    ims = [images.bgr_to_gray(im) for im in ims]
    circles = [
        images.find_circles(im, 27, 200, 7, 16, 16)
        for im in tqdm(ims, 'Finding Circles')
    ]

    # Save data
    data = dataframes.DataStore(savename, load=False)
    for f, info in tqdm(enumerate(circles), 'Adding Circles'):
        data.add_tracking_data(f, info, ['x', 'y', 'r'])

    # Calculate order parameter
    calc = statistics.PropertyCalculator(data)
    calc.order()

    # Get the course graining width
    cgw = get_cgw(data.df.loc[0]) / 2

    # Create the lattice points
    x = np.arange(0, max(data.df.x), lattice_spacing)
    y = np.arange(0, max(data.df.y), lattice_spacing)
    x, y = np.meshgrid(x, y)

    # Calculate the coarse order fields
    fields = [
        coarse_order_field(data.df.loc[f], cgw, x, y)
        for f in tqdm(range(N), 'Calculating Fields')
    ]

    # Calculate the field threshold
    field_threshold = get_field_threshold(fields, lattice_spacing, ims[0])

    # Find the contours representing the boundary in each frame
    contours = [
        find_contours(f, field_threshold)
        for f in tqdm(fields, 'Calculating contours')
    ]

    # Multiply the contours by the lattice spacing
    contours = [c * lattice_spacing for c in contours]

    # Find the angle of the image to rotate the boundary to the x-axis
    a, c, p1, p2 = get_angle(ims[0])
    print(p1)
    print(p2)
    # Rotate the selection points and the contours by the angle
    p1 = rotate_points(np.array(p1), c, a)
    p2 = rotate_points(np.array(p2), c, a)
    contours = [rotate_points(contour.squeeze(), c, a) for contour in contours]

    xmin = int(p1[0])
    xmax = int(p2[0])
    h = int(p1[1])

    # Get the heights of the fluctuations from the straight boundary
    hs = [
        get_h(contour, ims[0].shape, xmin, xmax, h)
        for contour in tqdm(contours, 'Calculating heights')
    ]

    # Calculate the fourier transforms for all the frames
    L = xmax - xmin
    pixels_to_mms = 195 / L
    print("pixels_to_mms = ", pixels_to_mms)

    # convert to mm
    hs = [h * pixels_to_mms for h in hs]
    L = L * pixels_to_mms
    x = np.linspace(0, L, len(hs[0]))

    np.savetxt(direc + '/x.txt', x)
    np.savetxt(direc + '/hs.txt', hs)

    # k, yplot = get_fourier(hs, L)

    return k, yplot
 def mean_frame(self):
     ims = [self.get_frame() for i in range(10)]
     im = images.mean(ims)
     im = images.bgr_to_gray(im)
     return im
def subtract_bkg(frame, parameters=None, call_num=None):
    '''
    Subtract a background


    Notes
    -----
    This function will subtract a background from the image. It has several 
    options: mean will subtract the average value from the image. img will subtract a preprepared
    background img from the img. Before subtracting the background image it is blurred according to
    the settings. 
    
    N.B. You must apply either a grayscale or color_channel method before the subtract_bkg method. 
    The software subtracts the mean image value, grayscale or color_channel version of the background image which you select from the current image.


    

    subtract_bkg_type
        Type of background substraction to be performed. Options are are 'mean' or 'grayscale','red','green','blue'. 
    subtract_bkg_filename
        filename of background image. If None it will look for a file named moviefilename_bkgimg.png. Otherwise it looks for the filename specified. The filename is assumed to be in the same directory as the movie. Alternatively specify the full path to the file. 
    subtract_bkg_blur_kernel
        An integer n specifying the kernel size (n,n) to be used in blurring bkg image
    subtract_bkg_invert
        Subtract bkg from image or image from background.
    subtract_bkg_norm
        Stretch range of outputted intensities on resultant image to fill 0-255 - True or False               
    
    
    Args
    ----
    frame
        This must be a grayscale / single colour channel image
    parameters
        Nested dictionary like object (same as .param files or output from general.param_file_creator.py
    call_num
        Usually None but if multiple calls are made modifies method name with get_method_key

    Returns
    -------
        grayscale image

    '''

    try:
        method_key = get_method_key('subtract_bkg', call_num=call_num)
        params = parameters['preprocess'][method_key]

        bkgtype = get_param_val(params['subtract_bkg_type'])
        if bkgtype == 'mean':
            mean_val = int(np.mean(frame))
            subtract_frame = mean_val * np.ones(np.shape(frame),
                                                dtype=np.uint8)
            frame2 = frame
        elif bkgtype == 'median':
            median_val = int(np.median(frame))
            subtract_frame = median_val * np.ones(np.shape(frame),
                                                  dtype=np.uint8)
            frame2 = frame
        else:
            # This option subtracts the previously created image which is added to dictionary.
            #These parameters are fed to the blur function
            temp_params = {}
            temp_params['preprocess'] = {
                'blur': {
                    'kernel': get_param_val(params['subtract_bkg_blur_kernel'])
                }
            }
            #Load bkg img
            if params['subtract_bkg_filename'] is None:
                name = parameters['experiment']['video_filename']
                bkg_frame = cv2.imread(name[:-4] +
                                       '_bkgimg.png')  #,cv2.IMREAD_GRAYSCALE)
            else:
                bkg_frame = cv2.imread(
                    params['subtract_bkg_filename'])  #,cv2.IMREAD_GRAYSCALE)

            if bkgtype == 'grayscale':
                subtract_frame = bgr_to_gray(bkg_frame)
            elif bkgtype == 'red':
                subtract_frame = bkg_frame[:, :, 2]
            elif bkgtype == 'green':
                subtract_frame = bkg_frame[:, :, 1]
            elif bkgtype == 'blue':
                subtract_frame = bkg_frame[:, :, 0]

            subtract_frame = crop(subtract_frame, parameters['crop'])

            frame2 = blur(frame, temp_params)
            frame2 = frame2.astype(np.uint8)
            subtract_frame = blur(subtract_frame, temp_params)
            subtract_frame = subtract_frame.astype(np.uint8)

        if get_param_val(params['subtract_bkg_invert']):
            frame2 = cv2.subtract(subtract_frame, frame2)
        else:
            frame2 = cv2.subtract(frame2, subtract_frame)

        if np.max(frame) == 0:
            frame2 = frame

        if get_param_val(params['subtract_bkg_norm']) == True:
            frame2 = cv2.normalize(frame2,
                                   None,
                                   alpha=0,
                                   beta=255,
                                   norm_type=cv2.NORM_MINMAX)

        return frame2
    except Exception as e:
        print(e)
        raise SubtractBkgError(e)
def grayscale(frame, parameters):
    return images.bgr_to_gray(frame)