字符串键的字典问题

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

我目前正在开展一个项目,使用 CNN 网络实现图像字幕问题。问题是,每当我尝试将图像名称作为字典的键传递,并将图像特征作为值时,它都会传递索引错误。

def load_features(photos):
    all_features = load(open('features.p', 'rb'))
    features={k:all_features[k] for k in photos}
    return features

在这里,features.p 是一个包含所有图像特征的 pickle 文件,而 photos 是一个包含所有图像名称的加载文本文件。图像名称是字母和数字值的组合,扩展名为 .jpg。我该如何解决这个问题?

python dictionary data-structures
1个回答
0
投票

尝试这样

从pickle导入加载

def load_features(photos):
    try:
        all_features = load(open('features.p', 'rb'))
    except FileNotFoundError:
        print("Error: 'features.p' file not found.")
        return None

    features = {}

    with open(photos, 'r') as f:
        for photo in f:
            photo = photo.strip()  # Remove leading/trailing whitespaces or newline characters
            if photo in all_features:
                features[photo] = all_features[photo]
            else:
                print(f"Warning: Image {photo} not found in 'features.p'")

    return features

# Example usage
photos_file = 'list_of_photos.txt'  # Replace with your actual file path
loaded_features = load_features(photos_file)

if loaded_features is not None:
    # Continue with your code using loaded_features
    print(loaded_features)
© www.soinside.com 2019 - 2024. All rights reserved.