Exemplo n.º 1
0
def main():
    opt = TestOptions()
    args = opt.initialize()

    if not os.path.exists(args.save):
        os.makedirs(args.save)

    model = CreateSSLModel(args)
    model.eval()
    model.cuda()
    targetloader = CreateTrgDataSSLLoader(args)

    predicted_label = np.zeros((len(targetloader), 1634, 1634))
    predicted_prob = np.zeros((len(targetloader), 1634, 1634))
    image_name = []
    for index, batch in enumerate(targetloader):
        if index % 100 == 0:
            print('%d processd' % index)
        image, _, name = batch
        image = Variable(image).cuda()
        _, output, _, _ = model(image, ssl=True)
        output = nn.functional.softmax(output, dim=1)
        output = nn.functional.upsample(
            output, (1634, 1634), mode='bilinear',
            align_corners=True).cpu().data[0].numpy()
        output = output.transpose(1, 2, 0)
        #import pdb;pdb.set_trace()
        label, prob = np.argmax(output, axis=2), np.max(output, axis=2)
        predicted_label[index] = label.copy()
        predicted_prob[index] = prob.copy()
        image_name.append(name[0])

    thres = []
    for i in range(3):
        x = predicted_prob[predicted_label == i]
        if len(x) == 0:
            thres.append(0)
            continue
        x = np.sort(x)
        thres.append(x[np.int(np.round(len(x) * 0.5))])
    thres = np.array(thres)
    thres[thres > 0.9] = 0.9

    color_labels = {0: 0, 128: 1, 255: 2}
    for index in range(len(targetloader)):
        name = image_name[index]
        label = predicted_label[index]
        prob = predicted_prob[index]
        for color, i in color_labels.items():
            label[(prob > thres[i]) * (label == i)] = color
        output = np.asarray(label, dtype=np.uint8)
        output = Image.fromarray(output)
        name = name.split('.')[0] + '.png'
        # arr = name.split('/')[-1].split('.')[0] + '.npy'
        # np.save('%s/%s' % (args.save, arr), prob)
        output.save('%s/%s' % (args.save, name))
Exemplo n.º 2
0
def main():
    opt = TestOptions()
    args = opt.initialize()

    if not os.path.exists(args.save):
        os.makedirs(args.save)

    model = CreateSSLModel(args)

    model.eval()
    model.cuda()
    targetloader = CreateTrgDataSSLLoader(args)

    predicted_label = np.zeros((len(targetloader), 512, 1024))
    predicted_prob = np.zeros((len(targetloader), 512, 1024))
    image_name = []

    for index, batch in enumerate(targetloader):
        if index % 100 == 0:
            print '%d processd' % index
        image, _, name = batch
        output = model(Variable(image).cuda(), ssl=True)
        output = nn.functional.softmax(output, dim=1)
        output = nn.functional.upsample(
            output, (512, 1024), mode='bilinear',
            align_corners=True).cpu().data[0].numpy()
        output = output.transpose(1, 2, 0)

        label, prob = np.argmax(output, axis=2), np.max(output, axis=2)
        predicted_label[index] = label.copy()
        predicted_prob[index] = prob.copy()
        image_name.append(name[0])

    thres = []
    for i in range(19):
        x = predicted_prob[predicted_label == i]
        if len(x) == 0:
            thres.append(0)
            continue
        x = np.sort(x)
        thres.append(x[np.int(np.round(len(x) * 0.5))])
    print thres
    thres = np.array(thres)
    thres[thres > 0.9] = 0.9
    print thres
    for index in range(len(targetloader)):
        name = image_name[index]
        label = predicted_label[index]
        prob = predicted_prob[index]
        for i in range(19):
            label[(prob < thres[i]) * (label == i)] = 255
        output = np.asarray(label, dtype=np.uint8)
        output = Image.fromarray(output)
        name = name.split('/')[-1]
        output.save('%s/%s' % (args.save, name))
