Ejemplo n.º 1
0
def show_intermediate(loader, model, layer_name='conv64'):
    layer_output = model.get_layer(layer_name).output

    model = Model(model.input, outputs=layer_output)

    step = 0

    # Training loop
    results_tr = []
    for batch in loader_tr:
        inputs, target = batch
        x, a = inputs
        gc1_out = model.predict(inputs, training=False)

        #i_model = Model(inputs=[X_in, A_in], outputs=[graph_conv_1, graph_conv_2])

        fig, m_axs = plt.subplots(4, 3, figsize=(20, 15))
        for i, (ax1, ax2, ax3) in enumerate(m_axs):
            ax1.imshow(x[i].reshape((28, 28)))
            gc_stack = gc1_out[i].reshape(
                (28, 28, -1)).swapaxes(0, 2).swapaxes(1, 2)
            ax2.imshow(montage(gc_stack), vmin=-0.5, vmax=0.5, cmap='RdBu')
            ax2.set_title(i_model.output_names[0])
            gc_stack = gc2_out[i].reshape(
                (28, 28, -1)).swapaxes(0, 2).swapaxes(1, 2)
            ax3.imshow(montage(gc_stack), vmin=-0.5, vmax=0.5, cmap='RdBu')
            ax3.set_title(model.output_names[1])
def plot_and_retrieve(im, pred, label):
    """Create a figure with contour, then save it as an numpy array"""
    fig = Figure(figsize=(8, 8), dpi=100)
    # A canvas must be manually attached to the figure (pyplot would automatically
    # do it).  This is done by instantiating the canvas with the figure as
    # argument.
    canvas = FigureCanvasAgg(fig)
    ax = fig.gca()
    # Threshold the input image
    thr = im[label == 1].max()
    im[im > thr] = thr
    # Plot
    ax.imshow(montage(im), cmap='gray')
    ax.contour(montage(pred), colors='r', linewidths=.3)
    ax.contour(montage(label), colors='y', linewidths=.3)
    # Setting
    ax.axis('off')
    fig.tight_layout(pad=0)
    # To remove the huge white borders
    ax.margins(0)
    canvas.draw()
    s, (width, height) = canvas.print_to_buffer()

    # Option 2a: Convert to a NumPy array.
    X = np.fromstring(s, np.uint8).reshape((height, width, 4))[:, :, :-1]
    return (X / 255).transpose(2, 0, 1)
Ejemplo n.º 3
0
def show_Gaussian_fit(imstack, i=0, j=1):
    """
    Shows the gaussians fit to the cross correlation on the given pair of images, per
    the parameters specified in setGaussianFitParams. 

    Inputs:
        i,j      ints     Image indices.  Gaussians fit to cross correlation of images
                           i and j.

    """
    datas, fits, popts, cc, maxima = imstack.getGaussianFitResult(i, j)
    posns = maxima[:, ::-1] + popts[:, 1:3][::1] - imstack.window_radius
    midx = np.argmax(2 * np.pi * popts[:, 0] * popts[:, 3] * popts[:, 4] +
                     popts[:, 6] * np.pi * popts[:, 3] * popts[:, 4])

    fig, ax = plt.subplots(1, 3)
    ax[0].matshow(montage(datas))
    ax[0].axis('off')
    ax[0].set_title('Data')
    ax[1].matshow(montage(fits))
    ax[1].axis('off')
    ax[1].set_title('Fits')
    ax[2].matshow(np.fft.fftshift(cc))
    ax[2].plot(posns[:, 0], posns[:, 1], 'r.')
    ax[2].axis('off')
    ax[2].plot(posns[midx, 0], posns[midx, 1], 'yx')
Ejemplo n.º 4
0
def montage_ndimage(ndimg):
    if np.ndim(ndimg) == 3:
        m = montage(ndimg, fill=0)
    elif np.ndim(ndimg) == 4:  # + rgb dimension
        m = np.stack(
            (montage(np.squeeze(ndimg[..., 0]),
                     fill=0), montage(np.squeeze(ndimg[..., 1]), fill=0),
             montage(np.squeeze(ndimg[..., 2]), fill=0)),
            axis=2)
    return m
