openCv 和 PyTorch 逆变器转换不工作

openCv and PyTorch inverser Transform not working

我有一个转换 class,它只做:

        if transform is None:
            transform = transforms.Compose([
                transforms.Resize((256, 256)),
                transforms.ToTensor()
            ])
        root = os.path.join(PROJECT_ROOT_DIR, "data")
        super(AttributesDataset, self).__init__()
        self.data = torchvision.datasets.CelebA(
            root=root,
            split=split,
            target_type='attr',
            download=True,
            transform=transform
        )

从文档中,我了解到这意味着只是按比例缩小 0,1 范围内的值,即所有像素值应位于 [0,1] 之间(我也已验证这一点)。 我想可视化模型的一些输出。因此,我创建了一个简单的方法:-

    for img, label in dataloader:
        img.squeeze_(0)
        # permute the channels. cv2 expects image in format (h, w, c)
        unscaled_img = img.permute(1, 2, 0)
        # move images to cpu and convert to numpy as required by cv2 library
        unscaled_img = torch.round(unscaled_img * 255)
        unscaled_img = unscaled_img.to(torch.uint8)
        # unscaled_img = np.rint(unscaled_img * 255).astype(np.uint8) 
        unscaled_img = cv2.cvtColor(unscaled_img, cv2.COLOR_RGB2BGR)
        cv2.imshow(unscaled_img.numpy())

但是,所有创建的图像都有异常的蓝色阴影。例如,

有人可以告诉我我到底做错了什么吗?非常感谢您的帮助

通过@LajosArpad 评论解决。罪魁祸首是

unscaled_img = cv2.cvtColor(unscaled_img, cv2.COLOR_RGB2BGR)

删除它会产生正确的值。