类型错误:无法将“文件名”的对象转换为“str”

问题描述 投票:0回答:1

我想创建

imgs
变量来加载“./input/hubmap-organ-segmentation/train_images/”文件夹中的所有图像。我的代码引发了
TypeError: Can't convert object to 'str' for 'filename'
错误。

import os
import glob
import pandas as pd
import cv2

BASE_PATH = "./input/hubmap-organ-segmentation/"
df = pd.read_csv(os.path.join(BASE_PATH, "train.csv"))
    
all_image_files = glob.glob(os.path.join(BASE_PATH, "train_images", "**", "*.tiff"), recursive=True)
train_img_map = {int(x[:-5].rsplit("/", 1)[-1]):x for x in all_image_files}
df.insert(3, "img_path", image_ids.map(train_img_map))

imgs = [cv2.imread(img_path)[..., ::-1] for img_path in df.img_path.values]

追溯:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [132], in <cell line: 38>()
     37 ftu_crop_map = {}
     38 for _organ in ORGANS:
     39     #sub_df = df[df.organ==_organ].sample(N_EX)
---> 40     imgs = [cv2.imread(img_path)[..., ::-1] for img_path in df.img_path.values]

Input In [132], in <listcomp>(.0)
     37 ftu_crop_map = {}
     38 for _organ in ORGANS:
     39     #sub_df = df[df.organ==_organ].sample(N_EX)
---> 40     imgs = [cv2.imread(img_path)[..., ::-1] for img_path in df.img_path.values]

TypeError: Can't convert object to 'str' for 'filename'

img_path
的示例:

df.img_path[0]
'./input/hubmap-organ-segmentation/train_images/10044.tiff'
python pandas opencv file-io typeerror
1个回答
0
投票

如果出现此错误,请确保传递给

cv2.imread()
的值是一个字符串(即文件路径)。例如,传递列表会引发此错误:

cv2.imread(['img1.png', 'img2.png'])  # <--- TypeError: Can't convert object to 'str' for 'filename'

在这种情况下,由于需要逐个读取每个文件,为了解决这个特定问题,请使用列表理解:

imgs = [cv2.imread(img) for img in ['img1.png', 'img2.png']]  # <--- OK

在OP中的情况下,NaN被传递给它,这导致了错误。

cv2.imread(float('nan'))  # <--- TypeError: Can't convert object to 'str' for 'filename'

这是因为调用

imread()
的列表理解是对使用
Series.map()
方法创建的数据框列的循环。当映射中不存在键时,它返回 NaN(例如参见此 Q/A),因此包含图像文件路径的数据帧列中很可能存在一些 NaN 值。

一个例子:

df = pd.DataFrame({'img_path': ['img1.png', np.nan]})      # <--- has non-string value
[cv2.imread(img_path) for img_path in df['img_path']]      # <--- TypeError:


df = pd.DataFrame({'img_path': ['img1.png', 'img2.png']})  # <--- all strings
[cv2.imread(img_path) for img_path in df['img_path']]      # <--- OK
© www.soinside.com 2019 - 2024. All rights reserved.