Beispiel #1
0
def contrast_stretch():

    img = data.moon()
    p2, p98 = np.percentile(img, (2, 58))
    #img2 = exposure.rescale_intesity(img, in_range=(p2,p98))

    img2 = (img.astype(np.float32) - p2) * 255 / (p98 - p2)
    img2[img2 < 0] = 0
    img2[img2 > 255] = 255
    img2 = img2.astype(np.uint8)

    fig, (ax, ax2) = plt.subplots(1, 2)
    ax.imshow(img, cmap="gray")
    ax2.imshow(img2, cmap="gray")

    #Display_histogram
    img2 = img_as_float32(img2)
    img = img_as_float32(img)
    fig, ax = plt.subplots()
    #img.ravel() -> splaszczenie obrazu wielowymiarowego
    ax.hist(img2.ravel(), bins=256, histtype="bar", color='blue')
    ax.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0))
    ax.set_xlim(0, 1)
    ax.grid(True)

    #dystrybuatna
    fig, ax = plt.subplots()
    cdf, bins = exposure.cumulative_distribution(img2, 256)
    ax.plot(bins, cdf, 'r')
    ax.grid(True)
Beispiel #2
0
    def generate_mov2art(img_mov, verbose=True, radius_max=60, use_normal=True):
        """Generate geometric augmentation and its inverse."""
        shape = img_mov.shape
        img_mov_float = img_as_float32(img_mov)
        edge_mask = canny(img_mov_float)

        if use_normal:
            c = np.random.normal(0.7, 0.3)
        else:
            c = np.random.random()

        if verbose:
            print("Scalar: {}".format(c))

        mov2art = c * DisplacementField.generate(
            shape,
            approach="edge_stretching",
            edge_mask=edge_mask,
            interpolation_method="rbf",
            interpolator_kwargs={"function": "linear"},
            n_perturbation_points=6,
            radius_max=radius_max,
        )

        return mov2art
Beispiel #3
0
 def _imagesProcessing(self, tif):
     """
     Process each images of the stack contained in one .tif file.
     Warning data type :
     https://scikit-image.org/docs/dev/user_guide/data_types.html#data-types
     """
     tif32 = util.img_as_float32(tif)
     N = tif32.shape[0]
     tifAvg = None
     imCount = 0
     for image in tif32:
         im = ndimage.median_filter(
             image, self.filterSize
         )  #filters.median(image, np.ones(self.filterSize))
         #           #Facultactive rescaling
         #            try:
         #                im = transform.rescale(im, self.rescaleRatio, anti_aliasing=True)
         #            except:
         #                print 'failed rescale'
         if tifAvg is not None:
             tifAvg += im / N
         else:
             h, w = im.shape
             tifAvg = np.ones((h, w),
                              np.float32)  #Should we really use ones ?
             tifAvg += im / N
         imCount += 1
     return tifAvg
def read_image(path):
    try:
        img = io.imread(path)
        return (transform.rescale(util.img_as_float32(img),
                                  0.02,
                                  multichannel=True).reshape(-1), path)
    except:
        return (None, path)
Beispiel #5
0
def img_grayscale_float(img_grayscale_uint):
    """Generate a float32 version of the grayscale image."""
    img_out = img_as_float32(img_grayscale_uint, force_copy=True)

    assert img_out.ndim == 2
    assert img_out.dtype == np.float32
    assert np.all(img_out >= 0) and np.all(img_out <= 1)

    return img_out
Beispiel #6
0
def load_image_and_blur(filename):
    image = cv2.imread(filename.decode(), 0)
    image = dilation(image)  # [0,0,255,0,0] => [0,255,255,255,0]
    image = dilation(image)
    image = img_as_float32(image)
    image = cv2.resize(image, (56, 56))
    image = cv2.GaussianBlur(image, (5, 5), 0)  # Blur image
    image = image[:, :, np.newaxis]  # TF insists on 3rd dimension.
    return image
 def __call__(self, image, target=None):
     size, im_scale = self.get_size(image.shape[:2])
     image = util.img_as_float32(T.resize(image, size))
     if target is None:
         return image
     target = target.resize(image.shape[:2])
     # target.im_scale = im_scale
     target.add_field("scale", im_scale)
     return image, target
