Exemple #1
0
    def vis_on_loader(self, loader, savedir_images, epoch=None):
        self.model.eval()
        count = 0
        for batch in tqdm.tqdm(loader):
            if batch['label'][0][1:].sum() == 0:
                continue
            cam_dict = self.make_multiscale_cam(batch)
            keys = cam_dict['keys']
            high_res = cam_dict['high_res']
            im_rgb = batch['original'][0]
            pred_cam = hu.f2l(hi.gray2cmap(cam_dict['cam_crf']))
            hu.save_image(
                os.path.join(
                    savedir_images,
                    batch['meta'][0]['name'] + '_cam_epoch:%d.jpg' % (epoch)),
                0.5 * (np.array(im_rgb / 255.)) + 0.5 * pred_cam)

            for i, k in enumerate(keys):
                pred = hu.f2l(hi.gray2cmap(high_res[i]))
                # im_rgb = hu.denormalize(im, 'rgb')
                # im_rgb = hu.f2l(im_rgb)
                hu.save_image(
                    os.path.join(
                        savedir_images, batch['meta'][0]['name'] +
                        '_class:%d_epoch:%d.jpg' % (k, epoch)),
                    0.5 * (np.array(im_rgb / 255.)) + 0.5 * pred)

            if count > 3:
                break
            count += 1
Exemple #2
0
    def vis_on_batch(self, batch, savedir_image):
        self.eval()
        images = batch["images"].to('cpu')  #helen changed this from .cuda()
        #print(images)
        #print(images.shape)
        points = batch["points"].long().to(
            'cpu')  #helen changed this from .cuda()
        logits = self.model.forward(images)
        probs = logits.sigmoid().cpu().numpy()

        blobs = lcfcn_loss.get_blobs(probs=probs)

        pred_counts = (np.unique(blobs) != 0).sum()
        pred_blobs = blobs
        pred_probs = probs.squeeze()

        # loc
        pred_count = pred_counts.ravel()[0]
        pred_blobs = pred_blobs.squeeze()

        img_org = hu.get_image(batch["images"], denorm="rgb")

        # true points
        y_list, x_list = np.where(batch["points"][0].long().numpy().squeeze())
        img_peaks = hi.points_on_image(y_list, x_list, img_org, radius=11)
        text = "%s ground truth" % (batch["points"].sum().item())
        hi.text_on_image(text=text, image=img_peaks)

        # pred points
        pred_points = lcfcn_loss.blobs2points(pred_blobs).squeeze()
        y_list, x_list = np.where(pred_points.squeeze())
        img_pred = hi.mask_on_image(img_org, pred_blobs)
        #img_pred = hi.points_on_image(y_list, x_list, img_org)
        text = "%s predicted" % (len(y_list))
        hi.text_on_image(text=text, image=img_pred)

        # ***************            helen added this code
        plt.imshow(
            img_pred
        )  #these lines of code display the image with the model's predications on it
        plt.show()
        # ***************            end of helen's code

        # heatmap
        heatmap = hi.gray2cmap(pred_probs)
        heatmap = hu.f2l(heatmap)
        hi.text_on_image(text="lcfcn heatmap", image=heatmap)

        img_mask = np.hstack([img_peaks, img_pred, heatmap])

        hu.save_image(savedir_image, img_mask)
