当前位置:   article > 正文

【异常错误】不论在测试还是训练的时候都要归一化并反归一化,保存图像方法要合适

【异常错误】不论在测试还是训练的时候都要归一化并反归一化,保存图像方法要合适

一、图像归一化问题

这里没有在测试的时候给图像归一化,会导致输出的图像颜色上有很大问题,例如就会变成这样,

所以需要在进入model之前归一化,并且在输出之后反归一化才可以。

二、在保存图像的时候

使用“vutils.save_image”而别使用ToPILImage(),否则也会导致你的图像出现很大的问题

有问题:

  1. import torchvision.utils as vutils
  2. # 方式一:正常保存,没有问题
  3. vutils.save_image(decoded_img, os.path.join(out_dir_path, filename))

没有问题: 

  1. # 方式二:使用PIL保存,有问题
  2. out_img = ToPILImage()(decoded_img)
  3. out_img.save(os.path.join(out_dir_path, filename))

正确代码示例:

来自于:https://github.com/CompVis/latent-diffusion/pull/353/files#diff-d7c29e5cdd97960f10932618a1693a094a186fddb09b5d781d39d49508a6b6a7

  1. import torch
  2. from ldm.util import instantiate_from_config
  3. from omegaconf import OmegaConf
  4. from PIL import Image
  5. import torchvision.transforms as T
  6. import os
  7. import torchvision.utils as vutils
  8. import argparse
  9. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  10. def load_model_from_config(config, ckpt):
  11. print(f"Loading model from {ckpt}")
  12. pl_sd = torch.load(ckpt, map_location="cpu")
  13. global_step = pl_sd["global_step"]
  14. sd = pl_sd["state_dict"]
  15. model = instantiate_from_config(config.model)
  16. m, u = model.load_state_dict(sd, strict=False)
  17. model.to(device)
  18. model.eval()
  19. return {"model": model}, global_step
  20. def load_and_preprocess_image(image_path, resize_shape=(256, 256)):
  21. transform = T.Compose([
  22. T.Resize(resize_shape),
  23. T.ToTensor(),
  24. T.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
  25. ])
  26. image = Image.open(image_path).convert("RGB")
  27. return transform(image).unsqueeze(0).to(device)
  28. def reconstruct_image(model, image_tensor):
  29. with torch.no_grad():
  30. reconstructed_img, _ = model(image_tensor)
  31. return reconstructed_img
  32. def save_image(tensor, filename):
  33. print("Tensor Type:", type(tensor)) # Debugging line to confirm tensor type
  34. if isinstance(tensor, torch.Tensor):
  35. tensor = (tensor + 1) / 2 # Normalize if the tensor is in the range [-1, 1]
  36. vutils.save_image(tensor, filename)
  37. else:
  38. print("The input is not a tensor.")
  39. def reconstruct_and_save_images(input_dir, output_dir, model):
  40. for image_name in os.listdir(input_dir):
  41. if not image_name.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
  42. continue
  43. # 1、加载图像
  44. image_path = os.path.join(input_dir, image_name)
  45. # 2、将图像转为Tensor
  46. image_tensor = load_and_preprocess_image(image_path)
  47. # 3、将图像Tensor经过model重建为tensor
  48. reconstructed_img = reconstruct_image(model, image_tensor)
  49. # 4、保存重建的图像
  50. output_path = os.path.join(output_dir, image_name)
  51. save_image(reconstructed_img, output_path)
  52. def main(config_path, ckpt_path, input_dir, output_dir):
  53. config = OmegaConf.load(config_path)
  54. model_info, step = load_model_from_config(config, ckpt_path)
  55. model = model_info["model"]
  56. os.makedirs(output_dir, exist_ok=True)
  57. reconstruct_and_save_images(input_dir, output_dir, model)
  58. if __name__ == "__main__":
  59. parser = argparse.ArgumentParser(description="Reconstruct images from training autoencoder models")
  60. parser.add_argument('--config', type=str, required=True, help='Path to model config YAML file')
  61. parser.add_argument('--ckpt', type=str, required=True, help='Path to model checkpoint file')
  62. parser.add_argument('--input_dir', type=str, required=True, help='Directory where input images are stored')
  63. parser.add_argument('--output_dir', type=str, required=True, help='Directory where output images will be saved')
  64. args = parser.parse_args()
  65. main(args.config, args.ckpt, args.input_dir, args.output_dir)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/524289
推荐阅读
相关标签
  

闽ICP备14008679号