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

tamersaleh: <p>Hello, have a nice day!!</p>
<h1>
<a name="when-to-try-implement-the-code-1" class="anchor" href="#when-to-try-implement-the-code-1"></a>When to try implement the code;</h1>
<p>def has_mask(mask_path):<br>
img = cv2.imread(mask_path, 0)<br>
thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)[1]<br>
if np.mean(thresh) &gt; 0.0:<br>
return True<br>
else:<br>
return False</p>
<p>def get_dataloader(rank, world_size):<br>
“”“Creates the data loaders.”""<br>
train_df = dataset.create_df(config.train_dir)<br>
valid_df = dataset.generate_df(config.valid_dir)</p>
<pre><code># 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
</code></pre>
<p>def <strong>getitem</strong>(self, index):<br>
example = {}<br>
df_row = self.dataset.iloc[index]<br>
image_1 = cv2.imread(df_row[‘image_1_path’], 0) / 255.0<br>
image_2 = cv2.imread(df_row[‘image_2_path’], 0) / 255.0<br>
rgb_image = s1_to_rgb(image_1, image_2)</p>
<pre><code>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
</code></pre>
<hr>
<p>After completing one epoch, I got these errors</p>
<p>Traceback (most recent call last):<br>
File “train.py”, line 240, in <br>
mp.spawn(train, args=(config.num_epochs, WORLD_SIZE), nprocs=WORLD_SIZE, join=True)<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 199, in spawn<br>
return start_processes(fn, args, nprocs, join, daemon, start_method=‘spawn’)<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 157, in start_processes<br>
while not context.join():<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 118, in join<br>
raise Exception(msg)<br>
Exception:</p>
<p>– Process 0 terminated with the following error:<br>
Traceback (most recent call last):<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\multiprocessing\spawn.py”, line 19, in _wrap<br>
fn(i, *args)<br>
File “F:\Projects\FD\1\train.py”, line 212, in train<br>
for batch in tqdm(val_loader, leave=False):<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\tqdm\std.py”, line 1180, in <strong>iter</strong><br>
for obj in iterable:<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data\dataloader.py”, line 435, in <strong>next</strong><br>
data = self._next_data()<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data\dataloader.py”, line 1085, in _next_data<br>
return self._process_data(data)<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data\dataloader.py”, line 1111, in _process_data<br>
data.reraise()<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch_utils.py”, line 428, in reraise<br>
raise self.exc_type(msg)<br>
TypeError: Caught TypeError in DataLoader worker process 0.<br>
Original Traceback (most recent call last):<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data_utils\worker.py”, line 198, in _worker_loop<br>
data = fetcher.fetch(index)<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data_utils\fetch.py”, line 44, in fetch<br>
data = [self.dataset[idx] for idx in possibly_batched_index]<br>
File “C:\ProgramData\Anaconda3\envs\torch171\lib\site-packages\torch\utils\data_utils\fetch.py”, line 44, in <br>
data = [self.dataset[idx] for idx in possibly_batched_index]<br>
File “F:\Projects\FD\1\etciDataset.py”, line 39, in <strong>getitem</strong><br>
building_mask = cv2.imread(df_row[‘building_label_path’], 0) / 255.0<br>
TypeError: Can’t convert object of type ‘numpy.float64’ to ‘str’ for ‘filename’</p>
<hr>
<p>Thanks for the help!</p>

ptrblck: <p>Based on the error message <code>df_row['building_label_path'], 0)</code> is a <code>np.float64</code> while <code>cv2.imread</code> expects a <code>str</code> as seen here:</p>
<pre><code class="lang-python">cv2.imread(np.float64(2.))
&gt; 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
</code></pre>
<p>Make sure to pass a valid path as a string to <code>imread</code>.</p>

tamersaleh: <p>Thanks very much for reply, could you give me an example I tried many times but doesn’t work.</p>

tamersaleh: <p>Thanks very much for reply, could you give me an example I tried many times but doesn’t work.</p>

ptrblck: <p>An example would be to pass a valid image path as a string:</p>
<pre><code class="lang-python">img = cv2.imread('/tmp/image.jpeg')
</code></pre>
<p>Right now <code>df_row['building_label_path']</code> is an <code>np.float64</code> value, which is a floating point value and not a path string so you would check your <code>df_row</code> content and make sure to index the right column/row.</p>

tamersaleh: <aside class="quote no-group" data-username="ptrblck" data-post="2" data-topic="139850">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>pass a valid path as a string to <code>imread</code></p>
</blockquote>
</aside>
<p>I passed a valid path as a string to cv2.imread and works well, thank you very much.</p>