コード例 #1
0
def main(args):
    if args.use_cuda:
        print("Using GPU")
        torch.cuda.set_device(args.gpu_id)
    else: 
        print("Using CPU")

    check_dir(args.loss_path)
    check_dir(args.model_path)
    check_dir(args.optimizer_path)

    pre_trans_img = [Transpose(), TensorFlip(0), TensorFlip(1)]
    datasets = {"train": BuildDataSet(args.data_root_path, args.train_folder, pre_trans_img, args.data_length["train"], "train"),
            "val": BuildDataSet(args.data_root_path, args.val_folder, None, args.data_length["val"], "val")}

    data_length = {x:len(datasets[x]) for x in ["train", "val"]}
    print("Data length:Train:{} Val:{}".format(data_length["train"], data_length["val"]))
    
    kwargs = {"num_workers": args.num_workers, "pin_memory": True if args.mode is "train" else False}
    dataloaders = {x: DataLoader(datasets[x], args.batch_size[x], shuffle=args.is_shuffle, **kwargs) for x in ["train", "val"]}

    ## *********************************************************************************************************
    model = WGAN_SACNN_AE(args.batch_size[args.mode], args.root_path, "v2")
    if args.mode is "train":
        train_model(model = model,
                dataloaders = dataloaders,
                args=args
                )
        print("Run train.py Success!")
    else:
        print("\nargs.mode is wrong!\n")
        sys.exit(0)
コード例 #2
0
ファイル: test.py プロジェクト: wuzhan11/SACNN
def main(args):
    if args.use_cuda:
        print("Using GPU")
        torch.cuda.set_device(args.gpu_id)
    else:
        print("Using CPU")

    datasets = {
        "test":
        BuildDataSet(args.data_root_path, args.test_folder, None,
                     args.data_length["test"], "test")
    }

    kwargs = {
        "num_workers": args.num_workers,
        "pin_memory": True if args.mode is "train" else False
    }
    dataloaders = {
        x: DataLoader(datasets[x], args.batch_size[x], shuffle=True, **kwargs)
        for x in ["test"]
    }
    print("Load Datasets Done")

    ## *********************************************************************************************************
    model_index = args.model_index
    model = WGAN_SACNN_AE(args.batch_size[args.mode], args.root_path,
                          args.version)
    model = model_updata(model,
                         model_old_name=args.model_name +
                         "{}".format(model_index),
                         model_old_path=args.model_path)

    ## *********************************************************************************************************
    test_model(model=model, dataloaders=dataloaders, args=args)
コード例 #3
0
def main(args):
    if args.use_cuda:
        print("Using GPU")
    else:
        print("Using CPU")

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)

    datasets = BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                            geo_sparse, None, "test")

    data_length = len(datasets)
    if not data_length == args.data_length:
        print("Args.data_length is wrong!")
        sys.exit(0)

    kwargs = {
        "num_workers": args.num_workers,
        "pin_memory": True if args.mode is "train" else False
    }
    dataloaders = DataLoader(datasets,
                             args.batch_size,
                             shuffle=args.is_shuffle,
                             **kwargs)
    test_model(dataloaders, geo_full, geo_sparse)
    print("Run test_function.py Success!")
コード例 #4
0
def main(args):
    if args.use_cuda:
        print("Using GPU")
    else:
        print("Using CPU")
    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)

    datasets = BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                            geo_sparse, None, "test")

    data_length = len(datasets)
    if not data_length == args.data_length:
        print("Args.data_length is wrong!")
        sys.exit(0)

    # s_sparse = 0
    # m_sparse = 0
    # p_sparse = 0
    s_inter = 0
    m_inter = 0
    p_inter = 0
    s_new = 0
    m_new = 0
    p_new = 0
    for i in range(224):
        print("Testing sample {}/224".format(i))
        sample = datasets[i]
        image_true = Any2One(sample["image_true"])
        image_full = Any2One(sample["image_full"])
        image_sparse = Any2One(sample["image_sparse"])
        image_inter = Any2One(sample["image_inter"])
        sinogram_full = sample["sinogram_full"]
        sinogram_sparse = sample["sinogram_sparse"]
        sinogram_inter = sample["sinogram_inter"]

        # sinogram_new = SinoInter(sinogram_inter, geo_full, -2, "sinogram_LineInter", "z")
        sinogram_new = newinter(sinogram_sparse)
        image_new = Any2One(fbp(sinogram_new, geo_full))

        # ssim, mse, psnr = ssim_mse_psnr(image_full, image_sparse)
        # s_sparse = s_sparse + ssim
        # m_sparse = m_sparse + mse
        # p_sparse = p_sparse + psnr
        ssim, mse, psnr = ssim_mse_psnr(image_full, image_inter)
        s_inter = s_inter + ssim
        m_inter = m_inter + mse
        p_inter = p_inter + psnr
        ssim, mse, psnr = ssim_mse_psnr(image_full, image_new)
        s_new = s_new + ssim
        m_new = m_new + mse
        p_new = p_new + psnr

    # print("Sparse:", s_sparse/224, m_sparse/224, p_sparse/224)
    print("Inter:", s_inter / 224, m_inter / 224, p_inter / 224)
    print("New:", s_new / 224, m_new / 224, p_new / 224)