Beispiel #8
0
def process(pth):

    print(f'\nProcessing {pth}')

    save_pth = pth / 'reg_stacks'
    #tmat_pth = pth / 'transformation_matrices'
    try:
        save_pth.mkdir()
        #tmat_pth.mkdir()
    except FileExistsError:
        ex('Save File for reg stacks or tmats already exists. Delete and re-run.'
           )

    #tell pystack reg that we will use a translational transformation
    #there shouldn't be intra-volume rotation or shear (there might be for rod blink)
    sr = StackReg(StackReg.TRANSLATION)
    #register to the first slice and output the transfomation matrix without transforming
    #iterate through the files in the stacks folder
    files = pth.glob('*.tif')
    loop_starts = time.time()

    for i, file in enumerate(files):
        #start_time = time.time()
        print(f'Processing: {file}')
        #Intravolume registration of the fixed volume

        #load first stack and do a 3d gaussian blur with a sigma=1
        #str needed for imread, otherwise only one frame is loaded
        fixed = io.imread(str(file))  #had gauss(), testing

        t_mats = sr.register_stack(gauss(fixed), reference='first', n_frames=1)
        #remove the x shift from all the matrices - horizontal movement isn't relevant here,
        #the volume should be acquired quickly enough that this isn't a problem.
        t_mats[:, 0, -1] = 0
        fixed = sr.transform_stack(fixed, tmats=t_mats)

        #Using previous to see if I could get rid of wigge. Didn't seem to work.
        #t_mats = sr.register_stack(gauss(fixed), reference='previous')
        #t_mats[:,1,-1] = 0
        #fixed = sr.transform_stack(fixed, tmats=t_mats)
        #save the register fixed volume in the parent directory for reference
        save_name = save_pth / f'reg_{file.name}'
        #io.imsave(arr=img_as_uint(fixed), fname=str(save_name))
        io.imsave(arr=img_as_float32(fixed), fname=str(save_name))
        #get fixed out of memory - may not be worth the time?
        print(f'Intravolume registration complete. File saved at {save_name}')

        #end_time = time.time()
        #print(f'{file} was processed in {(end_time - start_time):.2f}s. \
        #\n{((end_time - loop_starts)/60):.2f} minutes have elapsed.')

        #de;ete emumerate
        #if i==4:
        #ex('auto break')
    end_time = time.time()
    print(f'Run took {(end_time-loop_starts)/60:.2f} minutes')
Beispiel #9
0
def to_pytorch_from_uint8(img):
    """
  Convert from uint8 images, with standard dimension order of [h,w,c]
  To PyTorch format, float32, dimension order of [c,h,w]

  """
    order = (2, 0, 1)
    img = img_as_float32(img)  # convert from uint8 to float 32
    img = np.transpose(img, order)
    return img
