首页 > 解决方案 > 无法从 CSV 文件中读取文件名并在另一个文件夹中找到它

问题描述

我需要遍历包含以下结构的 CSV 文件的条目:

图像文件 | 班级


img1.png |

img2.png |

...

第一列包含文件名,另一列Class为空。所有这些文件都保存在路径PATH中的文件夹中。我需要

我已经设法对图像进行预测,但我无法对 CSV 文件中提到的给定文件做同样的事情。我应该如何进行?

这是用于重现问题的笔记本的链接:LINK

PS:我的代码可能存在不止 1 个问题。

标签: pythonpython-3.xcsvgoogle-colaboratory

解决方案


我给了它一些时间并且做对了:

遍历 CSV 文件中的每个文件名

import pandas as pd dff = pd.read_csv(path, index_col="Column_with_all_filenames")

从位置 PATH 访问文件

for img_name, Class in dff.iterrows(): if(".png" in img_name): #Check is the name is that of a PNG file if(find(img_name, path) ): #Check if the file was found in the path im=test_img_dir+'/'+img_name #Modify the path of the print(im) im = image.imread(im) #Make Predictions

将预测的类保存到图像行中的另一列

      #Create a list of the [filename--Prediction]
      listof_rows.append([file_name, prediction])

      #After all the files have been processed...
      df=pd.DataFrame(listof_rows, columns=['Image_File', 'Class'])
      df.to_csv('Result1.csv', index=False)

推荐阅读