Ejemplo n.º 5
0
def realImage(request):
    print(request)
    print(request.POST.dict())
    fileobj = request.FILES['filePath']
    fs = FileSystemStorage()
    filePathName = fs.save(fileobj.name, fileobj)
    filePathName = fs.url(filePathName)
    testimage = '.' + filePathName
    i = image.load_img(testimage)
    i = skimage.img_as_float(i)
    i = image.img_to_array(i)
    i = np.expand_dims(i, axis=0)
    p = model.predict(i)
    montage_rgb = lambda x: np.stack(
        [montage(x[:, :, :, i]) for i in range(x.shape[3])], -1)
    # plt.imshow(filePathName)
    plt.imshow(montage(p[:, :, :, 0]), cmap='Reds', alpha=1)
    plt.axis('off')
    plt.savefig('media/pred/' + fileobj.name + '.jpg',
                bbox_inches='tight',
                pad_inches=0)
    context = {
        'filePathName': filePathName,
        'rr': 'media/pred/' + fileobj.name + '.jpg'
    }
    return render(request, 'index.html', context)


# def predictImage(request):
#     print(request)
#     print(request.POST.dict())
#     fileobj=request.FILES['filePath']
#     fs=FileSystemStorage()
#     filePathName=fs.save(fileobj.name,fileobj)
#     filePathName=fs.url(filePathName)
#     testimage='.'+filePathName
#     img_width, img_height = 300, 300
#     fig, (ax1,ax2,ax3) = plt.subplots(1, 3, figsize = (24, 8))
#     i = image.load_img(testimage, target_size = (img_width, img_height))
#     ax1.imshow(i,alpha=1)
#     ax1.set_title('Actual Image')
#     ax2.imshow(i,alpha=1)
#     i = skimage.img_as_float(i)
#     i = image.img_to_array(i)
#     i = np.expand_dims(i, axis = 0)
#     p = model.predict(i)
#     print(p)
#     print('p', p.shape, p.dtype, p.min(), p.max())
#     montage_rgb = lambda x: np.stack([montage(x[:, :, :, i]) for i in range(x.shape[3])], -1)
#     ax2.imshow(montage(p[:, :, :, 0]), cmap = 'Reds',alpha=0.25)
#     ax2.set_title('Predicted Image overlayed on Actual Image')
#     ax3.imshow(montage(p[:, :, :, 0]), cmap = 'Reds',alpha=1)
#     context={'filePathName':ax3}
#     # filePathNamecontext={'a':1}
#     return render(request,'index.html',context)
    def mask_preprocessing(self, mask):
        """
        Test.
        """
        mask = mask.squeeze().cpu().detach().numpy()
        mask = np.moveaxis(mask, (0, 1, 2, 3), (0, 3, 2, 1))

        mask_WT = np.rot90(montage(mask[0]))
        mask_TC = np.rot90(montage(mask[1]))
        mask_ET = np.rot90(montage(mask[2]))

        return mask_WT, mask_TC, mask_ET
Ejemplo n.º 7
0
def batch_montage_display_using_generator(image_batch, img_channels):
    # images already read into 4 dim arrays as batches
    """
      Uses generator to display a montage.  Useful to check output of a
      generator.

      Args:
        image_batch : batch of images
        img_channels : number of channels

      Returns:
        nothing
    """

    multi_ch = True
    if img_channels == 1:
        image_batch = np.reshape(image_batch,
                                 (image_batch.shape[0],
                                  image_batch.shape[1],
                                  image_batch.shape[2]))
        multi_ch = False

    img_batch_montage = montage(image_batch, multichannel=multi_ch)
    fig, (ax1) = plt.subplots(1, 1, figsize=(30, 10))
    if img_channels == 1:
        ax1.imshow(img_batch_montage, cmap="gray")
    else:
        ax1.imshow(img_batch_montage)
    ax1.set_title('Batch images: '+str(len(image_batch)))