Beispiel #10
0
def copy_image(path):
    Path(os.path.join(target_dir,
                      os.path.split(path)[0])).mkdir(parents=True,
                                                     exist_ok=True)
    img = io.imread(os.path.join(datapath, path))
    io.imsave(
        os.path.join(target_dir,
                     os.path.splitext(path)[0] + '.png'),
        util.img_as_ubyte(
            transform.rescale(util.img_as_float32(img), 0.1,
                              multichannel=True)))
    def __data_generation(self, batch_filenames):
        """Data generation method

        Parameters
        ----------
        batch_filenames : list
            List of strings containing filenames to read. Note that, for each noisy image filename there must be a clean
            image with same filename.

        Returns
        -------
        noisy_batch : :class:`numpy.ndarray`
            Batch of noisy images.
        clean_batch : :class:`numpy.ndarray`
            Batch of reference images.
        """
        # Noised image and ground truth initialization
        inp_batch = []
        ref_batch = []

        for filename in batch_filenames:
            filepath = os.path.join(self.path, 'ref', filename)
            ref = imread(filepath)
            ref = img_as_float32(ref)

            if ref.ndim == 3 and ref.shape[-1] == 3 and self.n_channels == 1:
                # Converts RGB to Gray
                ref = rgb2gray(ref)
            if ref.ndim == 2 and self.n_channels == 1:
                # Expand last dim if image is grayscale
                ref = np.expand_dims(ref, axis=-1)
            elif ref.ndim == 2 and self.n_channels == 3:
                raise ValueError(
                    "Expected RGB image but got Grayscale (image shape: {})".
                    format(ref.shape))
            inp = ref.copy()

            for noise_function, noise_arg in zip(self.noise_functions,
                                                 self.noise_args):
                # Adds noise to the reference.
                inp = noise_function(inp, *noise_arg)

            # Applies preprocessing functions in order
            for func in self.preprocessing:
                inp, ref = func(inp, ref)

            ref_batch.append(ref)
            inp_batch.append(inp)
        inp_batch = np.stack(inp_batch)
        ref_batch = np.stack(ref_batch)
        if len(inp_batch.shape) > 4:
            inp_batch = inp_batch.reshape([-1, *inp_batch.shape[2:]])
            ref_batch = ref_batch.reshape([-1, *ref_batch.shape[2:]])
        return inp_batch, ref_batch
def plt_fnc(indx=77308, resize=False):
    plt.clf()
    img = io.imread(
        os.path.join(
            r'Z:\ftp\sprayers\IntelligentSprayTechnology\Connor_Field_Data\2019_ImageLibrary_FieldLogs_Motec',
            os.path.splitext(fn_time_crop_list[indx][0])[0] + '.bmp'))
    if resize:
        img = util.img_as_ubyte(
            transform.rescale(util.img_as_float32(img), 0.1,
                              multichannel=True))
    plt.imshow(img)
    return img
Beispiel #13
0
def load_dataset_images(root):
    gt, bl = list_dataset_images(root)

    for i, f in enumerate(bl):
        logger.debug("reading '{}'".format(f))
        I = imageio.imread(f)
        if I.ndim == 3:
            I = rgb2gray(I)
        I = img_as_float32(I)
        bl[i] = I

    if gt is not None:
        gt = imageio.imread(gt)
        if gt.ndim == 3:
            gt = rgb2gray(gt)
        gt = img_as_float32(gt)

        # sanity check
        s_gt = gt.shape
        if any([im.shape != s_gt for im in bl]):
            raise ValueError("blurred image has a different size")

    return gt, bl
Beispiel #14
0
def test_noise(ntype, fname):
    img = io.imread(fname)
    img = img_as_float32(img)
    img2 = add_noise(ntype, img)

    fig, (ax, ax2) = plt.subplots(1, 2)
    ax.imshow(img, cmap="gray")
    ax.set_title('original')
    ax2.imshow(img2, cmap="gray")
    ax2.set_title('noisy')
    ax.axis('off')
    ax2.axis('off')
    fig.tight_layout()
    plt.show(block=False)
def main():
    source = askdirectory()
    if source == '':
        ex("\n\nExited: No file path selected\n\n")
    #sorting(Path(os.path.abspath(source)))
    src = Path(source)
    stack = im_open(src)
    avg_stack = timeseries(stack)
    save_pth = src / 'timeseries'
    save_pth.mkdir()
    io.imsave(arr=img_as_float32(avg_stack),
              fname=str(save_pth / 'timeseries.tif'))

    print('\n\n\n\t\t\t\t---------\n\t\t\t\tCompleted\n\t\t\t\t---------')