Exemplo n.º 3
0
def main():
    opt = TestOptions()
    args = opt.initialize()
    os.environ["CUDA_VISIBLE_DEVICES"] = args.GPU

    if not os.path.exists(args.save):
        os.makedirs(args.save)

    args.restore_from = args.restore_opt1
    model1 = CreateSSLModel(args)
    model1.eval()
    model1.cuda()

    args.restore_from = args.restore_opt2
    model2 = CreateSSLModel(args)
    model2.eval()
    model2.cuda()

    args.restore_from = args.restore_opt3
    model3 = CreateSSLModel(args)
    model3.eval()
    model3.cuda()

    targetloader = CreateTrgDataSSLLoader(args)

    # change the mean for different dataset
    IMG_MEAN = np.array((104.00698793, 116.66876762, 122.67891434),
                        dtype=np.float32)
    IMG_MEAN = torch.reshape(torch.from_numpy(IMG_MEAN), (1, 3, 1, 1))
    mean_img = torch.zeros(1, 1)

    predicted_label = np.zeros((len(targetloader), 512, 1024))
    predicted_prob = np.zeros((len(targetloader), 512, 1024))
    image_name = []

    with torch.no_grad():
        for index, batch in enumerate(targetloader):
            if index % 100 == 0:
                print('%d processd' % index)
            image, _, name = batch
            if mean_img.shape[-1] < 2:
                B, C, H, W = image.shape
                mean_img = IMG_MEAN.repeat(B, 1, H, W)
            image = image.clone() - mean_img
            image = Variable(image).cuda()

            # forward
            output1 = model1(image)
            output1 = nn.functional.softmax(output1, dim=1)

            output2 = model2(image)
            output2 = nn.functional.softmax(output2, dim=1)

            output3 = model3(image)
            output3 = nn.functional.softmax(output3, dim=1)

            a, b = 0.3333, 0.3333
            output = a * output1 + b * output2 + (1.0 - a - b) * output3

            output = nn.functional.interpolate(
                output, (512, 1024), mode='bilinear',
                align_corners=True).cpu().data[0].numpy()
            output = output.transpose(1, 2, 0)

            label, prob = np.argmax(output, axis=2), np.max(output, axis=2)
            predicted_label[index] = label.copy()
            predicted_prob[index] = prob.copy()
            image_name.append(name[0])

    thres = []
    for i in range(19):
        x = predicted_prob[predicted_label == i]
        if len(x) == 0:
            thres.append(0)
            continue
        x = np.sort(x)
        thres.append(x[np.int(np.round(len(x) * 0.66))])
    print(thres)
    thres = np.array(thres)
    thres[thres > 0.9] = 0.9
    print(thres)

    for index in range(len(targetloader)):
        name = image_name[index]
        label = predicted_label[index]
        prob = predicted_prob[index]
        for i in range(19):
            label[(prob < thres[i]) * (label == i)] = 255
        output = np.asarray(label, dtype=np.uint8)
        output = Image.fromarray(output)
        name = name.split('/')[-1]
        output.save('%s/%s' % (args.save, name))
Exemplo n.º 4
0
def main():
    opt = TestOptions()
    args = opt.initialize()

    if not os.path.exists(args.save):
        os.makedirs(args.save)

    model = CreateSSLModel(args)
    cudnn.enabled = True
    cudnn.benchmark = True
    model.train()
    model.cuda()
    targetloader = CreateTrgDataSSLLoader(args)

    #predicted_label = np.zeros((len(targetloader), 1634, 1634))
    predicted_label = np.zeros((len(targetloader), 2056, 2124))
    #predicted_prob = np.zeros((len(targetloader), 1634, 1634))
    predicted_prob = np.zeros((len(targetloader), 2056, 2124))
    image_name = []

    for index, batch in enumerate(targetloader):
        if index % 10 == 0:
            print('%d processd' % index)
        image, _, name = batch
        image = Variable(image).cuda()
        _, output, _, _ = model(image, ssl=True)
        output = nn.functional.softmax(output / args.alpha, dim=1)
        #output = nn.functional.upsample(output, (1634, 1634), mode='bilinear', align_corners=True).cpu().data[0].numpy()
        output = nn.functional.upsample(
            output, (2056, 2124), mode='bilinear',
            align_corners=True).cpu().data[0].numpy()
        output = output.transpose(1, 2, 0)
        label, prob = np.argmax(output, axis=2), np.max(output, axis=2)
        cup_mask = get_bool(label, 0)
        disc_mask = get_bool(label, 0) + get_bool(label, 1)
        disc_mask = disc_mask.astype(np.uint8)
        cup_mask = cup_mask.astype(np.uint8)
        for i in range(5):
            disc_mask = scipy.signal.medfilt2d(disc_mask, 19)
            cup_mask = scipy.signal.medfilt2d(cup_mask, 19)
        disc_mask = morphology.binary_erosion(disc_mask,
                                              morphology.diamond(7)).astype(
                                                  np.uint8)  # return 0,1
        cup_mask = morphology.binary_erosion(cup_mask,
                                             morphology.diamond(7)).astype(
                                                 np.uint8)  # return 0,1
        disc_mask = get_largest_fillhole(disc_mask)
        cup_mask = get_largest_fillhole(cup_mask)

        disc_mask = morphology.binary_dilation(disc_mask,
                                               morphology.diamond(7)).astype(
                                                   np.uint8)  # return 0,1
        cup_mask = morphology.binary_dilation(cup_mask,
                                              morphology.diamond(7)).astype(
                                                  np.uint8)  # return 0,1

        disc_mask = get_largest_fillhole(disc_mask).astype(
            np.uint8)  # return 0,1
        cup_mask = get_largest_fillhole(cup_mask).astype(np.uint8)
        label = disc_mask + cup_mask
        predicted_label[index] = label.copy()
        predicted_prob[index] = prob.copy()
        image_name.append(name[0])

    thres = []
    for i in range(3):
        x = predicted_prob[predicted_label == i]
        if len(x) == 0:
            thres.append(0)
            continue
        x = np.sort(x)
        #print(len(x))
        print(i, x)
        print(np.sum(x < 0.5), '/', len(x), np.sum(x < 0.5) / len(x))
        #thres.append(x[np.int(np.round(len(x) *int(args.p[i])))])
        thres.append(0.5)
    thres = np.array(thres)
    print(thres)
    # thres[thres > 0.6] = 0.6

    color_labels = {0: 255, 1: 128, 2: 0}
    #import pdb;pdb.set_trace()
    for index in range(len(targetloader)):
        name = image_name[index]
        label = predicted_label[index]  # label_min:0 label_max=2
        #print(label)
        prob = predicted_prob[index]  # prob_min:0.5 prob_max=1.0
        #print(prob)
        for i, color in color_labels.items():
            label[label == i] = color
            #print(thres[i])
            label[(prob > thres[i]) * (label == i)] = color
        output = np.asarray(label, dtype=np.uint8)
        output = Image.fromarray(output.astype(np.uint8))
        #name = name.split('.')[0] + '.png'
        name = name.split('_')[0] + '.bmp'
        output.save('%s/%s' % (args.save, name))

    disc_dice, cup_dice = calculate_dice(args.gt_dir, args.save,
                                         args.devkit_dir)
    print('===> disc_dice:' + str(round(disc_dice, 3)) + '\t' + 'cup_dice:' +
          str(round(cup_dice, 3)))