コード例 #5
0
def main(args):
    print("-"*15, "Version:{}".format(args.version), "-"*15)
    print("*"*50)

    index = np.random.randint(low=0, high=args.data_length["test"])
    datasets = {"test": BuildDataSet(args.data_root_path, args.test_folder, None, args.data_length["test"], "test", patch_size=512)}

    sample = datasets["test"][index]
    full_image = sample["full_image"]
    quarter_image = sample["quarter_image"]
    quarter_pred_image = copy.copy(quarter_image)

    """
    ***********************************************************************************************************
    Test model
    ***********************************************************************************************************
    # """ 
    model = WGAN_SACNN_AE(args.batch_size[args.mode], args.root_path, args.model_version)
    full_image = rec_image(full_image[0,:,:,:])
    quarter_image = rec_image(quarter_image[0,:,:,:])
    for i in [195, 210, 220, 235, 340, 345]:
        if 1:
            model_index = i 

    # for i in range(0, 100):
    #     if i*5 > 305 :
    #         model_index = i*5
            
            quarter_pred_image1 = copy.copy(quarter_pred_image)
            model = model_updata(model, model_old_name=args.model_name + "{}".format(model_index), model_old_path=args.model_path)
            pred_image = pred_sample(quarter_pred_image1, model.generator)
            pred_image = rec_image(pred_image[0,:,:,:])
            del quarter_pred_image1

            # """
            # ***********************************************************************************************************
            # Show images
            # ***********************************************************************************************************
            # """
            plt.figure()
            plt.subplot(231), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[1,:,:], cmap="gray"),                          plt.title("Full image")
            plt.subplot(232), plt.xticks([]), plt.yticks([]), plt.imshow(quarter_image[1,:,:], cmap="gray"),                       plt.title("Quarter image")
            plt.subplot(233), plt.xticks([]), plt.yticks([]), plt.imshow(pred_image[1,:,:], cmap="gray"),                          plt.title("Pred image")
            plt.subplot(234), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[1,:,:]-full_image[1,:,:], cmap="gray"),      plt.title("Full res image")
            plt.subplot(235), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[1,:,:]-quarter_image[1,:,:], cmap="gray"),   plt.title("Quarter res image")
            plt.subplot(236), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[1,:,:]-pred_image[1,:,:], cmap="gray"),      plt.title("Pred res image")
            plt.show()
        else:
            pass 
コード例 #6
0
def main(args):
    if args.use_cuda:
        print("Using GPU")
    else:
        print("Using CPU")

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)

    datasets = BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                            geo_sparse, None, "test")
    kwargs = {
        "num_workers": args.num_workers,
        "pin_memory": True if args.mode is "train" else False
    }
    dataloaders = DataLoader(datasets,
                             args.batch_size,
                             shuffle=args.is_shuffle,
                             **kwargs)

    refs = ("image_true", "image_full")
    options = ("sinogram_LineInter", "other")
    zOfs = ("other", "z")

    phase = "find"

    for ref in refs:
        for option in options:
            for zOf in zOfs:
                result_name = ref + "_" + option + "_" + zOf
                result_path = args.root_path + "/Resul/Tred/FindTheBest_Result"

                if phase is "find":
                    print("Ref:{}, Option:{}, ZOf:{}".format(ref, option, zOf))
                    result = test_f(dataloaders, geo_full, option, zOf, ref)
                    print(result)
                    check_dir(result_path)
                    np.save(result_path + result_name + ".npy", result)
                elif phase is "read":
                    result = np.load(result_path + result_name + ".npy")
                    print("Result Name:{}".format(result_name))
                    print(result)
                else:
                    print("There are some wrong")
                    sys.exit(0)

    print("Run Done")