Beispiel #16
0
def test_optic_flow(frame1, frame2):
    # im1 = img_as_ubyte(frame1)
    # im2 = img_as_ubyte(frame2)
    im1 = cv2.imread('im1.png')
    im2 = cv2.imread('im2.png')
    frame1 = img_as_float32(im1)
    frame2 = img_as_float32(im2)
    prvs = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
    next = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)
    flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5,
                                        1.2, 0)

    flow[..., 0] /= flow.shape[1] / 2
    flow[..., 1] /= flow.shape[0] / 2
    flow *= -1
    for i in range(flow.shape[0]):
        for j in range(flow.shape[1]):
            flow[i, j, 0] += (j / flow.shape[1] * 2 - 1)
            flow[i, j, 1] += (i / flow.shape[0] * 2 - 1)

    print(flow.shape)

    torch_frame1 = torch.unsqueeze(torch.tensor(frame1).permute(2, 0, 1), 0)

    # print(frame1.shape)
    # print(torch_frame1.shape)
    # print(torch_frame1)
    flow = flow.astype(np.float32, copy=False)
    est_frame2 = func.grid_sample(torch_frame1,
                                  torch.unsqueeze(torch.tensor(flow), 0))
    res_img = img_as_ubyte(est_frame2[0].permute(1, 2, 0).numpy())
    cv2.imwrite('est_frame2.png', res_img)
    # flow_len = np.expand_dims(np.sqrt((flow[...,0]**2 + flow[...,1]**2)), 2)
    # flow /= flow_len
    # print(flow)
    pass
    exit(0)
Beispiel #17
0
def run(params):
	RTimageLocation = params['inputRTImagePath']
	GTimageLocation = params['inputGTImagePath']
	resultLocation = params['resultPath']
	resultLocationAdj = params['resultPathAdj']
	
	# Checking existence of temporary files (individual channels)
	if not os.path.exists(RTimageLocation):
		print(f'Error: {RTimageLocation} does not exist')
		return; 
	if not os.path.exists(GTimageLocation):
		print(f'Error: {GTimageLocation} does not exist')
		return; 
		
	# Loading input images
	RTData = imread(RTimageLocation)
	GTData = imread(GTimageLocation)
	print(f'Dimensions of Restored image: {RTData.shape}')
	print(f'Dimensions of GT image: {GTData.shape}')
	
	# Histogram matching
	matched_GTData = match_histograms(GTData, RTData).astype(RTData.dtype)
	
	# MSE measurement
	# valMSE = skimage.measure.compare_mse(RTData, GTData) # deprecated in scikit-image 0.18 
	valMSE = mean_squared_error(RTData, matched_GTData)
	print(f'___ MSE = {valMSE} ___')	# Value appears in the log if Verbosity option is set to 'Everything'
	
	# SSIM measurement
	outFullSSIM = structural_similarity(RTData, matched_GTData, full=True)
	
	# Extracting mean value (first item)
	outMeanSSIM = outFullSSIM[0]
	print(f'___ Mean SSIM = {outMeanSSIM} ___')
	
	# Extracting map (second item)
	outSSIM = outFullSSIM[1]
	print(f'Bit depth of SSIM array: {outSSIM.dtype}')
	
	# Convert output array whose range is [0-1] to adjusted bit range (8- or 16-bit)
	if RTData.dtype is np.dtype('u2'):
		outputData = img_as_uint(outSSIM)
	elif RTData.dtype is np.dtype('f4'):
		outputData = img_as_float32(outSSIM)	# necessary?
	else:
		outputData = img_as_ubyte(outSSIM)
	
	imsave(resultLocation, outputData)	
	imsave(resultLocationAdj, matched_GTData)
