Msy20070905 2024-07-18 12:20 采纳率: 21.2%
浏览 2
已结题

No such file or directory: 'Image'


import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import os
np.set_printoptions(threshold = np.inf)
# 自制训练集(jpg,txt)
def generated(path,txt):
    f = open(txt,'r')
    contents = f.readlines()
    f.close()
    x,y_ = [],[]
    for content in contents:
        value = content.split()
        img_path = path = value[0]
        img = Image.open(img_path)
        img = np.array(img.convert('L'))
        img = img/255.
        x.append(img)
        y_.append(value[1])
        print('loading :'+content)

    x=np.array(x)
    y_ = np.array(y_)
    y_ = y_.astype(np.int64)
    return x,y_

# 定义数据路径
train_path = './dataset/Original Images/dataset_train_jpg/'
train_txt = './dataset/Groundtruths/dataset_train_jpg.txt'
x_train_savepath = './dataset/dataset_x_train.npy'
y_train_savepath = './dataset/dataset_y_train.npy'

test_path = './dataset/Original Images/dataset_test_jpg/'
test_txt = './dataset/Groundtruths/dataset_test_jpg.txt'
x_test_savepath = './dataset/dataset_x_test.npy'
y_test_savepath = './dataset/dataset_y_test.npy'

if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath) and os.path.exists(x_test_savepath) and os.path.exists(y_test_savepath):
    print('Load Datasets')
    x_train_save = np.load(x_train_savepath)
    y_train = np.load(y_train_savepath)
    x_test_save = np.load(x_test_savepath)
    y_test = np.load(x_test_savepath)
    x_train = np.reshape(x_train_save,(len(x_train_save),4288,2848))
    x_test = np.reshape(x_test_save, (len(x_test_save), 4288, 2848))
else:
    print('Generate Datasets')
    x_train, y_train = generated(train_path, train_txt)
    x_test, y_test = generated(test_path, test_txt)

    print('save Datasets')
    x_train_save = np.reshape(x_train, (len(x_train),-1))
    x_test_save = np.reshape(x_test, (len(x_test), -1))
    np.save(x_train_savepath, x_train_save)
    np.save(x_train_savepath, y_train)
    np.save(x_test_savepath, x_test_save)
    np.save(y_test_savepath,y_test)

# 神经网搭建
model = tf.keras.models.Sequential(
    # 第一层卷积
    tf.keras.layers.Con2D(filter=96, kernel_size=(3,3),padding='valid'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Con2D(filter=128, kernel_size=(3,3),padding='valid'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Conv2D(filter=256, kernel_size=(3,3),padding='same'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Activation('sigmoid'),
    tf.keras.layers.AveragePooling2D(pool_size=(5,5),padding='valid'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(256,activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(96,activation='relu'),
    tf.keras.layers.Dense(20,activation='relu'),
    tf.keras.layers.Dense(5,activation='softmax')
)

model.compile(optimizer='nadam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),metrics=['sparse_categorical_accuracy'])

checkpoint_save_path = './checkpoint.ckpt'
if os.path.exists(checkpoint_save_path+'index'):
    print('load the model')
    model.load_weights(checkpoint_save_path)

cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath = checkpoint_save_path,save_weights_only=True,save_best_only=True)
history = model.fit(x_train,y_train, batch_size=32,epochs=10000, validation_data=(x_test,y_test), validation_freq=1,callbacks=[cp_callback])
model.summary()

print(model.trainable_variables)
file = open('./numtext.txt','w')
for v in model.trainable_variables:
    file.write(str(v.name)+'\n')
    file.write(str(v.shape)+'\n')
    file.write(str(v.numpy())+'\n')
file.close()

acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label="Validation Accuracy")
plt.title('Training and Validation Accuracy')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label="Validation Loss")
plt.title('Training and Validation Loss')
plt.legend()

plt.show()

这段代码,报[Errno 2] No such file or directory: 'Image',怎么处理啊

  • 写回答

4条回答 默认 最新

  • 关注

    中午好🌞🌞🌞
    本答案参考ChatGPT-3.5

    The error message "No such file or directory: 'Image'" suggests that you're trying to load an image using TensorFlow, but the file doesn't exist. This could be due to a number of reasons, including the incorrect file path, the file not being in the expected location, or the image file not being saved in the correct format.

    Here's some sample code to help you locate and fix the issue:

    # Find the file path
    image_file_path = 'dataset/image.jpg'
    # Check if the file exists
    if os.path.isfile(image_file_path):
        # Load the image
        img = Image.open(image_file_path)
        
        # Convert the image from JPEG format to PNG format
        img = img.convert('RGB').convert('PNG')
    else:
        print(f"The file {image_file_path} does not exist.")
    

    In this example, we first find the file path of the image we want to use. If the file exists, we then try to load it using Image.open() function. We convert the image from JPEG format to PNG format using img.convert() method before saving it back to the same format. If the file doesn't exist, we print an error message indicating so.

    If the code still returns errors after trying these steps, it may indicate that there are other issues with your training data, such as missing files or invalid images. In this case, you may need to gather more information about your dataset and the specific steps you took to generate it, and adjust the code accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 7月26日
  • 已采纳回答 7月18日
  • 创建了问题 7月18日

悬赏问题

  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 在虚拟机环境下完成以下,要求截图!
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见