Javaで画像を分類・タグ付けするアプリを作成する方法【機械学習・UI対応】

画像整理やコンテンツ管理の効率化のため、画像を自動で分類・タグ付けするアプリは非常に有用です。本記事では、Javaを使って以下のような機能を持つ簡易アプリを作成します。

  • フォルダ内の画像を読み込み
  • AIモデルによる画像分類・タグ付け
  • 分類結果をGUIで表示
  • 結果をCSVに保存

1. 使用ライブラリと前提環境

以下の環境を使用します

  • Java 17以上
  • JavaFX(GUI構築用)
  • DeepLearning4J(画像分類用)
  • OpenCV(画像前処理)
  • Maven(ビルド管理)

pom.xml(主要依存)

<dependencies>
  <dependency>
    <groupId>org.deeplearning4j</groupId>
    <artifactId>deeplearning4j-core</artifactId>
    <version>1.0.0</version>
  </dependency>
  <dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>opencv</artifactId>
    <version>4.5.5-1.5.7</version>
  </dependency>
  <dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>17</version>
  </dependency>
</dependencies>

2. 画像を読み込む処理

public List<File> loadImages(String folderPath) {
    File dir = new File(folderPath);
    return Arrays.stream(dir.listFiles((d, name) -> name.endsWith(".jpg") || name.endsWith(".png")))
                .collect(Collectors.toList());
}

3. AIモデルで分類(例:事前学習済みモデルを使用)

事前に学習したKerasまたはONNX形式のモデルをDL4Jで読み込みます。

ComputationGraph model = KerasModelImport.importKerasModelAndWeights("model.h5");
INDArray image = preprocessImage("image.jpg");
INDArray output = model.outputSingle(image);
String label = decodeLabel(output);

4. JavaFXによるUI構築(表示+分類ボタン)

public class ImageClassifierApp extends Application {
    @Override
    public void start(Stage stage) {
        Button classifyBtn = new Button("分類実行");
        ImageView imageView = new ImageView();
        Label resultLabel = new Label();

        classifyBtn.setOnAction(e -> {
            String path = "sample.jpg";
            imageView.setImage(new Image(new FileInputStream(path)));
            String label = classifyImage(path);
            resultLabel.setText("分類結果: " + label);
        });

        VBox root = new VBox(10, imageView, classifyBtn, resultLabel);
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.setTitle("画像分類アプリ");
        stage.show();
    }
}

5. 分類結果のCSV出力

try (BufferedWriter writer = new BufferedWriter(new FileWriter("result.csv", true))) {
    writer.write(fileName + "," + label);
    writer.newLine();
}

6. 応用アイデア

  • タグ別にフォルダへ自動仕分け
  • 学習済みモデルを更新して精度アップ
  • ユーザーがタグを修正して再学習

まとめ

Javaだけでも、機械学習とUIを組み合わせて強力な画像分類アプリを構築できます。Pythonのようなライブラリに頼らず、Javaエコシステム内で完結するソリューションは、企業内業務や組織内のデータ処理にも適しています。

タイトルとURLをコピーしました