Beispiel #18
0
def align_with(image, ref_matrix, ref_file):
    """
    Given a FITS file it will open the file and align to the reference image
    matrix and rewrite the file.
    It uses the astroalign package that align stellar astronomical images with
    an 3 point matching (triangle). It need above about 10 stellar sources in
    an image (based on the tests).

    # This function takes the matrix directly (instead of path to file)
    because of performance. This function in meant to be used within a loop,
    with this the ref_matrix needs to be loaded just once.

    Parameters
    ----------
        image : str
            Path to image to align with the reference.
        ref_matrix : Numpy 2D array
            Reference image.
        ref_name : str
            Name of reference FITS file.

    Returns
    -------
        None.

    File transformation:
        Re-write FITS file pointed at image variable with updated header.
    """
    # Loading

    data = fits.getdata(image)
    data = img_as_float32(data)  # Converting to float to avoid scikitimage bug
    # Issue #4525

    header = fits.getheader(image)
    new_image = "a" + image

    # Aligning

    aligned_image = astroalign.register(data, ref_matrix)

    # Re-write file and update header

    header["ALIGNED-TO"] = ref_file

    fits.writeto(new_image, aligned_image, header)
    os.remove(image)
    def __data_generation(self, batch_filenames):
        """Data generation method

        Parameters
        ----------
        batch_filenames : list
            List of strings containing filenames to read.

        Returns
        -------
        noisy_batch : :class:`numpy.ndarray`
            Batch of noisy images.
        """
        # Noised image and ground truth initialization
        inp_batch = []
        ref_batch = []

        for filename in batch_filenames:
            filepath = os.path.join(self.path, 'in', filename)
            module_logger.debug("Loading image located on {}".format(filepath))
            inp = imread(filepath)
            inp = img_as_float32(inp)

            if inp.ndim == 3 and inp.shape[-1] == 3 and self.n_channels == 1:
                # Converts RGB to Gray
                inp = rgb2gray(inp)
            if inp.ndim == 2 and self.n_channels == 1:
                # Expand last dim if image is grayscale
                inp = np.expand_dims(inp, axis=-1)
            elif inp.ndim == 2 and self.n_channels == 3:
                raise ValueError(
                    "Expected RGB image but got Grayscale (image shape: {})".
                    format(inp.shape))

            for func in self.preprocessing:
                # Preprocessing pipeline
                inp = func(inp)

            # Generates target from input
            inp, ref = self.target_fcn(inp)
            ref_batch.append(ref)
            inp_batch.append(inp)
        inp_batch = np.array(inp_batch)
        ref_batch = np.array(ref_batch)
        module_logger.debug("Data shape: {}".format(inp_batch.shape))
        return inp_batch, ref_batch
Beispiel #20
0
def align_all_images(images_folder, ref_file=None):
    """
    Align all FITS stellar images to reference file. If reference file is set
    to None it uses the first image in the folder.

    # Wraps align_with function.

    Parameters
    ----------
        images_folder : str
            Path to folder with images to align.
        ref_file : str
            Path to FITS with reference field. Default is None, so it takes
            the first file of the folder.

    Returns
    -------
        None.

    File transformation
    -------------------
        Re-write FITS files with aligned version.
    """
    os.chdir(images_folder)
    images = glob("*.fits")
    images.sort()

    if ref_file == None:
        ref_file = images[0]

    ref_image = img_as_float32(fits.getdata(ref_file))
    N = len(images)

    print(
        f"Aligning {N} images with file {ref_file} in folder {images_folder}.\n"
    )

    for i, im in enumerate(images, start=1):
        print(f"Aligning: {im} ({i} of {N}).")
        align_with(im, ref_image, ref_file)

    print(f"\n Finished alignment of {images_folder} images.")

    os.chdir("../")