Exemple #3
0
def get_blob_list(mask_dict, points_mask, img_pil, split_inst=False):
    blob_list = []
    mask = preds = mask_dict['preds']
    probs = mask_dict['probs']
    assert probs.shape[1] == preds.shape[0]
    assert probs.shape[2] == preds.shape[1]
    
    imask = np.zeros(mask.shape)
    cmask = np.zeros(mask.shape)
    
    blob_id = 1
    for c in np.unique(mask):
        if c == 0:
            continue
        probs_class = probs[c]
        point_ind = points_mask == c
        inst_mask = morphology.label(mask==c)
        for l in np.unique(inst_mask):
            if l == 0:
                continue
            blob_ind = inst_mask == l
            locs = np.where(blob_ind * point_ind)
            y_list, x_list = locs
            n_points = len(y_list)
            if n_points == 0:
                continue
            if n_points > 1 and split_inst: 
                # split multiple points
                img_points = hi.points_on_image(y_list, x_list, img_pil)
                img_masks = hi.mask_on_image(img_pil, mask)
                img_masks = hi.mask_on_image(img_points.copy(), blob_ind)
                hu.save_image('tmp.jpg', (img_points)*0.5 + hu.f2l(hi.gray2cmap(probs_class))*0.5)
                hu.save_image('tmp.jpg', img_masks)
                
                for yi, xi in zip(y_list, x_list):
                    imask, cmask, blob_list, blob_id = add_mask(yi, xi, points_mask, 
                                                            blob_ind, 
                                                            n_points, blob_list, imask, cmask,
                                                            blob_id)
            else:
                # add for that single point
                yi, xi = y_list[0], x_list[0]
                imask, cmask, blob_list, blob_id = add_mask(yi, xi, points_mask, 
                                                            blob_ind, 
                                                            n_points, blob_list, imask, cmask,
                                                            blob_id)
                

    return blob_list, cmask.astype('uint8'), imask.astype('uint8')
Exemple #4
0
    def vis_on_batch_helen(self, batch, savedir_image):
        self.eval()
        images = batch.to('cpu')
        #print(images)          #print statement to check what images is for debugging
        #print(images.shape)    #print statement to check images has the correct shape
        logits = self.model.forward(images)
        probs = logits.sigmoid().cpu().numpy()

        blobs = lcfcn_loss.get_blobs(probs=probs)

        pred_counts = (np.unique(blobs) != 0).sum()
        pred_blobs = blobs
        pred_probs = probs.squeeze()

        # loc
        pred_count = pred_counts.ravel()[0]
        pred_blobs = pred_blobs.squeeze()

        img_org = hu.get_image(images, denorm="rgb")
        #this is what was originally written: img_org = hu.get_image(batch["images"],denorm="rgb")

        #the following lines are commented out because my own data does not have labels and will thus throw errors
        # true points
        #y_list, x_list = np.where(batch["points"][0].long().numpy().squeeze())
        #img_peaks = hi.points_on_image(y_list, x_list, img_org, radius=11)
        #text = "%s ground truth" % (batch["points"].sum().item())
        #hi.text_on_image(text=text, image=img_peaks)

        # pred points
        pred_points = lcfcn_loss.blobs2points(pred_blobs).squeeze()
        y_list, x_list = np.where(pred_points.squeeze())
        img_pred = hi.mask_on_image(img_org, pred_blobs)
        # img_pred = hi.points_on_image(y_list, x_list, img_org)
        text = "%s predicted" % (len(y_list))
        hi.text_on_image(text=text, image=img_pred)

        # these lines of code display the image with the model's predications on it
        plt.imshow(img_pred)
        plt.show()

        # heatmap
        heatmap = hi.gray2cmap(pred_probs)
        heatmap = hu.f2l(heatmap)
        hi.text_on_image(text="lcfcn heatmap", image=heatmap)

        img_mask = np.hstack([img_pred, heatmap])  #helen took out im_peaks
        #this is what was originally written: img_mask = np.hstack([img_peaks, img_pred, heatmap])

        hu.save_image(savedir_image, img_mask)
