TypeError:div():参数'other'(位置1)必须为Tensor,而不是numpy.bool_

时间:2019-12-28 18:38:33

标签: python numpy tensorflow tensor

我正在尝试在医学图像上建立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上尝试代码。

1 个答案:

答案 0 :(得分:0)

在初始化掩码后添加此行。

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

方法torch.from_numpy期望类型为floatnp.float的对象,因为割炬中的每个张量都是torch.FloatTensor
有几种解决方法。一种方法是使用np.arraydtype='float'将布尔数组转换为浮点型

声明一个空的torch.BoolTensor,然后使用方法from_numpy

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