Beispiel #21
0
def quilt(filenames, block_size, num_block, mode, sequence=False):
    textures = np.stack(
        [util.img_as_float32(Image.open(path)) for path in filenames])

    if textures.ndim < 4:
        textures = np.expand_dims(textures, -1)

    overlap = block_size // 4
    num_blockHigh, num_blockWide = num_block

    h = (num_blockHigh * block_size) - (num_blockHigh - 1) * overlap
    w = (num_blockWide * block_size) - (num_blockWide - 1) * overlap
    c = textures[0].shape[2]

    res = np.zeros((h, w, c))

    for i in range(num_blockHigh):
        print(f'{i}/{num_blockHigh}')
        for j in range(num_blockWide):
            # print(i, j)
            # print(f'{i * num_blockHigh + j}/{num_blockHigh * num_blockWide}')
            y = i * (block_size - overlap)
            x = j * (block_size - overlap)

            if i == 0 and j == 0 or mode == "Random":
                patch = textures[np.random.randint(0, len(textures)
                                                   ), :block_size, :block_size]
            elif mode == "Best":
                patch = randomBestPatch(textures, block_size, overlap, res, y,
                                        x)
            elif mode == "Cut":
                patch = randomBestPatch(textures, block_size, overlap, res, y,
                                        x)
                patch = minCutPatch(patch, block_size, overlap, res, y, x)

            res[y:y + block_size, x:x + block_size] = patch

    print(res.shape, res.min(), res.max())
    if c == 1:
        res = res.squeeze(-1)
    image = Image.fromarray((res * 255).astype(np.uint8))
    return image
Beispiel #22
0
    def predict(self, images, object_extreme_points, torch_device=None, batch_size=4, num_workers=0):
        """
        Predict DEXTR masks for objects identified in images by extreme points.

        :param images: a list of N images; images can be PIL Images or NumPy arrays
        :param object_extreme_points: extreme points for each object/image as an array of `(N, 4, [y,x])` NumPy arrays
        :param torch_device: PyTorch device used
        :param batch_size: batch size used (relevant when using a large number of images)
        :param num_workers: number of background processes used by the data pipeline
        :return: mask for each image in images, where each mask is a NumPy array
        """
        if torch_device is None:
            torch_device = next(self.net.parameters()).device
        ds = _DextrInferenceDataset(images, object_extreme_points, transform=self.__inference_transforms)
        loader = torch.utils.data.DataLoader(ds, batch_size=batch_size, num_workers=num_workers)
        sample_i = 0
        predictions = []
        with torch.no_grad():
            for batch in loader:
                input = batch['input'].to(torch_device)
                crop_yx = batch['crop_yx'].detach().cpu().numpy()

                pred_logits = self.net(input)['out']

                pred_prob = torch.sigmoid(pred_logits).detach().cpu().numpy()

                for i in range(len(crop_yx)):
                    image_size = ds.image_sizes[sample_i]
                    pred_pil = dextr_transforms.paste_mask_into_image(
                        image_size, pred_prob[i, 0, :, :], crop_yx[i])

                    pred_pil_arr = img_as_float32(np.array(pred_pil))

                    predictions.append(pred_pil_arr)

                    sample_i += 1

        return predictions
Beispiel #23
0
def nissl_volume(path=None):
    """Output a dataset created of 528 consecutive coronal slices with Nissl staining.

    Parameters
    ----------
    path : str or None or LocalPath
        An absolute path to the underlying .npy file. If not speficied
        then a default one used.

    Returns
    -------
    x_atlas : np.ndarray
        An array of shape (528, 320, 456, 1) representing the consecutive coronal slices. The dtype is np.float32

    """
    path = path or (GLOBAL_CACHE_FOLDER / "nissl.npy")

    atlas_volume = np.load(str(path)).astype(
        "uint8")  # saved as float but actually just integers
    atlas_volume_float = np.array([
        img_as_float32(slc) for slc in atlas_volume
    ])  # deals with scaling too!

    return atlas_volume_float[:, :, :, np.newaxis]
Beispiel #24
0
def lowpass_filter(dname, fname):
    fname = dname + fname
    img = io.imread(fname)
    img = img_as_float32(img)
    img = add_noise("s&p", img)
    if img.ndim > 2:
        img = color.rgb2gray(img)

    #sigma -> jak szybko gasna
    #mode reflect -> odbija sie symetrycznie na 2 strone
    #granice obrazu sa odbiciem symetrycznym
    #imflt.gaussian - > inne pixele gasna odnosnie odleglosci od srodka pixela
    img = imflt.gaussian(img, sigma=2, mode='reflect')
    #img2 = imflt.median(img,mph.disk(2))

    fig, (ax, ax2) = plt.subplots(1, 2)
    ax.imshow(img, cmap="gray")
    ax.set_title('original')
    ax2.imshow(img2, cmap="gray")
    ax2.set_title('noisy')
    ax.axis('off')
    ax2.axis('off')
    fig.tight_layout()
    plt.show(block=False)
