TypeError: div(): argument 'other' (position 1) must be Tensor, not numpy.bool_

TypeError: div(): argument 'other' (position 1) must be Tensor, not numpy.bool_

我正在尝试在医学图像上使用 ODE-Net 模型来获得一些分割结果。 在进行实验时出现此错误: TypeError: div(): argument 'other' (position 1) must be Tensor, not numpy.bool_ 错误指示到代码以下部分的最后一行

def apply_data_augmentation(self, image, mask): patch = torch.from_numpy(image.transpose(2, 0, 1)).float() / 255 n_glands = mask.max() label = torch.from_numpy(mask).float() / n_glands

mask 是图像的基本事实。

以上部分前面是:

def __getitem__(self, index):
    image, mask = self.index_to_filename(index)
    image, mask = self.open_and_resize(image, mask)
    image, mask = self.pad_image(image, mask)
    label, patch = self.apply_data_augmentation(image, mask)
    label = self.create_eroded_mask(label, mask)
    patch, label = self.extract_random_region(image, patch, label)
    return patch, label.float()

def index_to_filename(self, index):
    """Helper function to retrieve filenames from index"""
    index_img = index // self.repeat
    index_img = self.images[index_img]
    index_str = str(index_img.item() + 1)

    image = self.image_fname + index_str + '.jpg'
    mask = self.image_fname + index_str + '_anno.png'
    return image, mask

def open_and_resize(self, image, mask):
    """Helper function to pad smaller image to the correct size"""
    image = PIL.Image.open(image)
    mask = PIL.Image.open(mask)

    ratio = (775 / 512)
    new_size = (int(round(image.size[0] / ratio)),
                int(round(image.size[1] / ratio)))

    image = image.resize(new_size)
    mask = mask.resize(new_size)

    image = np.array(image)
    mask = np.array(mask)
    return image, mask

def pad_image(self, image, mask):
    """Helper function to pad smaller image to the correct size"""
    if not self.validation:
        pad_h = max(self.patch_size[0] - image.shape[0], 128)
        pad_w = max(self.patch_size[1] - image.shape[1], 128)
    else:
        # we pad more than needed to later do translation augmentation
        pad_h = max((self.patch_size[0] - image.shape[0]) // 2 + 1, 0)
        pad_w = max((self.patch_size[1] - image.shape[1]) // 2 + 1, 0)

    padded_image = np.pad(image, ((pad_h, pad_h), (pad_w, pad_w), (0, 0)), mode='reflect')
    mask = np.pad(mask, ((pad_h, pad_h), (pad_w, pad_w)), mode='reflect')
    return padded_image, mask

在这方面的任何帮助将不胜感激;提前致谢!

PS:我正在 Google Colab 上尝试代码。

初始化掩码后添加此行。

mask = np.array(mask, dtype='float')

方法 torch.from_numpy 需要 floatnp.float 类型的对象,因为 torch 中的每个张量都是 torch.FloatTensor
有几种方法可以解决这个问题。一种方法是使用 np.arraydtype='float'

声明一个空的 torch.BoolTensor 然后使用方法 from_numpy 将布尔数组转换为浮点数.

PS
np.array 为加载的图像选择合适的数据类型。对于 bool 张图片,它是 np.bool.