Ejemplo n.º 8
0
def _aux_predict(predictions,
                 pad_width=16,
                 grid_shape=(10, 10),
                 num_class=2,
                 multichannel=False):
    """Calculates predictions according to padding width, grid shape and number
    of classes."""
    aux_slice = len(grid_shape) * [slice(pad_width, -pad_width)]
    if multichannel:
        # multiply pad_width with everyone, except depth and colors
        output = np.zeros(
            (predictions.shape[0],
             *np.asarray(predictions.shape[1:-1]) - 2 * pad_width,
             predictions.shape[-1]))
        for idx, pred in enumerate(predictions):
            aux_pred = _aux_label_visualize(image=pred,
                                            num_class=num_class,
                                            color_dict=const.COLOR_DICT)
            output[idx] = aux_pred[(*aux_slice, slice(None))]
    else:
        output = predictions[(slice(None), *aux_slice, 0)]

    if output.ndim == 3:
        output = util.montage(output,
                              fill=0,
                              grid_shape=grid_shape,
                              multichannel=multichannel)
    elif output.ndim == 4:
        output = montage_3d(output,
                            fill=0,
                            grid_shape=grid_shape,
                            multichannel=multichannel)
    return output
Ejemplo n.º 9
0
def test_montage_simple_rgb():
    n_images, n_rows, n_cols, n_channels = 2, 2, 2, 2
    arr_in = np.arange(n_images * n_rows * n_cols * n_channels, dtype=np.float)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols, n_channels)

    arr_out = montage(arr_in, multichannel=True)
    arr_ref = np.array(
        [[[ 0,  1],
          [ 2,  3],
          [ 8,  9],
          [10, 11]],
         [[ 4,  5],
          [ 6,  7],
          [12, 13],
          [14, 15]],
         [[ 7,  8],
          [ 7,  8],
          [ 7,  8],
          [ 7,  8]],
         [[ 7,  8],
          [ 7,  8],
          [ 7,  8],
          [ 7,  8]]]
        )
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 10
0
def make_montages():
    original_path = '/Users/adamcatto/SRC/dippy/input_data/gray_tunnel_sequence/images/'

    for i in tqdm(range(5)):
        if i != 4:
            seg_path = '/Users/adamcatto/SRC/dippy/output_data/segmentation/system_' + str(
                i + 1) + '/segmented/'
        else:
            seg_path = '/Users/adamcatto/SRC/dippy/output_data/segmentation/system_3a/segmented/'
        seg_files = list(sorted(os.listdir(seg_path)))

        for j, f in tqdm(enumerate(seg_files)):
            seg_img = lm(cv2.imread(os.path.join(seg_path, f)))
            original_img = lm(cv2.imread(os.path.join(original_path, f)))
            arr = np.array([original_img, seg_img])
            mntg = montage(arr, grid_shape=(1, 2))
            if i != 4:
                out_file = os.path.join(
                    '/Users/adamcatto/SRC/dippy/output_data/segmentation/system_'
                    + str(i + 1), 'montages', f)
            else:
                out_file = os.path.join(
                    '/Users/adamcatto/SRC/dippy/output_data/segmentation/system_3a',
                    'montages', f)
            cv2.imwrite(out_file, mntg)
def vis_h5(h5_file, num=36):
    # visualize h5 file as sanity check
    with h5py.File(h5_file, 'r') as h5_data:
        images = np.array(h5_data.get('images'))
    fig, ax1 = plt.subplots(1, 1, figsize=(12, 12))
    ax1.imshow(montage(images[:num, :, :, 0]))  #, cmap='bone')
    fig.savefig(os.path.join(OUTDIR, 'images.png'), dpi=300)
Ejemplo n.º 12
0
def test_montage_simple_rgb():
    n_images, n_rows, n_cols, n_channels = 2, 2, 2, 2
    arr_in = np.arange(n_images * n_rows * n_cols * n_channels, dtype=np.float)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols, n_channels)

    arr_out = montage(arr_in, multichannel=True)
    arr_ref = np.array(
        [[[ 0,  1],
          [ 2,  3],
          [ 8,  9],
          [10, 11]],
         [[ 4,  5],
          [ 6,  7],
          [12, 13],
          [14, 15]],
         [[ 7,  8],
          [ 7,  8],
          [ 7,  8],
          [ 7,  8]],
         [[ 7,  8],
          [ 7,  8],
          [ 7,  8],
          [ 7,  8]]]
        )
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 13
0
def disp_first_batch(t, tf):
    
    train_batch = next(iter(t))
    train_tf_batch = next(iter(tf))
    
    join_batch = np.concatenate([train_batch[0].detach().cpu().numpy(), train_tf_batch[0].detach().cpu().numpy()], axis=0)
    
    plt.imshow(montage(join_batch[:, 0, :, :]))