Beispiel #25
0
    def test_rgba2rgb_dtype(self):
        rgba = self.img_rgba.astype('float64')
        rgba32 = img_as_float32(rgba)

        assert rgba2rgb(rgba).dtype == rgba.dtype
        assert rgba2rgb(rgba32).dtype == rgba32.dtype
Beispiel #26
0
    def test_rgb2hsv_dtype(self):
        rgb = img_as_float(self.img_rgb)
        rgb32 = img_as_float32(self.img_rgb)

        assert rgb2hsv(rgb).dtype == rgb.dtype
        assert rgb2hsv(rgb32).dtype == rgb32.dtype
Beispiel #27
0
def main(
    load_name: Param("load learner name", str) = "em_save",
    save_dir: Param("dir to save to:",
                    str) = "/scratch/bpho/results/emsynth_crap",
    gpu: Param("GPU to run on", str) = 0,
):
    torch.cuda.set_device(gpu)

    bs = 1
    size = 1920
    data = get_data(bs, size)

    arch = models.resnet34
    wd = 1e-3
    learn = unet_learner(data,
                         arch,
                         wd=wd,
                         loss_func=feat_loss,
                         metrics=superres_metrics,
                         callback_fns=LossMetrics,
                         blur=True,
                         norm_type=NormType.Weight,
                         model_dir=model_path)
    gc.collect()

    learn = learn.load(load_name)

    test_files = Path(
        '/scratch/bpho/datasources/EM_manually_aquired_pairs_01242019/')
    test_hr = list((test_files / 'aligned_hr').glob('*.tif'))
    test_lr = list((test_files / 'aligned_lr').glob('*.tif'))
    results = Path(save_dir)

    if results.exists(): shutil.rmtree(results)
    results.mkdir(parents=True, mode=0o775, exist_ok=True)

    def get_key(fn):
        return fn.stem[0:(fn.stem.find('Region') - 1)]

    hr_map = {get_key(fn): fn for fn in test_hr}
    lr_map = {get_key(fn): fn for fn in test_lr}

    ssims = []
    psnrs = []
    for k in progress_bar(hr_map):
        hr_fn, lr_fn = hr_map[k], lr_map[k]
        hr_img = PIL.Image.open(hr_fn)
        lr_img = PIL.Image.open(lr_fn)
        lr_img_data = img_as_float32(lr_img)
        lr_up_data = npzoom(lr_img_data, 4, order=1)
        lr_up_img = Image(tensor(lr_up_data[None]))
        hr_pred_img, aaa, bbb = learn.predict(lr_up_img)
        pred_img = PIL.Image.fromarray(
            img_as_ubyte(np.array(hr_pred_img.data))[0, :, :])

        lr_img.save(results / f'{k}_orig.tif')
        hr_img.save(results / f'{k}_truth.tif')
        pred_img.save(results / f'{k}_pred.tif')
        hr_img_data = np.array(hr_img)

        ssims.append(
            compare_ssim(img_as_float32(np.array(hr_img)),
                         img_as_float32(np.array(pred_img))))
        psnrs.append(
            compare_psnr(img_as_float32(np.array(hr_img)),
                         img_as_float32(np.array(pred_img))))
    print(np.array(ssims).mean(), np.array(psnrs).mean())

    #target_path = Path('/DATA/Dropbox/bpho_movie_results/emsynth_003/')
    target_path = results

    orig, tru, pred = [
        list(target_path.glob(f'*{tag}*')) for tag in ['orig', 'tru', 'pred']
    ]
    orig.sort()
    tru.sort()
    pred.sort()

    ssims = []
    c_ssims = []
    l_ssims = []
    psnrs = []
    c_psnrs = []
    l_psnrs = []

    for o, t, p in progress_bar(list(zip(orig, tru, pred))):
        oimg, timg, pimg = [img_as_float32(io.imread(fn)) for fn in [o, t, p]]
        if len(pimg.shape) == 3: pimg = pimg[:, :, 0]
        cimg = npzoom(oimg, 4)
        limg = npzoom(oimg, 4, order=1)

        ssims.append(compare_ssim(timg, pimg))
        c_ssims.append(compare_ssim(timg, cimg))
        l_ssims.append(compare_ssim(timg, limg))
        psnrs.append(compare_psnr(timg, pimg))
        c_psnrs.append(compare_psnr(timg, cimg))
        l_psnrs.append(compare_psnr(timg, limg))

    import pandas as pd

    df = pd.DataFrame(
        dict(ssim=ssims,
             psnr=psnrs,
             bicubic_ssim=c_ssims,
             bicubic_psnr=c_psnrs,
             bilinear_ssim=l_ssims,
             bilinear_psnr=l_psnrs))

    df.describe()
    print(df.describe())
