Ejemplo n.º 1
0
def show_siamese_batch(loader):
    img_batch1, img_batch2, label_batch = next(iter(loader))
    print("Image batch size: {}. Label batch size: {}.".format(
        img_batch1.size(), len(label_batch)))
    print("Average pixel value in batch: {:.5f}".format(
        (img_batch1.mean() + img_batch1.mean()) / 2.))
    print("Stddev pixel value in batch: {:.5f}".format(
        (img_batch1.std() + img_batch2.std()) / 2.))
    # display batch
    n_cols = 8
    n_rows = 2 * (img_batch1.size()[0] // n_cols + 1 *
                  (img_batch1.size()[0] % n_cols > 0))
    fig, axs = plt.subplots(n_rows, n_cols, figsize=(15, n_rows * 15 / n_cols))
    for i in range(n_rows // 2):
        for j in range(n_cols):
            k = i * n_cols + j
            if k < img_batch1.size()[0]:
                img1 = img_batch1[k].permute(1, 2, 0).data.cpu().numpy()
                img2 = img_batch2[k].permute(1, 2, 0).data.cpu().numpy()
                img1, img2 = imgMinMaxScaler(img1), imgMinMaxScaler(img2)
                label = label_batch[k]
                axs[2 * i, j].imshow(rio.convert_tensor_to_rgb(img1))
                axs[2 * i + 1, j].imshow(rio.convert_tensor_to_rgb(img2))
                axs[2 * i, j].set_title(label)
                axs[2 * i + 1, j].set_title(label)

    plt.show()
Ejemplo n.º 2
0
 def __getitem__(self, index):
     item = self.items[index].copy()
     bunch = item.pop('images')
     if self.channels_mode == 'six':
         channels = []
         for i, filename in sorted(bunch, key=itemgetter(0)):
             img = self.open_fn(filename)
             img = img if self.tr is None else self.tr(img)
             channels.append(img)
         sample = torch.cat(channels, dim=0)
     else:
         filenames = [filename for _, filename in bunch]
         t = rio.load_images_as_tensor(filenames)
         arr = rio.convert_tensor_to_rgb(t)
         img = PIL.Image.fromarray(arr.astype(np.uint8))
         sample = img if self.tr is None else self.tr(img)
     # y = self.targets[index]
     y = item[self.targets_key]
     if self.drop_meta:
         item = dict(features=sample, targets=y)
     else:
         item.update(dict(features=sample, targets=y))
     if self.onehot:
         y_enc = get_one_hot(y,
                             smoothing=self.label_smoothing,
                             num_classes=self.num_classes)
         sample['targets_one_hot'] = y_enc
     return item
 def _show_imgs(self, imgs):
     from matplotlib import pyplot as plt
     import rxrx.io as rio
     import cv2
     for i, img in enumerate(imgs):
         img = np.moveaxis(img, 0, 2)
         height, width, _ = img.shape
         img = cv2.resize(img,
                          dsize=(512, 512),
                          interpolation=cv2.INTER_CUBIC)
         img_rgb = np.array(rio.convert_tensor_to_rgb(img), dtype='uint8')
         img_rgb = cv2.resize(img_rgb,
                              dsize=(height, width),
                              interpolation=cv2.INTER_CUBIC)
         ax = plt.subplot(1, len(imgs), i + 1)
         ax.title.set_text(self.mode)
         plt.imshow(img_rgb)
     plt.show()
Ejemplo n.º 4
0
def plot_rgb(data, figsize=10):
    """
    convert 6-channels to RGB (3-channel)
    and visualize the figure.

    """
    dirs = data[0].split("/")
    base_plates = [dirs.index(i) for i in dirs if i.startswith("Plate")][0]
    pre = "_".join(dirs[base_plates - 1:base_plates + 1])
    suf = "_".join(os.path.basename(data[0]).split("_")[:2])

    imgname = "_".join((pre, suf))

    plt.figure(figsize=(figsize, figsize))

    img_6channel = rio.load_images_as_tensor(data)
    img_as_rgb = rio.convert_tensor_to_rgb(img_6channel)
    plt.title(imgname)
    plt.imshow(img_as_rgb)
Ejemplo n.º 5
0
def plot_cell_sirna_rgb(filtered_data, figsize=20):
    """
    plot all data in a row (Actually mutliple rows)

    :param filtered_data: dataframe, after processed with 'filter_data_with_cell_sirna'
    :param figsize: column size
    :return:
    """
    data_num = len(filtered_data)
    row_num = math.ceil((data_num // 4))

    plt.figure(figsize=(figsize, figsize * row_num * 0.25))

    for i in range(data_num):
        plt.subplot(row_num, 4, i + 1)
        img_paths = filtered_data.iloc[i, -6:].tolist()

        img_6channel = rio.load_images_as_tensor(img_paths)
        img_as_rgb = rio.convert_tensor_to_rgb(img_6channel)
        plt.title(filtered_data.iat[i, 0])
        plt.imshow(img_as_rgb)
                  base_path=LOCAL_IMAGES_BASE_PATH)

t.shape

# In[5]:

fig, axes = plt.subplots(2, 3, figsize=(24, 16))

for i, ax in enumerate(axes.flatten()):
    ax.axis('off')
    ax.set_title('channel {}'.format(i + 1))
    _ = ax.imshow(t[:, :, i], cmap='gray')

# In[6]:

x = rio.convert_tensor_to_rgb(t)

x.shape

# In[7]:

plt.figure(figsize=(8, 8))
plt.axis('off')

_ = plt.imshow(x)

# In[8]:

y = rio.load_site_as_rgb('train',
                         'HUVEC-08',
                         4,
Ejemplo n.º 7
0
def upload():
    print('--> /upload')
    if 'POST' == request.method:
        HEPG2 = request.form.get('radio-choice-h-2a')
        HVUEC = request.form.get('radio-choice-h-2b')
        RPE = request.form.get('radio-choice-h-2c')
        U2OS = request.form.get('radio-choice-h-2d')

        cell_type = ''
        if HEPG2:
            cell_type = 'HEPG2'
        elif HVUEC:
            cell_type = 'HVUEC'
        elif RPE:
            cell_type = 'RPE'
        else:
            cell_type = 'U2OS'

        experiment_on = request.form.get('experiment-no')
        plate_no = request.form.get('plate-no')

        positive_control = request.form.get('well-radio-choice-h-2')
        negative_control = request.form.get('well-radio-choice-h-2b')
        treatment = request.form.get('well-radio-choice-h-2c')
        well_type = ''
        if positive_control:
            well_type = 'positive_control'
        elif negative_control:
            well_type = 'negative_control'
        else:
            well_type = 'treatment'

        print(HEPG2, HVUEC, RPE, U2OS)
        print(experiment_on)

        files = []
        rgb_file_name = ''
        for file in request.files.getlist('files'):
            if file and allowed_file(file.filename):
                filename = cell_type + '-' + experiment_on \
                           + '-Plate' + plate_no \
                           + '-' + secure_filename(file.filename)
                print('-->', file.filename, '==>', filename)

                t = filename.split('_')
                rgb_file_name = t[0] + '_rgb.png'

                files.append(filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        # load
        channel_paths = [
            os.path.join(app.config['UPLOAD_FOLDER'], f) for f in files
        ]
        tensor = rio.load_images_as_tensor(channel_paths)
        #
        rgb = rio.convert_tensor_to_rgb(tensor)
        rgb = np.array(rgb, dtype=np.uint8)
        matplotlib.image.imsave(
            os.path.join(app.config['UPLOAD_FOLDER'], rgb_file_name), rgb)
        # predict:
        tensor = np.expand_dims(tensor, axis=0)
        predictions = pred({'feature': tensor})

        print(predictions)

        id = str(uuid.uuid1())
        submit_time = isoformat(datetime.datetime.now())

        # save file to database
        record_file = File(id, session['email'], cell_type, experiment_on,
                           plate_no, well_type, ','.join(files), rgb_file_name,
                           submit_time, '%d' % predictions['classes'][0])
        db.session.add(record_file)
        db.session.commit()

    return redirect('file_list.html')