コード例 #7
0
ファイル: prove.py プロジェクト: guoyii/Resul
def main(args):
    if args.use_cuda:
        print("Using GPU")
    else:
        print("Using CPU")

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)

    result_path_1 = args.root_path + "/IterDa/results/Iter_1/v3/model/IterDa_E199_val_Best.pth"
    model_i1 = torch.load(result_path_1, map_location=torch.device('cpu'))

    datasets = BuildDataSet(args.data_root_path, args.test_folder, geo_full, geo_sparse, None, "test")
    sample = datasets[0]  
    image_true = sample["image_true"] 
    image_full = sample["image_full"] 
    image_sparse = sample["image_sparse"] 
    sinogram_sparse = sample["sinogram_sparse"]
    sinogram_full = sample["sinogram_full"]

    image_pred = pred_sample(image_sparse, model_i1)
    sinogram_full_pred = project(image_pred, geo_full)
    sinogram_sparse_pred = sparse_view_f(sinogram_full_pred, geo_full["sino_views"], geo_sparse["sino_views"])

    sinogram_updata = updata_sinogram(sinogram_sparse, sinogram_full_pred)
    image_updata = fbp(sinogram_updata, geo_full)

    # plt.figure()
    # plt.subplot(131), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_sparse, cmap="gray"),       plt.title("(a)", y=-2)
    # plt.subplot(132), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_sparse_pred, cmap="gray"),  plt.title("(b)", y=-2)
    # plt.subplot(133), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_sparse - sinogram_sparse_pred, cmap="gray"), plt.title("(c)", y=-2)
    # plt.savefig("V:/users/gy/MyProject/Resul/Tred/Image/image4-3.png")
    # plt.show()
    plt.figure()
    plt.subplot(131), plt.xticks([]), plt.yticks([]), plt.imshow(image_full, cmap="gray"),       plt.title("(a)", y=-2)
    plt.subplot(132), plt.xticks([]), plt.yticks([]), plt.imshow(image_pred, cmap="gray"),  plt.title("(b)", y=-2)
    plt.subplot(133), plt.xticks([]), plt.yticks([]), plt.imshow(image_updata, cmap="gray"), plt.title("(c)", y=-2)
    # plt.savefig("V:/users/gy/MyProject/Resul/Tred/Image/image4-3.png")
    plt.show()
    ssim,se,psnr = ssim_mse_psnr(Any2One(image_full), Any2One(image_pred))
    print("Pred:", ssim,se,psnr)
    ssim,se,psnr = ssim_mse_psnr(Any2One(image_full), Any2One(image_updata))
    print("Updata:", ssim,se,psnr)
    print("Run Done")
コード例 #8
0
def main(args):
    if args.use_cuda:
        print("Using GPU")
        root_path = "/mnt/tabgha/users/gy/MyProject"
    else:
        print("Using CPU")
        root_path = "V:/users/gy/MyProject"

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)

    datasets = BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                            geo_sparse, None, "test")
    sample = datasets[0]
    image_true = sample["image_true"]
    image_full = sample["image_full"]
    image_sparse = sample["image_sparse"]
    sinogram_sparse = sample["sinogram_sparse"]

    image_pred = rec_other(sinogram_sparse, geo_sparse, "CGLS", 30)
    image_pred = rec_other(sinogram_sparse, geo_sparse, "SART", 100)
    image_pred = Any2One(image_pred)

    plt.figure()
    plt.subplot(231), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_true, cmap="gray"), plt.title("image_true")
    plt.subplot(232), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_full, cmap="gray"), plt.title("image_full")
    plt.subplot(233), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_sparse, cmap="gray"), plt.title("image_sparse")
    plt.subplot(234), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_pred, cmap="gray"), plt.title("image_inter")
    # plt.subplot(235), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_sparse, cmap="gray"),   plt.title("sinogram_sparse")
    # plt.subplot(236), plt.xticks([]), plt.yticks([]), plt.imshow(image_origin, cmap="gray"),       plt.title("image_origin")
    # plt.savefig("test.png")
    plt.show()

    print("Run Done")


