<jupyter_start><jupyter_text>Visualize predictions<jupyter_code>T_norm = T.Compose([T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406],
                std=[0.229, 0.224, 0.225])])

T_tensor = T.Compose([T.ToTensor()])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

def getPredict(a):
    pred =a['out'].data.cpu().numpy()
    return np.argmax(pred, axis=1)[0]

def get_segment_labels(image, model, device, transform):
    # transform the image to tensor and load into computation device
    image = transform(image).to(device)
    image = image.unsqueeze(0) # add a batch dimension
    outputs = model(image)
    return outputs

# Convert mask to binary map
def to3cat(mask):
    mask[mask < 127] = 0
    mask[mask >= 127] = 1
    mask[mask[:, :, 1] > 0] = 2
    mask = mask[:,:,0]
    return mask

def to2cat(mask):
    mask[mask < 127] = 0
    mask[mask >= 127] = 1
    return mask
def makeSeg(image, mask):
    segmap = np.zeros(image.shape, dtype=bool)
    segmap[:,:,0] = mask
    segmap = SegmentationMapOnImage(segmap, shape=image.shape)
    
    return segmap

def makeSeg3(image, mask):
    segmap = mask
    segmap = SegmentationMapsOnImage(segmap, shape=image.shape)
    
    return segmap
def reconstructIMG(imgs):
    
    myorder = [0, 7, 8, 9, 10, 11 ,12, 13, 14,15, 1, 2, 3, 4, 5, 6]
    order_imgs = [np.array(imgs[i], dtype='uint8') for i in myorder]
    order_imgs =imgs
    
    
    if len(order_imgs[0].shape)==3:
        new_img = np.zeros((1880,1120,3))
        for i, m in enumerate(order_imgs):
            if i <= 3:
                new_img[i*470:i*470+470,:280,:] = m
            if i > 3 and i <=7:
                new_img[(i-4)*470:(i-4)*470+470,280:560,:] = m
            if i > 7 and i <=11:
                new_img[(i-8)*470:(i-8)*470+470,560:840,:] = m
            if i > 11 and i <=15:
                new_img[(i-12)*470:(i-12)*470+470,840:,:] = m
    else:   
        new_img = np.zeros((1880,1120))    
        for i, m in enumerate(order_imgs):
            if i <= 3:
                new_img[i*470:i*470+470,:280] = m
            if i > 3 and i <=7:
                new_img[(i-4)*470:(i-4)*470+470,280:560] = m
            if i > 7 and i <=11:
                new_img[(i-8)*470:(i-8)*470+470,560:840] = m
            if i > 11 and i <=15:
                new_img[(i-12)*470:(i-12)*470+470,840:] = m
    new_img = new_img.astype('uint8')
    
    return new_img

def makeSeg(image, mask):
    segmap = np.zeros(image.shape, dtype=bool)
    if len(mask.shape)==3:
        segmap[:,:,0] = mask[:,:,0]
    else:
        segmap[:,:,0] = mask
    segmap = SegmentationMapOnImage(segmap, shape=image.shape)
    
    return segmap
filepath = r'H:\Aurélie\Data\ModelB\Test\Mixed\ImgMasked'
files = glob(filepath+'\\*.*')
filenames = [f.split('\\')[-1] for f in files]

img_path = r'C:\Users\A60026184\Desktop\ModelB\Test\Mixed\ImgMasked'
msk_path = r'C:\Users\A60026184\Desktop\ModelB\Test\Mixed\Join'

gt_path= r'H:\Aurélie\Predictions\ModelB\Images\gt\Mixed'
pred_path = r'H:\Aurélie\Predictions\ModelB\Images\pred\B1\Mixed'
filenames
# Load the models
ModelA = torch.load(r'C:\Users\A60026184\Desktop\ModelA\Results\weights_Aaug5_v1.pt')
ModelA.eval()

ModelB = torch.load(r'C:\Users\A60026184\Desktop\ModelB\Results\weights_cascBaug5_v1.pt')
ModelB.eval()