Ejemplo n.º 14
0
def test_montage_grid_default_gray():
    n_images, n_rows, n_cols = 15, 11, 7
    arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    n_tiles = int(np.ceil(np.sqrt(n_images)))
    arr_out = montage(arr_in)
    assert_equal(arr_out.shape, (n_tiles * n_rows, n_tiles * n_cols))
Ejemplo n.º 15
0
def test_montage_grid_default_gray():
    n_images, n_rows, n_cols = 15, 11, 7
    arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    n_tiles = int(np.ceil(np.sqrt(n_images)))
    arr_out = montage(arr_in)
    assert_equal(arr_out.shape, (n_tiles * n_rows, n_tiles * n_cols))
Ejemplo n.º 16
0
 def image_preprocessing(self, image):
     """
     Returns image flair as mask for overlaping gt and predictions.
     """
     image = image.squeeze().cpu().detach().numpy()
     image = np.moveaxis(image, (0, 1, 2, 3), (0, 3, 2, 1))
     flair_img = np.rot90(montage(image[0]))
     return flair_img
def montage_volume(_x, _l=None, save_to_file=False, _set='train', case_id=0):
    """Visualize image and contoured label (if available)"""
    plt.figure(1, (12, 12), frameon=False)
    plt.imshow(montage(_x), cmap='gray')
    if _l is not None:
        plt.contour(montage(_l), cmap='gray')
    plt.axis('off')

    if save_to_file:
        _folder = 'inputs/figures/resampled/%s' % _set
        _filename = '%s/Case%02d.png' % (_folder, case_id)
        os.makedirs(_folder) if not os.path.exists(_folder) else None

        plt.savefig(_filename,
                    bbox_inches='tight',
                    transparent=True,
                    pad_inches=0)
        plt.close()
Ejemplo n.º 18
0
def test_montage_simple_gray():
    n_images, n_rows, n_cols = 3, 2, 3
    arr_in = np.arange(n_images * n_rows * n_cols, dtype=float)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in)
    arr_ref = np.array([[0., 1., 2., 6., 7., 8.], [3., 4., 5., 9., 10., 11.],
                        [12., 13., 14., 8.5, 8.5, 8.5],
                        [15., 16., 17., 8.5, 8.5, 8.5]])
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 19
0
def test_montage_grid_custom_gray():
    n_images, n_rows, n_cols = 6, 2, 2
    arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float32)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in, grid_shape=(3, 2))
    arr_ref = np.array([[0., 1., 4., 5.], [2., 3., 6., 7.], [8., 9., 12., 13.],
                        [10., 11., 14., 15.], [16., 17., 20., 21.],
                        [18., 19., 22., 23.]])
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 20
0
def bmp_stack(image, axis=1):
    if len(image.shape) == 4:
        plt.figure()
        if axis == 1:
            imager = image[:, :, int(image.shape[2] / 2), :]
        elif axis == 2:
            imager = image[:, int(image.shape[1] / 2), :, :]
        elif axis == 3:
            imager = image[:, :, :, int(image.shape[3] / 2)]
        plt.imshow(montage(imager), cmap='gray')
        plt.colorbar()
    else:
        plt.figure()
        if axis == 1:
            plt.imshow(montage(np.transpose(image, (2, 0, 1))))  #,cmap='gray')
        elif axis == 2:
            plt.imshow(montage(image))  #,cmap='gray')
        elif axis == 3:
            plt.imshow(montage(np.transpose(image, (1, 2, 0))))  #,cmap='gray')
        plt.colorbar()
