首页 > 解决方案 > 将 for 循环的索引集成到循环内函数的路径中

问题描述

我想预测图像是否是技术图纸。我在 python 中创建了一个带有 keras 的 CNN,它可以很好地用于单张图片预测。现在我想每次运行预测不止一张图片。所以我想创建一个循环来解决这个问题。我似乎在这里错过的一点是我如何将循环的索引实现为路径。因此,每次循环都会选择并预测文件夹中的下一张图像(命名为 1-47)。我认为用索引替换文件名就足够了,但索引变量似乎无法访问路径本身?

这是我的循环:

# Part 3 - Making new predictions
import numpy as np
from keras.preprocessing import image
prediction=list(range(50)) #Create an empty list of 50 entrys
for  i in enumerate(47,start=1): 
    test_image = image.load_img('C:/Users/Anwender/Documents/Uni/KI/Predict/i.jpg', target_size = (64, 64),color_mode = 'grayscale') #Defines your single image you want to predict. This image has to be unseen by the network before. So it is necessary to withdraw those files from the whole data set before running the code. 
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    result = classifier.predict(test_image)
    training_set.class_indices
    if result[0][0] == 1:
        prediction[i] = 'Tech. draw.'
    else:
        prediction[i] = 'No tech. draw.'

print(prediction)

标签: pythonnumpyfor-loopkeras

解决方案


如果您的文件名为1.jpg, 2.jpg...,您应该更改正在阅读的文件的名称。现在它正在读取文件i.jpg

import numpy as np
from keras.preprocessing import image
prediction=list(range(50)) #Create an empty list of 50 entrys
for  i in enumerate(47,start=1): 
    ## here, replace your `i.jpg` by the current value of i
    test_image = image.load_img('C:/Users/Anwender/Documents/Uni/KI/Predict/'+str(i)+'.jpg', target_size = (64, 64),color_mode = 'grayscale') #Defines your single image you want to predict. This image has to be unseen by the network before. So it is necessary to withdraw those files from the whole data set before running the code. 
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    result = classifier.predict(test_image)
    training_set.class_indices
    if result[0][0] == 1:
        prediction[i] = 'Tech. draw.'
    else:
        prediction[i] = 'No tech. draw.'

print(prediction)

推荐阅读