# if __name__ == "__main__":
#     parsers = InitParser()
#     main(parsers)
コード例 #9
0
ファイル: mymain.py プロジェクト: guoyii/UnetDa
def main(args):
    if args.use_cuda:
        print("Using GPU")
        torch.cuda.set_device(args.gpu_id)
    else:
        print("Using CPU")

    check_dir(args.result_path)
    check_dir(args.loss_path)
    check_dir(args.model_path)
    check_dir(args.optimizer_path)

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)

    pre_trans_img = [Transpose(), TensorFlip(0), TensorFlip(1)]
    datasets_v = {
        "train":
        BuildDataSet(args.data_root_path, args.train_folder, geo_full,
                     geo_sparse, pre_trans_img, "train"),
        "val":
        BuildDataSet(args.data_root_path, args.val_folder, geo_full,
                     geo_sparse, None, "val"),
        "test":
        BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                     geo_sparse, None, "test")
    }

    data_length = {x: len(datasets_v[x]) for x in ["train", "val", "test"]}
    print("Data length:Train:{} Val:{} Test:{}".format(data_length["train"],
                                                       data_length["val"],
                                                       data_length["test"]))
    if not data_length == args.data_length:
        print("Args.data_length is wrong!")
        sys.exit(0)

    batch_num = {
        x: int(data_length[x] / args.batch_size[x])
        for x in ["train", "val", "test"]
    }
    kwargs = {
        "num_workers": args.num_workers,
        "pin_memory": True if args.mode is "train" else False
    }
    dataloaders = {
        x: DataLoader(datasets_v[x],
                      args.batch_size[x],
                      shuffle=args.is_shuffle,
                      **kwargs)
        for x in ["train", "val", "test"]
    }

    ## *********************************************************************************************************
    model_parser = ModelInit()
    model = UnetDa(model_parser)
    criterion = torch.nn.MSELoss()
    if args.use_cuda:
        criterion = criterion.cuda()
        model = model.cuda()
    optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.999))
    scheduler = lr_scheduler.StepLR(
        optimizer, step_size=args.step_size,
        gamma=args.gamma) if args.is_lr_scheduler else None
    ## *********************************************************************************************************
    if args.mode is "train":
        train_model(model=model,
                    optimizer=optimizer,
                    geo_full=geo_full,
                    geo_sparse=geo_sparse,
                    dataloaders=dataloaders,
                    batch_num=batch_num,
                    criterion=criterion,
                    scheduler=scheduler,
                    args=args)
        print("Run train_function.py Success!")
    elif args.mode is "test":
        old_modle_path = args.old_modle_path
        model_reload_path = old_modle_path + "/" + args.old_modle_name + ".pkl"
        if os.path.isfile(model_reload_path):
            print("Loading previously trained network...")
            print(model_reload_path)
            checkpoint = torch.load(model_reload_path,
                                    map_location=lambda storage, loc: storage)
            model_dict = model.state_dict()
            checkpoint = {
                k: v
                for k, v in checkpoint.items() if k in model_dict
            }
            model_dict.update(checkpoint)
            model.load_state_dict(model_dict)
            del checkpoint
            torch.cuda.empty_cache()
            if args.use_cuda:
                model = model.cuda()
            print("Loading Done!")
        else:
            print("Loading Fail...")
            sys.exit(0)
        test_model(model=model,
                   dataloaders=dataloaders,
                   criterion=criterion,
                   batch_num=batch_num,
                   args=args)
        print("Run test_function.py Success!")
    else:
        print("\nPlease go to 'exhibit_main.py' to get more information!!\n")
コード例 #10
0
def main(args):
    if args.use_cuda:
        print("Using GPU")
        # torch.cuda.set_device(args.gpu_id)
    else:
        print("Using CPU")

    check_dir(args.result_path)

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)
    index = np.random.randint(0,223)


    datasets = {"train": BuildDataSet(args.data_root_path, args.train_folder, geo_full, geo_sparse, "train"),
                "val": BuildDataSet(args.data_root_path, args.val_folder, geo_full, geo_sparse, "val"),
                "test": BuildDataSet(args.data_root_path, args.test_folder, geo_full, geo_sparse, "test")}
    image, sinogram_full, sinogram_sparse, sinogram_LineInter, image_name = datasets["train"][index]
    res_sinogram = sinogram_full - sinogram_LineInter

    image_full = fbp(sinogram_full, geo_full)
    image_sparse = fbp(sinogram_sparse, geo_sparse)
    plt.figure()
    plt.xticks([])
    plt.yticks([])
    plt.imshow(image_sparse, "gray")
    # plt.title("sinogram_sparse")
    plt.show()
    
    # image_LineInter = fbp(sinogram_LineInter, geo_full)

    # ssim_0, mse_0, psnr_0 = ssim_mse_psnr(image, image_sparse)
    # ssim_1, mse_1, psnr_1 = ssim_mse_psnr(image, image_LineInter)
    # print("   Sparse Image--> SSIM:{}, MSE:{}, PSNR:{}".format(ssim_0, mse_0, psnr_0))
    # print("LineInter Image--> SSIM:{}, MSE:{}, PSNR:{}".format(ssim_1, mse_1, psnr_1))
    # time.sleep(5)

    # weg = test_f(sinogram_LineInter, geo_full, image)

    # sinogram_new = SinoInter(sinogram_LineInter, geo_full, weg) 
    # sinogram_res = sinogram_full - sinogram_new
    # image_new = fbp(sinogram_new, geo_full)

    # image_res = image_full - image_new

    # plt.figure()
    # plt.suptitle(image_name)
    # plt.subplot(231),plt.xticks([]),plt.yticks([]),plt.imshow(sinogram_full, "gray"),       plt.title("sinogram_full")
    # plt.subplot(232),plt.xticks([]),plt.yticks([]),plt.imshow(sinogram_sparse, "gray"),     plt.title("sinogram_sparse")
    # plt.subplot(233),plt.xticks([]),plt.yticks([]),plt.imshow(sinogram_LineInter, "gray"),  plt.title("sinogram_LineInter")
    # # plt.subplot(234),plt.xticks([]),plt.yticks([]),plt.imshow(res_sinogram, "gray"),        plt.title("res_sinogram")
    # # plt.subplot(235),plt.xticks([]),plt.yticks([]),plt.imshow(sinogram_new, "gray"),        plt.title("sinogram_new")
    # # plt.subplot(236),plt.xticks([]),plt.yticks([]),plt.imshow(sinogram_res, "gray"),        plt.title("sinogram_res")
    # plt.show()
    # plt.figure()
    # plt.suptitle(image_name)
    # plt.subplot(231),plt.xticks([]),plt.yticks([]),plt.imshow(image, "gray"),           plt.title("image")
    # plt.subplot(232),plt.xticks([]),plt.yticks([]),plt.imshow(image_full, "gray"),      plt.title("image_full")
    # plt.subplot(233),plt.xticks([]),plt.yticks([]),plt.imshow(image_sparse, "gray"),    plt.title("image_sparse")
    # plt.subplot(234),plt.xticks([]),plt.yticks([]),plt.imshow(image_LineInter, "gray"), plt.title("image_LineInter")
    # plt.subplot(235),plt.xticks([]),plt.yticks([]),plt.imshow(image_new, "gray"),       plt.title("image_new")
    # plt.subplot(236),plt.xticks([]),plt.yticks([]),plt.imshow(image_res, "gray"),    plt.title("image_res")
    # plt.show()

    # ssim_0, mse_0, psnr_0 = ssim_mse_psnr(image_full, image_sparse)
    # ssim_1, mse_1, psnr_1 = ssim_mse_psnr(image_full, image_LineInter)
    # ssim_2, mse_2, psnr_2 = ssim_mse_psnr(image_full, image_new)
    # ssim_0, mse_0, psnr_0 = ssim_mse_psnr(image, image_sparse)
    # ssim_1, mse_1, psnr_1 = ssim_mse_psnr(image, image_LineInter)
    # ssim_2, mse_2, psnr_2 = ssim_mse_psnr(image, image_new)
    # print("   Sparse Image--> SSIM:{}, MSE:{}, PSNR:{}".format(ssim_0, mse_0, psnr_0))
    # print("LineInter Image--> SSIM:{}, MSE:{}, PSNR:{}".format(ssim_1, mse_1, psnr_1))
    # print("      New Image--> SSIM:{}, MSE:{}, PSNR:{}".format(ssim_2, mse_2, psnr_2))
    print("Run Done")
