Esempio n. 1
0
    #transforms.ToTensor()
])

have_cuda = torch.cuda.is_available()
start_epoch = 2
epochs = 3

data_dir = "./places365_standard/train/"
train_set = TrainImageFolder(data_dir, original_transform)
train_set_size = len(train_set)
train_set_classes = train_set.classes
train_loader = torch.utils.data.DataLoader(train_set,
                                           batch_size=64,
                                           shuffle=True,
                                           num_workers=8)
color_model = torch.nn.DataParallel(ColorNet())
if os.path.exists('./pretrained/colornet_params.pkl'):
    color_model.load_state_dict(torch.load('./pretrained/colornet_params.pkl'))
if have_cuda:
    color_model.cuda()
optimizer = optim.Adadelta(color_model.parameters())

if have_cuda:
    print("Have cuda")
else:
    print("No cuda")


def train(epoch):
    color_model.train()
Esempio n. 2
0
# Define transformation
original_transform = transforms.Compose([
    transforms.Resize(256),
    # transforms.RandomCrop(224),
])

# Read dataset
test_set = TrainImageFolder(data_dir, original_transform)
test_loader = torch.utils.data.DataLoader(test_set,
                                          batch_size=batch_size,
                                          shuffle=False,
                                          num_workers=num_workers)

# Define model
colornet = ColorNet()
model = colornet.model
model.load_state_dict(torch.load('./revisions/multi_data/colornet_params.pkl'))
if cuda:
    model.cuda()

i = 0
with torch.no_grad():
    for data, _ in test_loader:
        if cuda:
            data = data.cuda()

        pred = model(data)
        pred = pred * 128

        color_img = torch.cat((data, pred), 1)
Esempio n. 3
0
    transforms.Scale(256),
    transforms.RandomCrop(224),
    transforms.RandomHorizontalFlip(),
    #transforms.ToTensor()
])

# have_cuda = torch.cuda.is_available()
epochs = 1
writer = SummaryWriter("MyTest")

data_dir = "../images256/"
train_set = TrainImageFolder(data_dir, original_transform)
train_set_size = len(train_set)
train_set_classes = train_set.classes
train_loader = torch.utils.data.DataLoader(train_set, batch_size=32, shuffle=True, num_workers=4)
color_model = ColorNet()

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

color_model = nn.DataParallel(color_model)
color_model.to(device)

if os.path.exists('./colornet_params.pkl'):
    color_model.load_state_dict(torch.load('colornet_params.pkl'))
# if have_cuda:
#     color_model.cuda()
optimizer = optim.Adadelta(color_model.parameters())


def train(epoch):
    color_model.train()
Esempio n. 4
0
from PIL import Image
from torchvision import transforms
import numpy as np
import torch
from skimage.color import lab2rgb, rgb2gray
import matplotlib.pyplot as plt
from torch.autograd import Variable
from colornet import ColorNet

# 配置cuda
have_cuda = torch.cuda.is_available()
color_model = ColorNet()  # 网络架构
color_model.load_state_dict(torch.load('colornet_params.pkl'))  # 参数路径
if have_cuda:
    color_model.cuda()
color_model.eval()


# 处理图像,转成黑白和彩色,供GUI调用
def Picture(name):
    img_name = name  # 输入图片的路径
    img = Image.open(img_name)
    scale_transform = transforms.Compose([
        transforms.Resize(256),
        transforms.RandomCrop(224),  # 剪切图片大小为224*224
    ])
    img1 = scale_transform(img)

    img_scale = np.asarray(img1)
    img_original = np.asarray(img)
Esempio n. 5
0
    #transforms.ToTensor()                              # 将PIL Image或者 ndarray 转换为tensor,并且归一化至[0-1]
])

have_cuda = torch.cuda.is_available()
epochs = 10
data_dir = "/input_dir/datasets/Caltech256/256_ObjectCategories"
# data_dir = "../images256/"
train_set = TrainImageFolder(data_dir, original_transform)  # 建训练集
train_set_size = len(train_set)
train_set_classes = train_set.classes  # classes (list): List of the class names.
print('train_set_classes', train_set_classes)
train_loader = torch.utils.data.DataLoader(train_set,
                                           batch_size=16,
                                           shuffle=True,
                                           num_workers=4)
