首页 > 解决方案 > openCv 和 PyTorch 逆变器转换不起作用

问题描述

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

        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())

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

出现很多蓝色阴影

有人可以告诉我我到底在做什么错吗?您的帮助将不胜感激

标签: numpypytorchopencv-python

解决方案


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

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

删除它会产生正确的值。


推荐阅读