コード例 #11
0
def main(args):
    print("*" * 50)
    print("-" * 20, "Version:{}".format(args.version), "-" * 20)
    print("*" * 50)

    index = np.random.randint(low=0, high=223)

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)
    pre_trans_img = [Transpose(), TensorFlip(0), TensorFlip(1)]
    datasets_v = {
        "train":
        BuildDataSet(args.data_root_path, args.train_folder, geo_full,
                     geo_sparse, pre_trans_img, "train"),
        "val":
        BuildDataSet(args.data_root_path, args.val_folder, geo_full,
                     geo_sparse, None, "val"),
        "test":
        BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                     geo_sparse, None, "test")
    }

    sample = datasets_v["test"][index]
    image_true = sample["image_true"]
    image_full = sample["image_full"][0].numpy()
    image_sparse = sample["image_sparse"][0].numpy()
    image_res = sample["image_res"][0].numpy()
    """
    ***********************************************************************************************************
    Show Loss
    ***********************************************************************************************************
    """
    TrainBestEpoch, ValBestEpoch = read_loss(loss_name="min_loss_epoch",
                                             loss_path=args.loss_path)
    TrainBestLoss, ValBestLoss = read_loss(loss_name="min_loss",
                                           loss_path=args.loss_path)
    print("TrainBestEpoch:{}, ValBestEpoch:{}".format(TrainBestEpoch,
                                                      ValBestEpoch))
    print("TrainBestLoss:{:.6f}, ValBestLoss:{:.6f}".format(
        TrainBestLoss, ValBestLoss))
    show_loss(loss_name="losses", loss_path=args.loss_path)
    """
    ***********************************************************************************************************
    Test model
    ***********************************************************************************************************
    """
    modelparser = ModelInit()
    model = UnetDa(modelparser)
    model = model_updata(model,
                         model_old_name=args.model_name +
                         "{}_{}_Best".format(ValBestEpoch, "val"),
                         model_old_path=args.model_path)
    print("Load Modle...")
    # print(args.root_path + "/results/Iter_{}/{}/model/IterDa_E{}_val_Best.pth".format(args.iter, args.version,ValBestEpoch))
    # model =  torch.load(args.root_path + "/results/Iter_{}/{}/model/IterDa_E{}_val_Best.pth".format(args.iter, args.version,ValBestEpoch),
    #                     map_location=torch.device('cpu'))
    res_pred = pred_sample(image_sparse, model)
    image_pred = image_sparse + res_pred
    """
    ***********************************************************************************************************
    Show images
    ***********************************************************************************************************
    """
    plt.figure()
    plt.subplot(231), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_true, cmap="gray"), plt.title("image_true")
    plt.subplot(232), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_full, cmap="gray"), plt.title("image_full")
    plt.subplot(233), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_sparse, cmap="gray"), plt.title("image_sparse")
    plt.subplot(234), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_res, cmap="gray"), plt.title("image_res")
    plt.subplot(235), plt.xticks([]), plt.yticks([]), plt.imshow(
        res_pred, cmap="gray"), plt.title("res_pred")
    plt.subplot(236), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_pred, cmap="gray"), plt.title("image_pred")
    plt.show()

    plt.figure()
    plt.subplot(231), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_full, cmap="gray"), plt.title("image_full")
    plt.subplot(232), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_sparse, cmap="gray"), plt.title("image_sparse")
    plt.subplot(233), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_pred, cmap="gray"), plt.title("image_pred")
    plt.subplot(234), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_true, cmap="gray"), plt.title("image_true")
    plt.subplot(235), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_full - image_sparse, cmap="gray"), plt.title("Res image_sparse")
    plt.subplot(236), plt.xticks([]), plt.yticks([]), plt.imshow(
        image_full - image_pred, cmap="gray"), plt.title("Res image_pred")
    plt.show()
    """
    ***********************************************************************************************************
    量化指标
    ***********************************************************************************************************
    """
    ssim_0, mse_0, psnr_0 = ssim_mse_psnr(image_full, image_sparse)
    ssim_1, mse_1, psnr_1 = ssim_mse_psnr(image_full, image_pred)
    print("Sparse Image--> SSIM:{}, MSE:{}, PSNR:{}".format(
        ssim_0, mse_0, psnr_0))
    print("Pred Image--> SSIM:{}, MSE:{}, PSNR:{}".format(
        ssim_1, mse_1, psnr_1))
