Can't convert object of type 'numpy.float64' to 'str' for 'filename'

Hello, have a nice day!!

When to try implement the code;

def has_mask(mask_path):
img = cv2.imread(mask_path, 0)
thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)[1]
if np.mean(thresh) > 0.0:
return True
else:
return False

def get_dataloader(rank, world_size):
“”“Creates the data loaders.”""
train_df = dataset.create_df(config.train_dir)
valid_df = dataset.generate_df(config.valid_dir)

# determine if an image contains mask or not
building_label_paths = train_df['building_label_path'].values.tolist()
train_has_masks = list(map(dataset.has_mask, building_label_paths))
train_df['has_mask'] = train_has_masks

def getitem(self, index):
example = {}
df_row = self.dataset.iloc[index]
image_1 = cv2.imread(df_row[‘image_1_path’], 0) / 255.0
image_2 = cv2.imread(df_row[‘image_2_path’], 0) / 255.0
rgb_image = s1_to_rgb(image_1, image_2)

if self.split == 'test':
    # no building mask should be available
    example['image'] = rgb_image.transpose((2,0,1)).astype('float32')
else:
    # load ground truth building mask
    building_mask = cv2.imread(df_row['building_label_path'], 0) / 255.0

    # compute transformations or apply augmentations if specified 
    if self.transform:
        augmented = self.transform(image=rgb_image, mask=building_mask)
        rgb_image = augmented['image']
        building_mask = augmented['mask']

    example['image'] = rgb_image.transpose((2,0,1)).astype('float32')
    example['mask'] = building_mask.astype('int64')

return example

After completing one epoch, I got these errors

Traceback (most recent call last):
File “train.py”, line 240, in
mp.spawn(train, args=(config.num_epochs, WORLD_SIZE), nprocs=WORLD_SIZE, join=True)
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 199, in spawn
return start_processes(fn, args, nprocs, join, daemon, start_method=‘spawn’)
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 157, in start_processes
while not context.join():
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 118, in join
raise Exception(msg)
Exception:

– Process 0 terminated with the following error:
Traceback (most recent call last):
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 19, in _wrap
fn(i, *args)
File “F:\Projects\FD\1\train.py”, line 212, in train
for batch in tqdm(val_loader, leave=False):
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\tqdm\std.py”, line 1180, in iter
for obj in iterable:
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data\dataloader.py”, line 435, in next
data = self._next_data()
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data\dataloader.py”, line 1085, in _next_data
return self._process_data(data)
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data\dataloader.py”, line 1111, in _process_data
data.reraise()
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch_utils.py”, line 428, in reraise
raise self.exc_type(msg)
TypeError: Caught TypeError in DataLoader worker process 0.
Original Traceback (most recent call last):
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data_utils\worker.py”, line 198, in _worker_loop
data = fetcher.fetch(index)
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data_utils\fetch.py”, line 44, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data_utils\fetch.py”, line 44, in
data = [self.dataset[idx] for idx in possibly_batched_index]
File “F:\Projects\FD\1\etciDataset.py”, line 39, in getitem
building_mask = cv2.imread(df_row[‘building_label_path’], 0) / 255.0
TypeError: Can’t convert object of type ‘numpy.float64’ to ‘str’ for ‘filename’


Thanks for the help!

Based on the error message df_row['building_label_path'], 0) is a np.float64 while cv2.imread expects a str as seen here:

cv2.imread(np.float64(2.))
> TypeError: Can't convert object of type 'numpy.float64' to 'str' for 'filename'

cv2.imread(str(np.float64(2.))) # works but returns None as it's an invalid file name

Make sure to pass a valid path as a string to imread.

Thanks very much for reply, could you give me an example I tried many times but doesn’t work.

Thanks very much for reply, could you give me an example I tried many times but doesn’t work.

An example would be to pass a valid image path as a string:

img = cv2.imread('/tmp/image.jpeg')

Right now df_row['building_label_path'] is an np.float64 value, which is a floating point value and not a path string so you would check your df_row content and make sure to index the right column/row.

1 Like

I passed a valid path as a string to cv2.imread and works well, thank you very much.