Ejemplo n.º 21
0
def make_montages(original_path, processed_path, out_dir):
    original_files = list(sorted(os.listdir(original_path)))
    processed_files = list(sorted(os.listdir(processed_path)))

    for i, f in tqdm(enumerate(processed_files)):
        original_img = lm(cv2.imread(os.path.join(original_path, f)))
        processed_img = lm(cv2.imread(os.path.join(processed_path, f)))
        arr = np.array([original_img, processed_img])
        mntg = montage(arr, grid_shape=(1, 2))
        out_file = os.path.join(out_dir, f)
        cv2.imwrite(out_file, mntg)
Ejemplo n.º 22
0
    def k_means_montage(self, df, class_col):
        """Montage for all shoes by class"""

        n_classes = df[class_col].nunique()
        for cl in sorted(df[class_col].unique()):
            montage_df = df[df[class_col] == cl].path
            imgs = [np.array(Image.open(img)) for img in montage_df]
            imgs = np.stack(imgs)
            plt.figure(figsize=(12, 15))
            plt.imshow(montage(imgs, multichannel=True).astype(np.uint8))
            plt.title(f"Montage for Class{cl}")
Ejemplo n.º 23
0
def returnMontage(np_array, title):
    """
    Returns a montage of input 3D array

    :param np_array: 3D numpy array
    :param title: modality eg T1w
    :return: Montage
    """
    fig, (ax1) = plt.subplots(1, 1, figsize=(20, 20))
    ax1.set(title=title)
    ax1.imshow(montage(np_array), cmap='gray')
