def main(): dataloaders = myDataloader() test_loader = dataloaders.getTestLoader(batch_size) model = SRCNN().cuda() model.load_state_dict(torch.load("./result/train/20srcnnParms.pth")) model.eval() with torch.no_grad(): for i, (pic, blurPic, index) in enumerate(test_loader): blurPic = blurPic.cuda() out = model(blurPic).cpu() blurPic = blurPic.cpu() showImages(pic[0]) showImages(blurPic[0]) showImages(out[0]) print(index) break
def main(): dataloaders = myDataloader() test_loader = dataloaders.getTestLoader(batch_size) model = SRCNN().cuda() model.load_state_dict( torch.load("./result/train/" + str(epoch) + "srcnnParms.pth")) model.eval() with torch.no_grad(): for i, (pic, blurPic, index) in enumerate(test_loader): pic = pic.cuda() blurPic = blurPic.cuda() out = model(blurPic) res = torch.cosine_similarity(pic, out, dim=1) res = res[0] minValue = torch.min(res) meanValue = res.mean() output = 1 - ((res >= meanValue) + 0) plt.figure() plt.title(index) plt.imshow(output.cpu(), cmap="gray") plt.show() break
if args.cuda and not torch.cuda.is_available(): raise Exception('No GPU found') device = torch.device('cuda' if args.cuda else 'cpu') print('Use device:', device) filenames = os.listdir(args.img_dir) image_filenames = [os.path.join(args.img_dir, x) for x in filenames \ if is_image_file(x)] image_filenames = sorted(image_filenames) model = SRCNN().to(device) if args.cuda: ckpt = torch.load(args.model) else: ckpt = torch.load(args.model, map_location='cpu') model.load_state_dict(ckpt['model']) res = {} for i, f in enumerate(image_filenames): # Read test image. img = Image.open(f).convert('RGB') width, height = img.size[0], img.size[1] # Crop test image so that it has size that can be downsampled by the upscale factor. pad_width = width % args.upscale_factor pad_height = height % args.upscale_factor width -= pad_width height -= pad_height img = img.crop((0, 0, width, height)) img = _rgb2ycbcr(img)
parser.add_argument('--cuda', action='store_true', default=False) parser.add_argument('--weight_path', type=str, default=None) parser.add_argument('--save_dir', type=str, default=None) opt = parser.parse_args() test_set = DatasetFromFolderEval(image_dir='./data/General-100/test', scale_factor=4) test_loader = DataLoader(dataset=test_set, batch_size=1, shuffle=False) model = SRCNN() criterion = nn.MSELoss() if opt.cuda: model = model.cuda() criterion = criterion.cuda() model.load_state_dict( torch.load(opt.weight_path, map_location='cuda' if opt.cuda else 'cpu')) model.eval() total_loss, total_psnr = 0, 0 total_loss_b, total_psnr_b = 0, 0 with torch.no_grad(): for batch in test_loader: inputs, targets = batch[0], batch[1] if opt.cuda: inputs = inputs.cuda() targets = targets.cuda() prediction = model(inputs) loss = criterion(prediction, targets) total_loss += loss.data total_psnr += 10 * log10(1 / loss.data)
os.environ['CUDA_VISIBLE_DEVICES'] = '0, 1, 2, 3' Start_epoch = 0 End_epoch = 100 Evaluation = True test_path = '3.bmp' #================================================ model = SRCNN() if use_cuda: model = nn.DataParallel(model).cuda() #不要忘记在Dataparallel后面也加上.cuda() if resume: checkpoint = torch.load( checkpiont_path) #如果之前使用了model=dataparallel之后,网络结构会有所变化,因此在读取之前同样要赋值操作 model.load_state_dict(checkpoint['state']) Start_epoch = checkpoint['epoch'] train_config['lr'] = checkpoint['lr'] print('===============Load Model Successully', checkpiont_path) try: from tensorboardX import SummaryWriter except ImportError as reason: print('Use pip install tensorboardX', reason) else: writer = SummaryWriter(log_dir='writer_log', comment='--') print('================Use TensorBoard ================') #================================================= if Evaluation:
help="use CUDA to speed up computation") opt = parser.parse_args() # check cuda if opt.cuda and not torch.cuda.is_available(): raise Exception("No GPU found, please run without --cuda") # load LR image open_image = lambda x: TF.to_tensor(Image.open(x).convert("RGB")) image = open_image(opt.filename).unsqueeze(0) # load model device = torch.device( "cuda" if opt.cuda and torch.cuda.is_available() else "cpu") map_location = "cuda:0" if opt.cuda else device checkpoint = load_checkpoint(opt.checkpoint, map_location) # init model model = SRCNN() model.load_state_dict(checkpoint["model_state_dict"]) model.to(device) model.eval() # process input with torch.no_grad(): image = image.to(device) output = model(image) # save result output_name = os.path.splitext(opt.filename) output_name = "_srcnn_x3".join(output_name) torchvision.utils.save_image(output[0], output_name) print("Output HR image saved to '{output}'".format(output=output_name))
parser.add_argument('--scale', type=float, default=2.) return vars(parser.parse_args()) if __name__ == '__main__': args = get_arguments() weight = args.get('weight') p = args.get('input') upscale = args.get('scale') dirpath = os.path.dirname(p) input_filename = os.path.basename(p) gen = SRCNN() gen.load_state_dict(torch.load(weight)) gen.eval() img = Image.open(p) new_size = [int(x * upscale) for x in img.size] converter = T.Compose([ T.Resize(size=new_size[::-1], interpolation=Image.BICUBIC), T.ToTensor() ]) with torch.no_grad(): x = converter(img) pred = gen(x[None, :, :, :])[0] save_image(pred, os.path.join(dirpath, f'outputx{upscale}_{input_filename}'))
for path in tqdm(list(Path('BSDS300\\images\\test').iterdir())): img = Image.open(path).convert('YCbCr') y, cb, cr = img.split() img = img.resize( (int(img.size[0] * zoom_factor), int(img.size[1] * zoom_factor)), Image.BICUBIC) # first, we upscale the image via bicubic interpolation img.save(f'{path.stem}_bicubic.jpg') img_to_tensor = transforms.ToTensor() input = img_to_tensor(y).view( 1, -1, y.size[1], y.size[0]) # we only work with the "Y" channel device = torch.device("cpu") model = SRCNN() model.load_state_dict(torch.load('model_21.pth')) model = model.eval().to(device) input = input.to(device) with torch.no_grad(): out = model(input) out = out.cpu() out_img_y = out[0].numpy() out_img_y *= 255.0 out_img_y = out_img_y.clip(0, 255) out_img_y = Image.fromarray(np.uint8(out_img_y[0]), mode='L') out_img = Image.merge( 'YCbCr', [out_img_y,