在tensorflow的images案例中,
LICENSE.txt文件如下图:
利用LICENSE.txt文件生成字典代码如下:
attributions = (data_root/“LICENSE.txt”).open(encoding=‘utf-8’).readlines()[4:]
attributions = [line.split(’ CC-BY’) for line in attributions]
attributions = dict(attributions)
这样字典内容如下:
attributions[“sunflowers/5923085671_f81dd1cf6f.jpg”]
Out[31]: ’ by Svetoslav Nikolov - https://www.flickr.com/photos/svenikolov/5923085671/\n’
windows读取文件路径的反斜杠不同。
import random
all_image_paths = list(data_root.glob(’/’))
all_image_paths = [str(path) for path in all_image_paths]
image_path = random.choice(all_image_paths)
image_path
Out[28]: 'C:\Users\zephyr_wang\.keras\datasets\flower_photos\sunflowers\5923085671_f81dd1cf6f.jpg’
image_rel = pathlib.Path(image_path).relative_to(data_root)
image_rel
Out[27]: WindowsPath(‘sunflowers/5923085671_f81dd1cf6f.jpg’)
转成字符串后,反斜杠不同
str(image_rel)
Out[38]: ‘sunflowers\5923085671_f81dd1cf6f.jpg’
故与字典不匹配,attributions[str(image_rel)]报错。