コード例 #12
0
ファイル: exhibit.py プロジェクト: guoyii/Resul
def main(args):
    if args.use_cuda:
        print("Using GPU")
    else:
        print("Using CPU")

    if torch.cuda.is_available():
        root_path = "/mnt/tabgha/users/gy/MyProject"
    else:
        root_path = "V:/users/gy/MyProject"

    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)

    datasets = BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                            geo_sparse, None, "test")

    data_length = len(datasets)
    if not data_length == args.data_length:
        print("Args.data_length is wrong!")
        sys.exit(0)

    sample = datasets[0]
    image_true = sample["image_true"]
    image_full = sample["image_full"]
    image_sparse = sample["image_sparse"]
    image_inter = sample["image_inter"]
    sinogram_sparse = sample["sinogram_sparse"]

    unetda = Unetda(root_path)
    iterda = Iterda(root_path, sinogram_sparse, geo_full)
    image_unet = unetda(image_sparse)
    image_iter = iterda(image_sparse)
    start_time = time.time()
    image_cgls = rec_other(sinogram_sparse, geo_sparse, "CGLS", 30)
    print("CGLS Time:{:.4f}s".format(time.time() - start_time))
    start_time = time.time()
    image_sart = rec_other(sinogram_sparse, geo_sparse, "SART", 100)
    print("SART Time:{:.4f}s".format(time.time() - start_time))

    image_1 = np.hstack((
        Any2One(image_full),
        Any2One(image_sparse),
        Any2One(image_cgls),
        Any2One(image_sart),
        Any2One(image_unet),
        Any2One(image_iter),
    ))
    image_2 = np.hstack((
        np.zeros(image_full.shape),
        Any2One(image_full - image_sparse),
        Any2One(image_full - image_cgls),
        Any2One(image_full - image_sart),
        Any2One(image_full - image_unet),
        Any2One(image_full - image_iter),
    ))
    image_all = np.vstack((image_1, image_2))

    plt.figure()
    plt.xticks([])
    plt.yticks([])
    plt.imshow(image_all, cmap="gray")
    plt.savefig("V:/users/gy/毕业设计/生物医学工程/论文/图表/第四章/图4-3.png")
    plt.show()
    ssim, mse, psnr = ssim_mse_psnr(image_full, image_sparse)
    print("Sparse:", ssim, mse, psnr)
    ssim, mse, psnr = ssim_mse_psnr(image_full, image_cgls)
    print("CGLS:", ssim, mse, psnr)
    ssim, mse, psnr = ssim_mse_psnr(image_full, image_sart)
    print("SART:", ssim, mse, psnr)
    ssim, mse, psnr = ssim_mse_psnr(image_full, image_unet)
    print("Unet:", ssim, mse, psnr)
    ssim, mse, psnr = ssim_mse_psnr(image_full, image_iter)
    print("Iter:", ssim, mse, psnr)
