pandas TypeError:无法将对象转换为“filename”的“str”

wixjitnu  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(395)

我想创建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'

m3eecexj

m3eecexj1#

如果你得到了这个错误,请确保传递给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()方法创建的嵌套框列上的循环。当Map中不存在键时,它返回一个NaN(例如,参见this 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

相关问题