Exemplo n.º 5
0
def main():
    opt = TestOptions()
    args = opt.initialize()
    os.environ["CUDA_VISIBLE_DEVICES"] = args.GPU

    if not os.path.exists(args.save):
        os.makedirs(args.save)

    args.restore_from = args.restore_opt1
    model1 = CreateSSLModel(args)
    model1.eval()
    model1.cuda()

    args.restore_from = args.restore_opt2
    model2 = CreateSSLModel(args)
    model2.eval()
    model2.cuda()

    args.restore_from = args.restore_opt3
    model3 = CreateSSLModel(args)
    model3.eval()
    model3.cuda()

    targetloader = CreateTrgDataSSLLoader(args)

    # change the mean for different dataset
    IMG_MEAN = np.array((104.00698793, 116.66876762, 122.67891434), dtype=np.float32)
    IMG_MEAN = torch.reshape( torch.from_numpy(IMG_MEAN), (1,3,1,1)  )
    mean_img = torch.zeros(1, 1)

   
    image_name = []

    x = [None]*19     # x values for all 19 classes    
  

    cachepath = "../cache"    # Directory to save the numpy files as cache.

    with torch.no_grad():
        for index, batch in enumerate(targetloader):
            if index % 1 == 0:
                print( '%d processd' % index )
            image, _, name = batch
            if mean_img.shape[-1] < 2:
                B, C, H, W = image.shape
                mean_img = IMG_MEAN.repeat(B,1,H,W)
            image = image.clone() - mean_img
            image = Variable(image).cuda()

            # forward
            output1 = model1(image)
            output1 = nn.functional.softmax(output1, dim=1)

            output2 = model2(image)
            output2 = nn.functional.softmax(output2, dim=1)

            output3 = model3(image)
            output3 = nn.functional.softmax(output3, dim=1)

            a, b = 0.3333, 0.3333
            output = a*output1 + b*output2 + (1.0-a-b)*output3

            output = nn.functional.interpolate(output, (512, 1024), mode='bilinear', align_corners=True).cpu().data[0].numpy()
            output = output.transpose(1,2,0)
       
            label, prob = np.argmax(output, axis=2), np.max(output, axis=2)
            
           
            # Saving the prob and label files for each index seperately so that while loading the whole array need not be loaded in turn saving a lot of CPU ram.

            f1 = gzip.GzipFile(os.path.join(cachepath, "label_" + str(index))+'.npy.gz', "w")
            f2 = gzip.GzipFile(os.path.join(cachepath, "prob_" + str(index))+'.npy.gz', "w")
            np.save(f1,label)
            np.save(f2, prob)
            f1.close()
            f2.close()


            for i in range(19):
                d = prob[label==i]
                if(len(d)==0):
                  continue
                 
                if x[i] is None:
                    x[i]=d
                else:   
                    x[i]= np.concatenate((x[i],d))
                  

            image_name.append(name[0])
          

    thres = []

    

    thres = []
    for i in range(19):
        if x[i] is None:
            thres.append(0)