Beispiel #28
0
def copy_image(path):
    # Path(os.path.join(target_dir, os.path.split(path)[0])).mkdir(parents=True, exist_ok=True)
    img = io.imread(os.path.join(datapath, path))
    return tf.image.encode_png(util.img_as_ubyte(
        transform.rescale(util.img_as_float32(img), 0.1, multichannel=True)),
                               compression=9).numpy()
Beispiel #29
0
from skimage.morphology import binary_erosion
from skimage.morphology import binary_dilation
from skimage.morphology import label
from skimage.morphology import remove_small_objects
import cv2

filename = "/Users/jrug001/Desktop/nesi00119/Yule/intravital/Mistgcamp-3_0002.oir"

figX, ax = plt.subplots(1, 1)  # an extra single figure

fig = plt.figure(figsize=(16, 8))
gs = gridspec.GridSpec(nrows=2, ncols=4, height_ratios=[1, 1])

# get the image stack
#os.system("/Users/jrug001/Desktop/nesi00119/bftools/bfconvert " + filename + " temp.tiff")
A0 = img_as_float32(io.imread('temp.tiff'))
A0 = exposure.rescale_intensity(A0)
#os.system("rm temp.tiff")

# average out y-direction aliasing over every other line
for n in range(A0.shape[0] - 1):  # average over every two lines
    A0[n] = (A0[n] + A0[n + 1]) / 2.0

###########################################
# unstimulated average over time
A = np.concatenate((A0[:100, :, :], A0[249:, :, :]))  # unstimulated only
M = np.zeros(A[0].shape)
for n in range(A.shape[0]):  # average over time
    M += A[n]
M /= A.shape[0]
Beispiel #30
0
NUM_SAMPLES_LIME = int(args['samples'])
N_KEEP = int(args['keep'])
CHECKPOINT_DIR = str(args['checkpoint_dir'])
OUTPUT_DIR = os.path.abspath(str(args['output_dir'])) + "/"
THRESHOLD_TRUE_CLASS = float(args['theta'])
NOISE = int(args['noise'])

# completely remove the output directory and create a new one
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
os.makedirs(OUTPUT_DIR)

# load in and resize original image to match network default size

image_filepath = os.path.abspath(args["image"])
image = img_as_float32(io.imread(image_filepath))
image = resize(image, (own_rel.IMAGE_SIZE, own_rel.IMAGE_SIZE),
               anti_aliasing=True)

# import model
model = own_rel.own_rel()

# load weights from checkpoint
model.load_weights(CHECKPOINT_DIR)

# get the annotated image
annotated_image = la.annotate_image_parts(image, model, OUTPUT_DIR,
                                          NUM_SAMPLES_LIME)

# get the list of the important superpixels
important_superpixels, labeled_image = la.find_important_parts(