Ejemplo n.º 24
0
def test_montage_simple_padding_gray():
    n_images, n_rows, n_cols = 2, 2, 2
    arr_in = np.arange(n_images * n_rows * n_cols)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in, padding_width=1)
    arr_ref = np.array([[3, 3, 3, 3, 3, 3, 3], [3, 0, 1, 3, 4, 5, 3],
                        [3, 2, 3, 3, 6, 7, 3], [3, 3, 3, 3, 3, 3, 3],
                        [3, 3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3, 3],
                        [3, 3, 3, 3, 3, 3, 3]])
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 25
0
def make_patch_collage(collage, patches=2):
    patch_collage = []
    p = 25
    for x, y in coo:
        for i in range(-patches, 0, 1):
            patch_collage.append(collage[i][y - p:y + p + 1,
                                            x - p:x + p + 1, :])
    return montage(patch_collage,
                   grid_shape=(len(coo), len(patch_collage) // len(coo)),
                   padding_width=2,
                   fill=[1.0] * 3,
                   multichannel=True)
Ejemplo n.º 26
0
def show_images(images, N=1, shape=None):
    # Show N random samples from the dataset.
    ind = np.random.choice(images.shape[2], N, replace=False)
    ind.shape = (len(ind),)

    if shape is None:
        s = int(np.ceil(N**(0.5)))
        shape = (s, s)
    m = montage(images[:, :, ind].transpose(2, 0, 1), grid_shape=shape)
    plt.imshow(m, cmap='gray')
    plt.axis('off')
    plt.show()
Ejemplo n.º 27
0
def main():
    # Instantiate parser
    parser = ArgumentParser()

    parser.add_argument("--img_dir",
                        help="Where the images reside",
                        required=True)

    parser.add_argument("--batch_indices", nargs="+", required=True)

    parser.add_argument("--step_size", type=int, default=10)

    parser.add_argument("--horizon", type=int, default=2000)

    # Parse
    args = parser.parse_args()

    # Input assertions
    assert os.path.isdir(args.img_dir), "Directory does not exist!"

    collage = []
    for i, batch_index in enumerate(args.batch_indices):

        # Load images
        image_fnames = glob(os.path.join(args.img_dir, batch_index, "*.png"))
        image_fnames.sort(key=lambda fname: int(
            os.path.splitext(os.path.basename(fname))[0]))
        images = [imageio.imread(image_fname) for image_fname in image_fnames]

        # Add text overlay
        overlays = []
        for step, image in enumerate(images):
            if step % args.step_size > 0 or step > args.horizon:
                continue

            overlays.append(
                cv2.putText(image, "Step: {}".format(step), (
                    30, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (
                        0, 0, 0), 2) if i == 0 else image)

        # Add to collage
        collage.append(overlays)

    # Merge images
    collage = [
        montage(np.stack(images_at_step, axis=0), multichannel=True)
        for images_at_step in zip(*collage)
    ]

    # Write images
    imageio.mimsave(
        os.path.join(os.path.dirname(args.img_dir), "animation.gif"), collage)
Ejemplo n.º 28
0
    def sample_images(self, epoch):
        r, c = 5, 5
        noise = np.random.normal(0, 1, (r * c, self.latent_dim))
        gen_imgs = self.generator.predict(noise)

        # Rescale images 0 - 255
        gen_imgs = (0.5 * gen_imgs + 0.5) * 255

        gan_montage = montage(gen_imgs.astype(np.uint8), multichannel=True)
        plt.imshow(gan_montage)
        plt.axis("off")
        gan_montage = Image.fromarray(gan_montage)
        gan_montage.save(f"/output/montage{epoch}.png")
Ejemplo n.º 29
0
def test_montage_fill_gray():
    n_images, n_rows, n_cols = 3, 2, 3
    arr_in = np.arange(n_images*n_rows*n_cols, dtype=np.float)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in, fill=0)
    arr_ref = np.array(
        [[  0. ,   1. ,   2. ,   6. ,   7. ,   8. ],
         [  3. ,   4. ,   5. ,   9. ,  10. ,  11. ],
         [ 12. ,  13. ,  14. ,   0. ,   0. ,   0. ],
         [ 15. ,  16. ,  17. ,   0. ,   0. ,   0. ]]
    )
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 30
0
def test_error_ndim():
    arr_error = np.random.randn(1, 2)
    with testing.raises(ValueError):
        montage(arr_error)

    arr_error = np.random.randn(1, 2, 3, 4)
    with testing.raises(ValueError):
        montage(arr_error)

    arr_error = np.random.randn(1, 2, 3)
    with testing.raises(ValueError):
        montage(arr_error, multichannel=True)

    arr_error = np.random.randn(1, 2, 3, 4, 5)
    with testing.raises(ValueError):
        montage(arr_error, multichannel=True)
Ejemplo n.º 31
0
def test_montage_simple_rgb_channel_axes(channel_axis):
    n_images, n_rows, n_cols, n_channels = 2, 2, 2, 2
    arr_in = np.arange(n_images * n_rows * n_cols * n_channels, dtype=float)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols, n_channels)

    # place channels at the desired location
    arr_in = np.moveaxis(arr_in, -1, channel_axis)

    arr_out = montage(arr_in, channel_axis=channel_axis)
    arr_ref = np.array([[[0, 1], [2, 3], [8, 9], [10, 11]],
                        [[4, 5], [6, 7], [12, 13], [14, 15]],
                        [[7, 8], [7, 8], [7, 8], [7, 8]],
                        [[7, 8], [7, 8], [7, 8], [7, 8]]])
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 32
0
def test_error_ndim():
    arr_error = np.random.randn(1, 2)
    with pytest.raises(ValueError):
        montage(arr_error)

    arr_error = np.random.randn(1, 2, 3, 4)
    with pytest.raises(ValueError):
        montage(arr_error)

    arr_error = np.random.randn(1, 2, 3)
    with pytest.raises(ValueError):
        montage(arr_error, multichannel=True)

    arr_error = np.random.randn(1, 2, 3, 4, 5)
    with pytest.raises(ValueError):
        montage(arr_error, multichannel=True)
def plot_as_montage(images, masks):
    """
    plots multiple images as montage
    :param images: images
    :param masks: their masks as arrays
    """
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(30, 10))
    batch_rgb = montage_rgb(images)
    batch_seg = montage(masks[:, :, :, 0])
    ax1.imshow(batch_rgb)
    ax1.set_title('Images')
    ax2.imshow(batch_seg)
    ax2.set_title('Segmentations')
    ax3.imshow(mark_boundaries(batch_rgb, batch_seg.astype(int)))
    ax3.set_title('Outlined Ships')