Exemple #5
0
def mask_on_image(mask, image):
    from skimage.color import color_dict, colorlabel
    from skimage.segmentation import mark_boundaries
    default_colors = [
        'red', 'blue', 'yellow', 'magenta', 'green', 'indigo', 'darkorange',
        'cyan', 'pink', 'yellowgreen'
    ]
    image = hi.image_as_uint8(image) / 255.
    labels = [l for l in np.unique(mask) if l < len(color_dict)]
    colors = (default_colors + list(color_dict.keys())[len(default_colors):])
    colors = np.array(colors)[labels]

    image_label_overlay = label2rgb(mask,
                                    image=hu.f2l(image).squeeze().clip(0, 1),
                                    colors=colors,
                                    bg_label=0,
                                    bg_color=None,
                                    kind='overlay')
    return mark_boundaries(image_label_overlay, mask)
    def vis_on_batch(self, batch, savedir_image):
        self.eval()
        images = batch["images"].cuda()
        points = batch["points"].long().cuda()
        logits = self.model_base.forward(images)
        probs = logits.sigmoid().cpu().numpy()

        blobs = lcfcn_loss.get_blobs(probs=probs)

        pred_counts = (np.unique(blobs)!=0).sum()
        pred_blobs = blobs
        pred_probs = probs.squeeze()

        # loc 
        pred_count = pred_counts.ravel()[0]
        pred_blobs = pred_blobs.squeeze()
        
        img_org = hu.get_image(batch["images"],denorm="rgb")

        # true points
        y_list, x_list = np.where(batch["points"][0].long().numpy().squeeze())
        img_peaks = haven_img.points_on_image(y_list, x_list, img_org)
        text = "%s ground truth" % (batch["points"].sum().item())
        haven_img.text_on_image(text=text, image=img_peaks)

        # pred points 
        pred_points = lcfcn_loss.blobs2points(pred_blobs).squeeze()
        y_list, x_list = np.where(pred_points.squeeze())
        img_pred = hi.mask_on_image(img_org, pred_blobs)
        # img_pred = haven_img.points_on_image(y_list, x_list, img_org)
        text = "%s predicted" % (len(y_list))
        haven_img.text_on_image(text=text, image=img_pred)

        # heatmap 
        heatmap = hi.gray2cmap(pred_probs)
        heatmap = hu.f2l(heatmap)
        haven_img.text_on_image(text="lcfcn heatmap", image=heatmap)
        
        
        img_mask = np.hstack([img_peaks, img_pred, heatmap])
        
        hu.save_image(savedir_image, img_mask)
Exemple #7
0
    def vis_on_batch(self, batch, savedir_image, save_preds=False):
        self.eval()
        images = batch["images"].cuda()
        counts = float(batch["counts"][0])

        logits = self.model_base(images)

        probs = logits.sigmoid()

        # get points from attention
        att_dict = self.att_model.get_attention_dict(
            images_original=torch.FloatTensor(
                hu.denormalize(batch['images'], mode='rgb')),
            counts=batch['counts'][0],
            probs=probs.squeeze(),
            return_roi=True)

        blobs = lcfcn.get_blobs(probs.squeeze().detach().cpu().numpy())
        org_img = hu.denormalize(images.squeeze(), mode='rgb')
        rgb_labels = label2rgb(
            blobs,
            hu.f2l(org_img),
            bg_label=0,
            bg_color=None,
        )
        res1 = mark_boundaries(rgb_labels, blobs)

        if att_dict['roi_mask'] is not None:
            img_mask = hu.save_image('tmp2.png',
                                     org_img,
                                     mask=att_dict['roi_mask'] == 1,
                                     return_image=True)
            res2 = hu.save_image('tmp.png',
                                 np.array(img_mask) / 255.,
                                 points=att_dict['points'],
                                 radius=1,
                                 return_image=True)

            os.makedirs(os.path.dirname(savedir_image), exist_ok=True)
            # plt.savefig(savedir_image.replace('.jpg', '.png')
            hu.save_image(savedir_image.replace('.jpg', '.png'),
                          np.hstack([res1, np.array(res2) / 255.]))