print('DONE Loading models...')<jupyter_output>DONE Loading models...<jupyter_text>Model A<jupyter_code>for f in filenames:
    
    images, masks = [], []
    preds_a, preds_b = [], []
    name = []
    
    print(f)
    
    img_files = glob(img_path+'\\*'+f)
    msk_files = glob(msk_path+'\\*'+f)
    
    print(img_files)

    for i, m in enumerate(img_files):
        name.append(m.split('\\')[-1].split('_')[0])
        # read the image
        image = Image.open(m)
        images.append(image)
        # Read  a sample image and mask from the data-set
        masks.append(np.array(Image.open(msk_files[i])))
        #Get prediction 
        a = get_segment_labels(image, ModelA, device, T_norm)
        preds_a.append(getPredict(a))

    # use imageio library to read the image (alternatively you can use OpenCV cv2.imread() function)
    full_image = reconstructIMG(images)
    full_mask = reconstructIMG(masks)
    full_mask = to2cat(full_mask)
    pred_a = reconstructIMG(preds_a)

    gt = makeSeg(full_image, full_mask)
    res = makeSeg(full_image, pred_a)

    img_gt = gt.draw_on_image(full_image)[0]
    img_res = res.draw_on_image(full_image)[0]

    #--------------- SHOW THE RESULTS
    #results=[]
    #results.append(res_a.draw_on_image(full_image)[0])
    #ia.imshow(ia.draw_grid(results, cols=1))

    #--------------- SAVE THE RESULTS
    imageio.imwrite(gt_path+'\\'+f, img_gt)
    imageio.imwrite(pred_path+'\\'+f, img_res)<jupyter_output>180919_Pr_A_M16_1.jpg
['C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\00_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\01_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\02_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\03_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\04_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\05_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\06_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\07_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\08_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\09_180919_Pr_A_M16_1.jpg', 'C:\\Users\\A60026184\\Desktop\\ModelB\\Test\\Mixed\\ImgMasked\\10_[...]<jupyter_text>Model B<jupyter_code>for f in filenames:
    
    images, masks = [], []
    preds_b = []
    name = []
    
    print(f)
    
    img_files = glob(img_path+'\\*'+f)
    msk_files = glob(msk_path+'\\*'+f)

    for i, m in enumerate(img_files):
        # read the image
        image = Image.open(m)
        images.append(image)
        # Read  a sample image and mask from the data-set
        masks.append(np.array(Image.open(msk_files[i])))

        #Get prediction 
        b = get_segment_labels(image, ModelB, device, T_norm)
        preds_b.append(getPredict(b))

    # use imageio library to read the image (alternatively you can use OpenCV cv2.imread() function)
    full_image = reconstructIMG(images)
    full_mask = reconstructIMG(masks)
    full_mask = to3cat(full_mask)
    pred_b = reconstructIMG(preds_b)

    gt = makeSeg3(full_image, full_mask)
    res = makeSeg3(full_image, pred_b)

    img_gt = gt.draw_on_image(full_image)[0]
    img_res = res.draw_on_image(full_image)[0]

    #--------------- SHOW THE RESULTS
    #results=[]
    #results.append(gt.draw_on_image(full_image)[0])
    #ia.imshow(ia.draw_grid(results, cols=1))

    #--------------- SAVE THE RESULTS
    imageio.imwrite(gt_path+'\\'+f, img_gt)
    imageio.imwrite(pred_path+'\\'+f, img_res)<jupyter_output>180919_Pr_A_M16_1.jpg
180919_Pr_D_M12_2.jpg
180926_Md_A_M10_1.jpg
180926_Pr_A_M11_2.jpg
181010_Pr_D_M19_3.jpg
181015_Md_A_M17_2.jpg
181016_Pr_D_M13_2.jpg
190913_Pr_A_M11_4.jpg
190913_Pr_D_M12_4.jpg
190927_Pr_D_M15_2.jpg
{'fraction_non_alphanumeric': 0.16630226837933862, 'fraction_numerical': 0.08144301721781907, 'mean_word_length': 2.964788732394366, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '380062', 'license': 'MIT', 'n_tokens_mistral': 3315, 'n_tokens_neox': 2933, 'n_words': 461, 'path': 'model/visualization/visualize.ipynb', 'repo_name': 'aureliedj/OilseedRapeSegmentation', 'size': '7318'}