为什么我的图片没有保存?使用 TensorFlow Keras.preprocessing.image.directoryIterator

问题描述

我对使用 tensorflow 和 CNN 非常陌生。我正在尝试加载我的图像数据集并调整每个图像的大小和灰度。我正在阅读有关 TensorFlow Keras.preprocessing.image.directoryIterator 的文档。我试过了(下面的代码),它找到了我的所有图像,但实际上并没有保存它们或对图像进行任何修改?难道我做错了什么?我自己有这个代码,所以我不确定我是否需要设置其他任何东西来完成这项工作。任何帮助表示赞赏!不幸的是,互联网上没有太多文档或帮助:(

注意:我已经排除了包含图像的本地文件路径 - 但我的代码中确实有一个合法的路径。另外,save_to_dir 参数,我不确定它是目录名还是完整的文件路径,但我已经尝试了两种方法,但都不起作用。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class User {
    private String username;

    public User(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }
}

public class Main {
    public static void main(String[] args) {
        // Test
        List<User> users = List.of(new User("Will.Smith3"),new User("Ragnar.Lothbrok74"),new User("Anakin.Skywalker30"),new User("Cristiano.Ronaldo32"),new User("Lionel.Messi2"));
        try {
            addUsers(5,users);
        } catch (IOException e) {
            e.printstacktrace();
        }
    }

    static void addUsers(int maxLines,List<User> users) throws IOException {
        // List to store lines from the file plus corresponding username
        List<String> list = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(new File("Users.txt")))) {
            String currentLine;
            int line = 0;
            while ((currentLine = reader.readLine()) != null && line < users.size()) {
                list.add(line,currentLine + " > " + users.get(line).getUsername() + System.lineseparator());
                line++;
            }
        }

        // Write the content of the list into the file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("Users.txt")))) {
            for (String s : list) {
                writer.write(s);
            }
        }
    }
}

解决方法

您需要触发您创建的生成器迭代器。

下面是将文件保存在所需目录中的代码。

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator 

image_data_generator = ImageDataGenerator() 

image = tf.keras.preprocessing.image.DirectoryIterator(
'/content/Images/',image_data_generator,target_size=(170,170),color_mode ='grayscale',classes =['Face','NonFace'],class_mode ="categorical",batch_size=5,shuffle=True,seed=None,data_format ='channels_first',save_to_dir = '/content/Test/',save_prefix='Test_',save_format ='jpg',follow_links=False,subset=None,interpolation='nearest',dtype=None)

image.next() # This line will trigger the execution of Iterator.