Can't convert np.ndarray of type numpy.bool_

I am wondering why I am getting this error when I start to train the model while I used this model before to train another dataset.

mask = torch.from_numpy(np.array(mask))
TypeError: can't convert np.ndarray of type numpy.bool_. The only supported types are: double, float, float16, int64, int32, and uint8.

The error is about how mask defined in a customised dataset but I don’t have a clue how can I fix that.

this is how customised dataset created.

import torch
from import Dataset  # For custom data-sets
import torchvision.transforms as transforms
from PIL import Image
import numpy as np
class CustomDataset(Dataset):
    def __init__(self, image_paths, target_paths):   # initial logic happens like transform

        self.image_paths = image_paths
        self.target_paths = target_paths
        self.transforms = transforms.ToTensor()
        self.mapping = {
            0: 0,
            255: 1
#            85: 0,
#            170: 1,
#            255: 2               
    def mask_to_class(self, mask):
        for k in self.mapping:
            mask[mask==k] = self.mapping[k]
        return mask
    def __getitem__(self, index):

        image =[index])
        mask =[index])
        t_image = self.transforms(image)
        mask = torch.from_numpy(np.array(mask))
        mask = self.mask_to_class(mask)
        mask = mask.long()
        return t_image, mask

    def __len__(self):  # return count of sample we have

        return len(self.image_paths)

also, one example of my mask is attached.
mask value is 0-255 and it’s uint8

1 Like

Apparently this image is saved in as bool values, since when you check the dtype of the numpy array, you’ll get dtype('bool').
An easy fix is to convert it to np.uint8 after loading:

mask = torch.from_numpy(np.array(mask, dtype=np.uint8))

Yes it work. Thanks a lot