コード例 #13
0
ファイル: exhibit.py プロジェクト: wuzhan11/SACNN
def main(args):
    print("-" * 15, "Version:{}".format(args.version), "-" * 15)
    print("*" * 50)

    index = np.random.randint(low=0, high=args.data_length["test"])
    datasets = {
        "test":
        BuildDataSet(args.data_root_path,
                     args.test_folder,
                     None,
                     args.data_length["test"],
                     "test",
                     patch_size=512)
    }

    sample = datasets["test"][index]
    full_image = sample["full_image"]
    quarter_image = sample["quarter_image"]
    quarter_pred_image = copy.copy(quarter_image)
    """
    ***********************************************************************************************************
    Show Loss
    ***********************************************************************************************************
    """
    loss_train, loss_val = read_loss("losses", args.loss_path)
    Wasserstein = -(loss_train[:, 2] + loss_train[:, 3])
    show_Wasserstein(Wasserstein)
    show_loss(loss_train)
    plt.show()
    """
    ***********************************************************************************************************
    Test model
    ***********************************************************************************************************
    # """
    model_index = args.model_index
    model = WGAN_SACNN_AE(args.batch_size[args.mode], args.root_path,
                          args.model_version)
    model = model_updata(model,
                         model_old_name=args.model_name +
                         "{}".format(model_index),
                         model_old_path=args.model_path)
    pred_image = pred_sample(quarter_pred_image, model.generator)
    print("Full_Image Shape", full_image.shape)
    print("Quarter_Image Shape", quarter_image.shape)
    print("Pred_Image Shape", pred_image.shape)
    if 1:
        full_image = rec_image(full_image[0, :, :, :])
        quarter_image = rec_image(quarter_image[0, :, :, :])
        pred_image = rec_image(pred_image[0, :, :, :])
    else:
        full_image = full_image[0, :, :, :].numpy()
        quarter_image = quarter_image[0, :, :, :].numpy()
        pred_image = pred_image[0, :, :, :].numpy()

    scio.savemat(
        args.result_path + "/image.mat", {
            'full_image': full_image,
            'quarter_image': quarter_image,
            'pred_image': pred_image
        })
    """
    ***********************************************************************************************************
    量化指标
    ***********************************************************************************************************
    """
    # ssim_0, mse_0, psnr_0 = ssim_mse_psnr(full_image[1,:,:], quarter_image[1,:,:])
    # ssim_1, mse_1, psnr_1 = ssim_mse_psnr(full_image[1,:,:], pred_image[1,:,:])
    # print("Quarter Image--> SSIM:{}, MSE:{}, PSNR:{}".format(ssim_0, mse_0, psnr_0))
    # print("Predict Image--> SSIM:{}, MSE:{}, PSNR:{}".format(ssim_1, mse_1, psnr_1))

    # """
    # ***********************************************************************************************************
    # Show images
    # ***********************************************************************************************************
    # """
    # plt.figure()
    # plt.subplot(331), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[0,:,:], cmap="gray"),                          plt.title("full_image")
    # plt.subplot(332), plt.xticks([]), plt.yticks([]), plt.imshow(quarter_image[0,:,:], cmap="gray"),                       plt.title("quarter_image")
    # plt.subplot(333), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[0,:,:]-quarter_image[0,:,:], cmap="gray"),   plt.title("res_image")
    # plt.subplot(334), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[1,:,:], cmap="gray"),                          plt.title("full_image")
    # plt.subplot(335), plt.xticks([]), plt.yticks([]), plt.imshow(quarter_image[1,:,:], cmap="gray"),                       plt.title("quarter_image")
    # plt.subplot(336), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[1,:,:]-quarter_image[1,:,:], cmap="gray"),   plt.title("res_image")
    # plt.subplot(337), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[2,:,:], cmap="gray"),                          plt.title("full_image")
    # plt.subplot(338), plt.xticks([]), plt.yticks([]), plt.imshow(quarter_image[2,:,:], cmap="gray"),                       plt.title("quarter_image")
    # plt.subplot(339), plt.xticks([]), plt.yticks([]), plt.imshow(full_image[2,:,:]-quarter_image[2,:,:], cmap="gray"),   plt.title("res_image")
    # plt.show()

    plt.figure()
    plt.subplot(231), plt.xticks([]), plt.yticks([]), plt.imshow(
        full_image[1, :, :], cmap="gray"), plt.title("Full image")
    plt.subplot(232), plt.xticks([]), plt.yticks([]), plt.imshow(
        quarter_image[1, :, :], cmap="gray"), plt.title("Quarter image")
    plt.subplot(233), plt.xticks([]), plt.yticks([]), plt.imshow(
        pred_image[1, :, :], cmap="gray"), plt.title("Pred image")
    plt.subplot(234), plt.xticks([]), plt.yticks(
        []), plt.imshow(full_image[1, :, :] - full_image[1, :, :],
                        cmap="gray"), plt.title("Full res image")
    plt.subplot(235), plt.xticks([]), plt.yticks(
        []), plt.imshow(full_image[1, :, :] - quarter_image[1, :, :],
                        cmap="gray"), plt.title("Quarter res image")
    plt.subplot(236), plt.xticks([]), plt.yticks(
        []), plt.imshow(full_image[1, :, :] - pred_image[1, :, :],
                        cmap="gray"), plt.title("Pred res image")
    plt.show()