color_model = ColorNet()
if os.path.exists('/output_dir/colornet_paramsCaltech257.pkl'):
    color_model.load_state_dict(
        torch.load('/output_dir/colornet_paramsCaltech257.pkl'))
if have_cuda:
    color_model.cuda()
optimizer = optim.Adadelta(color_model.parameters())  # 优化方案:Adadelta


def train(epoch):
    color_model.train()

    try:
        for batch_idx, (data, classes) in enumerate(train_loader):
            messagefile = open('/output_dir/message.txt', 'a')
            original_img = data[0].unsqueeze(1).float()  # 在第一维增加一个维度
Esempio n. 6
0
    transforms.CenterCrop(900),
    #transforms.RandomHorizontalFlip(),
    #transforms.ToTensor()
])
torch.cuda.empty_cache()
data_dir = "images256"
have_cuda = torch.cuda.is_available()

val_set = ValImageFolder(data_dir, original_transform)
val_set_size = len(val_set)
val_loader = torch.utils.data.DataLoader(val_set,
                                         batch_size=1,
                                         shuffle=False,
                                         num_workers=0)

color_model = ColorNet()
color_model.load_state_dict(torch.load('colornet_params.pkl'))
if have_cuda:
    color_model.cuda()


def val():
    color_model.eval()
    torch.cuda.empty_cache()
    i = 0
    for data, _ in val_loader:
        original_img = data[0].unsqueeze(1).float()
        gray_name = 'gray/' + str(i) + '.jpg'
        for img in original_img:
            pic = img.squeeze().numpy()
            pic = pic.astype(np.float64)
Esempio n. 7
0
    raise Exception("No GPU found, please run without --cuda")

torch.manual_seed(opt.seed)
if cuda:
    torch.cuda.manual_seed(opt.seed)

print('===> Loading datasets')
train_set = get_training_colorset(opt.data_dir, opt.nFrames, opt.upscale_factor, opt.data_augmentation, opt.hr_flist, opt.lr_flist, opt.other_dataset, opt.patch_size, opt.future_frame)
training_data_loader = DataLoader(dataset=train_set, num_workers=opt.threads, batch_size=opt.batchSize, shuffle=True)
test_set = get_test_colorset(opt.data_dir, opt.nFrames, opt.upscale_factor, opt.test_flist, opt.other_dataset, opt.future_frame)
testing_data_loader = DataLoader(dataset=test_set, num_workers=opt.threads, batch_size=opt.testBatchSize, shuffle=False)
img_names = [line.rstrip() for line in open(opt.test_flist)]

print('===> Building model ', opt.model_type)
if opt.model_type == 'ColorNet':
    model = ColorNet()
model = torch.nn.DataParallel(model, device_ids=gpus_list)
criterion = nn.L1Loss()


print('---------- Networks architecture -------------')
print_network(model)
print('----------------------------------------------')

if opt.pretrained or opt.test_only:
    model_name = os.path.join(opt.save_folder + opt.pretrained_sr)
    if os.path.exists(model_name):
        model.load_state_dict(torch.load(model_name, map_location=lambda storage, loc: storage))
        print('Pre-trained SR model is loaded.')

if cuda:
Esempio n. 8
0
from skimage import io
from colornet import ColorNet
from myimgfolder import ValImageFolder
import numpy as np
import matplotlib.pyplot as plt
from colornet import ColorNet
from pt1.dataset import ColorDataset

device = torch.device('cuda' if torch.cuda.is_available() else 'gpu')
BZ = 1
test_set = ColorDataset('test')
test_loader = torch.utils.data.DataLoader(test_set,
                                          batch_size=BZ,
                                          shuffle=False,
                                          num_workers=4)
color_model = ColorNet()
color_model.load_state_dict(torch.load('/home/wsf/colornet_params.pkl'))
color_model.to(device)


def test():
    color_model.eval()

    for idx, (imgs, imgs_scale) in enumerate(test_loader):
        imgs = imgs.to(device)
        imgs_scale = imgs_scale.to(device)
        gray_name = test_set.samples[idx].strip().split('/')[-1]
        for img in imgs:
            pic = img.cpu().squeeze().numpy()
            pic = pic.astype(np.float64)
            plt.imsave('./{}/{}'.format('grayimg', gray_name),