Exemple #8
0
def bbox_on_image_utils(bbox_xyxy, image, text_list=None):
    image = hu.f2l(image.squeeze())
    image_uint8 = (image*254).astype("uint8").copy()
    H, W, _ = image.shape
    for i, bb in enumerate(bbox_xyxy):
        x1, y1, x2, y2 = bb
        x1, y1 = int(x1*W), int(y1*H) 
        x2, y2 = int(x2*W), int(y2*H)
        
        # Blue color in BGR 
        color = (255, 0, 0) 
        
        # Line thickness of 2 px 
        thickness = 2
        
        # Using cv2.rectangle() method 
        # Draw a rectangle with blue line borders of thickness of 2 px 
        image_uint8 = cv2.rectangle(image_uint8, (x1, y1), (x2, y2), color, thickness) 
        if text_list is not None:
            image_uint8 = cv2.putText(image_uint8, str(int(text_list[i]*100)), 
                        (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX,  0.6, (0, 0, 255) , 1, cv2.LINE_AA) 
    # hu.save_image("/mnt/datasets/public/issam/prototypes/wscl/tmp.jpg", image_uint8)
    return image_uint8 / 255.
    def vis_on_batch(self, batch, savedir_image, save_preds=False):
        # os.makedirs(savedir_image, exist_ok=True)
        self.eval()

        # if self.just_one:
        #   onnx_output = torch.onnx._export(self.model_base, batch['images'].cuda(), 'onnx_model.onnx', verbose=False, opset_version=12)
        #   self.just_one = False

        # onnx_output = torch.onnx._export(self.model_base, torch_input.cuda(), 'onnx_model2.onnx', verbose=False, opset_version=11, operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK)

        # clf
        #pred_mask = self.predict_on_batch(batch).cpu()
        pred_mask = self.predict_on_batch_onnx(batch).cpu()

        # print(pred_mask.sum())
        img = hu.f2l(batch['images'])[0]
        img += abs(img.min())
        img /= img.max()
        img = img.repeat(1, 1, 3)

        mask_vis = batch["masks"].clone().float()[0][..., None]
        mask_vis[mask_vis == 255] = 0

        pred_mask_vis = pred_mask.clone().float()[0][..., None]
        vmax = 0.1

        fig, ax_list = plt.subplots(ncols=3, nrows=1)
        ax_list[0].imshow(
            img[:, :, 0],
            cmap='gray',
            #   interpolation='sinc', vmin=0, vmax=0.4
        )

        colors_all = np.array(['black', 'red', 'blue', 'green', 'purple'])
        colors = colors_all[np.unique(mask_vis).astype(int)]

        vis = label2rgb(mask_vis[:, :, 0].numpy(),
                        image=img.numpy(),
                        colors=colors,
                        bg_label=255,
                        bg_color=None,
                        alpha=0.6,
                        kind='overlay')
        vis = mark_boundaries(vis,
                              mask_vis[:, :, 0].numpy().astype('uint8'),
                              color=(1, 1, 1))

        ax_list[1].imshow(vis, cmap='gray')

        colors = colors_all[np.unique(pred_mask_vis).astype(int)]
        vis = label2rgb(pred_mask_vis[:, :, 0].numpy(),
                        image=img.numpy(),
                        colors=colors,
                        bg_label=255,
                        bg_color=None,
                        alpha=0.6,
                        kind='overlay')
        vis = mark_boundaries(vis,
                              pred_mask_vis[:, :, 0].numpy().astype('uint8'),
                              color=(1, 1, 1))

        ax_list[2].imshow(vis, cmap='gray')

        for i in range(1, self.n_classes):
            plt.plot([None], [None], label='group %d' % i, color=colors_all[i])
        # ax_list[1].axis('off')
        ax_list[0].grid()
        ax_list[1].grid()
        ax_list[2].grid()

        ax_list[0].tick_params(axis='x', labelsize=6)
        ax_list[0].tick_params(axis='y', labelsize=6)

        ax_list[1].tick_params(axis='x', labelsize=6)
        ax_list[1].tick_params(axis='y', labelsize=6)

        ax_list[2].tick_params(axis='x', labelsize=6)
        ax_list[2].tick_params(axis='y', labelsize=6)

        ax_list[0].set_title('Original image', fontsize=8)
        ax_list[1].set_title('Ground-truth', fontsize=8)
        ax_list[2].set_title('Prediction', fontsize=8)

        legend_kwargs = {
            "loc": 2,
            "bbox_to_anchor": (1.05, 1),
            'borderaxespad': 0.,
            "ncol": 1
        }
        ax_list[2].legend(fontsize=6, **legend_kwargs)
        plt.savefig(savedir_image.replace('.jpg', '.png'),
                    bbox_inches='tight',
                    dpi=300)
        plt.close()

        # save predictions
        if save_preds:
            from PIL import Image
            pred_dict = {}
            pred_numpy = pred_mask.cpu().numpy().squeeze().astype('uint8')

            uniques = np.unique(np.array(pred_numpy))
            # print(uniques)
            meta_dict = batch['meta'][0]

            for u in range(self.n_classes):
                meta_dict['gt_group%d_n_pixels' % u] = float(
                    (batch['masks'] == u).float().sum())
                meta_dict['pred_group%d_n_pixels' % u] = float(
                    (pred_mask == u).float().sum())

                if u == 0:
                    continue
                pred = Image.fromarray(pred_numpy == u)
                pred.save(savedir_image.replace('.jpg', '_group%d.png' % u))

            hu.save_json(savedir_image.replace('.jpg', '.json'), meta_dict)
Exemple #10
0
    def train_on_batch(self, batch, **extras):

        self.train()

        images = batch["images"].cuda()
        counts = float(batch["counts"][0])

        logits = self.model_base(images)
        if self.exp_dict['model'].get('loss') == 'lcfcn':
            loss = lcfcn.compute_lcfcn_loss(logits, batch["points"].cuda(),
                                            None)
            probs = F.softmax(logits, 1)
            mask = probs.argmax(
                dim=1).cpu().numpy().astype('uint8').squeeze() * 255

            # img_mask=hu.save_image('tmp2.png',
            #             hu.denormalize(images, mode='rgb'), mask=mask, return_image=True)
            # hu.save_image('tmp2.png',np.array(img_mask)/255. , radius=3,
            #                 points=batch["points"])

        elif self.exp_dict['model'].get('loss') == 'glance':
            pred_counts = logits[:, 1].mean()
            loss = F.mse_loss(pred_counts.squeeze(), counts.float().squeeze())

        elif self.exp_dict['model'].get('loss') == 'att_lcfcn':
            probs = logits.sigmoid()

            # get points from attention
            att_dict = self.att_model.get_attention_dict(
                images_original=torch.FloatTensor(
                    hu.denormalize(batch['images'], mode='rgb')),
                counts=batch['counts'][0],
                probs=probs.squeeze(),
                return_roi=True)
            if 1:
                blobs = lcfcn.get_blobs(probs.squeeze().detach().cpu().numpy())
                org_img = hu.denormalize(images.squeeze(), mode='rgb')
                rgb_labels = label2rgb(
                    blobs,
                    hu.f2l(org_img),
                    bg_label=0,
                    bg_color=None,
                )
                res1 = mark_boundaries(rgb_labels, blobs)
                img_mask = hu.save_image('tmp2.png',
                                         org_img,
                                         return_image=True)
                res2 = hu.save_image('tmp.png',
                                     np.array(img_mask) / 255.,
                                     points=att_dict['points'],
                                     radius=1,
                                     return_image=True)

                hu.save_image('tmp_blobs.png',
                              np.hstack([res1, np.array(res2) / 255.]))

            loss = lcfcn.compute_loss(
                probs=probs,
                # batch["points"].cuda(),
                points=att_dict['points'].cuda(),
                roi_mask=att_dict['roi_mask'])
            # loss += .5 * F.cross_entropy(logits,
            #             torch.from_numpy(1 -
            #                 att_dict['mask_bg']).long().cuda()[None],
            #             ignore_index=1)

        self.opt.zero_grad()
        loss.backward()
        if self.exp_dict['optimizer'] == 'sps':
            self.opt.step(loss=loss)
        else:
            self.opt.step()

        return {"train_loss": float(loss)}
Exemple #11
0
        def vis_on_batch(self, batch, savedir_image):
            image = batch['images']
            index = batch['meta'][0]['index']
            gt = np.asarray(batch['masks'], np.float32)
            gt /= (gt.max() + 1e-8)
            res = self.predict_on_batch(batch)

            image = F.interpolate(image,
                                  size=gt.shape[-2:],
                                  mode='bilinear',
                                  align_corners=False)
            original = hu.denormalize(image, mode='rgb')[0]
            img_res = hu.save_image(savedir_image,
                                    original,
                                    mask=res[0],
                                    return_image=True)

            img_gt = hu.save_image(savedir_image,
                                   original,
                                   mask=gt[0],
                                   return_image=True)
            img_gt = models.text_on_image('Groundtruth',
                                          np.array(img_gt),
                                          color=(0, 0, 0))
            img_res = models.text_on_image('Prediction',
                                           np.array(img_res),
                                           color=(0, 0, 0))

            if 'points' in batch:
                pts = batch['points'][0].numpy().copy()
                pts[pts == 1] = 2
                pts[pts == 0] = 1
                pts[pts == 255] = 0
                img_gt = np.array(
                    hu.save_image(savedir_image,
                                  img_gt / 255.,
                                  points=pts,
                                  radius=2,
                                  return_image=True))

            # score map
            if self.heuristic != 'random':
                score_map = self.compute_uncertainty(batch['images'],
                                                     replicate=True,
                                                     scale_factor=1,
                                                     method=self.heuristic)
                score_map = F.interpolate(score_map[None],
                                          size=gt.shape[-2:],
                                          mode='bilinear',
                                          align_corners=False).squeeze()
                h, w = score_map.shape
                bbox_yxyx = get_rect_bbox(h, w, n_regions=self.n_regions)

                heatmap = hu.f2l(
                    hi.gray2cmap(
                        (score_map / score_map.max()).cpu().numpy().squeeze()))

                s_list = np.zeros(len(bbox_yxyx))
                for i, (y1, x1, y2, x2) in enumerate(bbox_yxyx):
                    s_list[i] = score_map[y1:y2, x1:x2].mean()

                img_bbox = bbox_yxyx_on_image(bbox_yxyx[[s_list.argmax()]],
                                              original)
                img_score_map = img_bbox * 0.5 + heatmap * 0.5

                img_list = [
                    np.array(img_gt),
                    np.array(img_res), (img_score_map * 255).astype('uint8')
                ]
            else:
                img_list = [np.array(img_gt), np.array(img_res)]
            hu.save_image(savedir_image, np.hstack(img_list))
def save_images(exp_dict):

    dataset_name = exp_dict['dataset']['name']
    n_classes = exp_dict['dataset']['n_classes']
    model = models.get_model(model_dict=exp_dict['model'],
                             exp_dict=exp_dict,
                             train_set=None).cuda()
    state_dict = hc.load_checkpoint(exp_dict,
                                    savedir_base,
                                    fname='model_best.pth')
    model.load_state_dict(state_dict)
    model.eval()
    np.random.seed(1)

    train_set = datasets.get_dataset(dataset_dict={'name': dataset_name},
                                     datadir=None,
                                     split="test",
                                     exp_dict=exp_dict)
    n_images = 0
    for _ in range(len(train_set)):
        i = np.random.choice(len(train_set))
        b = train_set[i]

        if n_images > 5:
            break

        if b['masks'].sum() == 0:
            print(i)
            continue
        n_images += 1
        batch = ut.collate_fn([b])

        image = batch['images']
        gt = np.asarray(batch['masks'], np.float32)
        gt /= (gt.max() + 1e-8)

        image = F.interpolate(image,
                              size=gt.shape[-2:],
                              mode='bilinear',
                              align_corners=False)
        img_rgb = hu.f2l(hu.denormalize(image, mode='rgb')[0])
        img_rgb = (np.array(img_rgb) * 255.).astype('uint8')

        # save rgb
        fname_rgb = '.tmp/covid_qualitative/%s/%s/%d_rgb.png' % (exp_group,
                                                                 'gt', i)
        hu.save_image(fname_rgb, img_rgb)

        # save pts
        fname_pts = '.tmp/covid_qualitative/%s/%s/%d_pts.png' % (exp_group,
                                                                 'gt', i)
        img_gt = np.array(hu.save_image('', img_rgb, return_image=True))

        if 'points' in batch:
            pts = batch['points'][0].numpy()
            pts[pts == 1] = 2
            pts[pts == 0] = 1
            pts[pts == 255] = 0
            img_gt = np.array(
                hu.save_image('',
                              img_gt / 255.,
                              points=pts,
                              radius=2,
                              return_image=True))
        hu.save_image(fname_pts, img_gt)

        # save mask
        fname_mask = '.tmp/covid_qualitative/%s/%s/%d_mask.png' % (exp_group,
                                                                   'gt', i)

        img_mask = np.array(
            hu.save_image('', img_rgb, mask=gt[0], return_image=True))
        hu.save_image(fname_mask, img_mask)

        # pred
        fname_pred = '.tmp/covid_qualitative/%s/%s/%d_%s.png' % (
            exp_group, 'preds', i, exp_dict['model']['loss'])
        res = model.predict_on_batch(batch)

        img_res = hu.save_image('', img_rgb, mask=res[0], return_image=True)
        hu.save_image(fname_pred, np.array(img_res))