コード例 #14
0
def main(args):
    if args.use_cuda:
        print("Using GPU")
    else:
        print("Using CPU")
    geo_full = build_geo(args.full_view)
    geo_sparse = build_geo(args.sparse_view)
    index = np.random.randint(low=0, high=223)
    index = 185
    # 100
    print("Index:", index)
    datasets = BuildDataSet(args.data_root_path, args.test_folder, geo_full,
                            geo_sparse, None, "test")

    data_length = len(datasets)
    if not data_length == args.data_length:
        print("Args.data_length is wrong!")
        sys.exit(0)
    sample = datasets[index]

    image_true = Any2One(sample["image_true"])
    image_full = Any2One(sample["image_full"])
    image_sparse = Any2One(sample["image_sparse"])
    image_inter = Any2One(sample["image_inter"])
    # sinogram_full = sample["sinogram_full"]
    # sinogram_sparse = sample["sinogram_sparse"]
    # sinogram_inter = sample["sinogram_inter"]
    plt.figure()
    plt.subplot(121), plt.xticks([]), plt.yticks([]), plt.imshow(image_full,
                                                                 cmap="gray")
    plt.subplot(122), plt.xticks([]), plt.yticks([]), plt.imshow(image_sparse,
                                                                 cmap="gray")
    plt.show()
    """
    **************************************************
    Image 4-1
    **************************************************
    """
    # sinogram_new = SinoInter(sinogram_inter, geo_full, -3, "sinogram_LineInter", "z")
    # sinogram_new = newinter(sinogram_sparse)
    # image_new = Any2One(fbp(sinogram_new, geo_full))
    # plt.figure()
    # plt.subplot(341), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_full, cmap="gray"),   plt.title("(a)", y=-0.22)
    # plt.subplot(342), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_sparse, cmap="gray"), plt.title("(b)", y=-8.5)
    # plt.subplot(343), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_inter, cmap="gray"),     plt.title("(c)",  y=-0.22)
    # plt.subplot(344), plt.xticks([]), plt.yticks([]), plt.imshow(sinogram_new, cmap="gray"),   plt.title("(d)",  y=-0.22)
    # plt.subplot(345), plt.xticks([]), plt.yticks([]), plt.imshow(image_full, cmap="gray"),   plt.title("(e)", y=-0.22)
    # plt.subplot(346), plt.xticks([]), plt.yticks([]), plt.imshow(image_sparse, cmap="gray"), plt.title("(f)", y=-0.22)
    # plt.subplot(347), plt.xticks([]), plt.yticks([]), plt.imshow(image_inter, cmap="gray"),     plt.title("(g)",  y=-0.22)
    # plt.subplot(348), plt.xticks([]), plt.yticks([]), plt.imshow(image_new, cmap="gray"),   plt.title("(h)",  y=-0.2)
    # plt.subplot(349), plt.xticks([]), plt.yticks([]), plt.imshow(image_full-image_full, cmap="gray"),   plt.title("(i)", y=-0.22)
    # plt.subplot(3,4,10), plt.xticks([]), plt.yticks([]), plt.imshow(image_full-image_sparse, cmap="gray"), plt.title("(j)", y=-0.22)
    # plt.subplot(3,4,11), plt.xticks([]), plt.yticks([]), plt.imshow(image_full-image_inter, cmap="gray"),     plt.title("(k)",  y=-0.22)
    # plt.subplot(3,4,12), plt.xticks([]), plt.yticks([]), plt.imshow(image_full-image_new, cmap="gray"),   plt.title("(l)",  y=-0.22)
    # # plt.savefig("V:/users/gy/MyProject/Resul/Tred/Image/image4-1.png")
    # plt.show()
    """
    **************************************************
    шби 4-1
    **************************************************
    """
    # ssim, mse, psnr = ssim_mse_psnr(image_full, image_sparse)
    # print("Sparse:", ssim, mse, psnr)
    # ssim, mse, psnr = ssim_mse_psnr(image_full, image_inter)
    # print("Inter:", ssim, mse, psnr)
    # ssim, mse, psnr = ssim_mse_psnr(image_full, image_new)
    # print("New:", ssim, mse, psnr)
    """