Ejemplo n.º 34
0
def test_montage_rescale_intensity_gray():
    n_images, n_rows, n_cols = 4, 3, 3
    arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float32)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in, rescale_intensity=True)
    arr_ref = np.array([[0., 0.125, 0.25, 0., 0.125, 0.25],
                        [0.375, 0.5, 0.625, 0.375, 0.5, 0.625],
                        [0.75, 0.875, 1., 0.75, 0.875, 1.],
                        [0., 0.125, 0.25, 0., 0.125, 0.25],
                        [0.375, 0.5, 0.625, 0.375, 0.5, 0.625],
                        [0.75, 0.875, 1., 0.75, 0.875, 1.]])
    assert_equal(arr_out.min(), 0.0)
    assert_equal(arr_out.max(), 1.0)
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 35
0
def test_montage_grid_custom_gray():
    n_images, n_rows, n_cols = 6, 2, 2
    arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float32)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in, grid_shape=(3, 2))
    arr_ref = np.array(
	[[  0.,   1.,   4.,   5.],
         [  2.,   3.,   6.,   7.],
         [  8.,   9.,  12.,  13.],
         [ 10.,  11.,  14.,  15.],
         [ 16.,  17.,  20.,  21.],
         [ 18.,  19.,  22.,  23.]]
    )
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 36
0
def test_montage_simple_padding_gray():
    n_images, n_rows, n_cols = 2, 2, 2
    arr_in = np.arange(n_images * n_rows * n_cols)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in, padding_width=1)
    arr_ref = np.array(
        [[3, 3, 3, 3, 3, 3, 3],
         [3, 0, 1, 3, 4, 5, 3],
         [3, 2, 3, 3, 6, 7, 3],
         [3, 3, 3, 3, 3, 3, 3],
         [3, 3, 3, 3, 3, 3, 3],
         [3, 3, 3, 3, 3, 3, 3],
         [3, 3, 3, 3, 3, 3, 3]]
    )
    assert_array_equal(arr_out, arr_ref)
Ejemplo n.º 37
0
def test_montage_rescale_intensity_gray():
    n_images, n_rows, n_cols = 4, 3, 3
    arr_in = np.arange(n_images * n_rows * n_cols, dtype=np.float32)
    arr_in = arr_in.reshape(n_images, n_rows, n_cols)

    arr_out = montage(arr_in, rescale_intensity=True)
    arr_ref = np.array(
        [[ 0.   ,  0.125,  0.25 ,  0.   ,  0.125,  0.25 ],
         [ 0.375,  0.5  ,  0.625,  0.375,  0.5  ,  0.625],
         [ 0.75 ,  0.875,  1.   ,  0.75 ,  0.875,  1.   ],
         [ 0.   ,  0.125,  0.25 ,  0.   ,  0.125,  0.25 ],
         [ 0.375,  0.5  ,  0.625,  0.375,  0.5  ,  0.625],
         [ 0.75 ,  0.875,  1.   ,  0.75 ,  0.875,  1.   ]]
    )
    assert_equal(arr_out.min(), 0.0)
    assert_equal(arr_out.max(), 1.0)
    assert_array_equal(arr_out, arr_ref)
from skimage.util.shape import view_as_windows
from skimage.util import montage

np.random.seed(42)

patch_shape = 8, 8
n_filters = 49

astro = color.rgb2gray(data.astronaut())

# -- filterbank1 on original image
patches1 = view_as_windows(astro, patch_shape)
patches1 = patches1.reshape(-1, patch_shape[0] * patch_shape[1])[::8]
fb1, _ = kmeans2(patches1, n_filters, minit='points')
fb1 = fb1.reshape((-1,) + patch_shape)
fb1_montage = montage(fb1, rescale_intensity=True)

# -- filterbank2 LGN-like image
astro_dog = ndi.gaussian_filter(astro, .5) - ndi.gaussian_filter(astro, 1)
patches2 = view_as_windows(astro_dog, patch_shape)
patches2 = patches2.reshape(-1, patch_shape[0] * patch_shape[1])[::8]
fb2, _ = kmeans2(patches2, n_filters, minit='points')
fb2 = fb2.reshape((-1,) + patch_shape)
fb2_montage = montage(fb2, rescale_intensity=True)

# -- plotting
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
ax = axes.ravel()

ax[0].imshow(astro, cmap=plt.cm.gray)
ax[0].set_title("Image (original)")