メインコンテンツへスキップ

世界の名所を画像認識で識別


    はじめに

    初心者が世界の名所を画像認識で識別するアプリを製作しました。
    旅好きでいろいろな国の名所を見てきたため、画像認識のアプリを製作するならそれに関することをやってみたいと思いとりくみました。

    完成したアプリケーション

    今回はとりあえず、「マチュピチュ」「ウユニ塩湖」「アンコールワット」の三か所のみの画像認識をできるように作成しています。(もっと増やしていきたいですが。。。)

    https://flask-place-app.onrender.com/    

    実行環境

    ・Visual Studio Code
    ・Google Colaboratory

    画像収集

    目的の画像を収集。
    GoogleDrive上に画像を保管するため、ドライブをマウントします。
    以下のコードを実行してマウントします。

    from google.colab import drive
    drive.mount('/content/drive')

    どのように画像を収集するか悩みましたが、最終的に「scraiping」で画像を収集することにしました。
    参考文献:Python2年生 スクレイピングのしくみ(書籍)

    参考になった動画:以下のurlの動画がスクレイピングの参考になりました。初心者でもWebから大量画像を収集する方法をわかりやすく解説されているます。(YouTube動画)
    https://www.youtube.com/watch?v=hRB104ik6pQ

    # 必要な機能のインストール
    !pip install icrawler
    
    # 必要な機能の読込
    from icrawler.builtin import BingImageCrawler
    
    # 画像のダウンロード
    crawler = BingImageCrawler(storage={'root_dir': 'drive/MyDrive/Aidemy/world_data/machupichu'})
    crawler.crawl(keyword='マチュピチュ', max_num=30)
    
    crawler = BingImageCrawler(storage={'root_dir': 'drive/MyDrive/Aidemy/world_data/uyuni'})
    crawler.crawl(keyword='ウユニ塩湖', max_num=30)
    
    crawler = BingImageCrawler(storage={'root_dir': 'drive/MyDrive/Aidemy/world_data/Angkor'})
    crawler.crawl(keyword='アンコールワット', max_num=30)
    

    まずは確認のためそれぞれ10枚ずつでやってみて、画像がダウンロードできることを確認しました。その後30枚ずつに増やしてみましたがしっかり保存されていました。


    モデルの作成

    import os
    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    from tensorflow.keras.utils import to_categorical
    from tensorflow.keras.layers import Dense, Dropout, Flatten, Input
    from tensorflow.keras.applications.vgg16 import VGG16
    from tensorflow.keras.models import Model, Sequential
    from tensorflow.keras import optimizers
    
    
    
    path_machupichu = os.listdir('/content/drive/MyDrive/Aidemy/world_data/machupichu/')
    path_uyuni = os.listdir('/content/drive/MyDrive/Aidemy/world_data/uyuni/')
    path_Angkor = os.listdir('/content/drive/MyDrive/Aidemy/world_data/Angkor/')
    
    img_machupichu = []
    img_uyuni = []
    img_Angkor = []
    
    for i in range(len(path_machupichu)):
        img = cv2.imread('/content/drive/MyDrive/Aidemy/world_data/machupichu/' + path_machupichu[i])
        b,g,r = cv2.split(img)
        img = cv2.merge([r,g,b])
        img = cv2.resize(img, (50,50))
        img_machupichu.append(img)
    
    for i in range(len(path_uyuni)):
        img = cv2.imread('/content/drive/MyDrive/Aidemy/world_data/uyuni/' + path_uyuni[i])
        b,g,r = cv2.split(img)
        img = cv2.merge([r,g,b])
        img = cv2.resize(img, (50,50))
        img_uyuni.append(img)
    
    for i in range(len(path_Angkor)):
        img = cv2.imread('/content/drive/MyDrive/Aidemy/world_data/Angkor/' + path_Angkor[i])
        b,g,r = cv2.split(img)
        img = cv2.merge([r,g,b])
        img = cv2.resize(img, (50,50))
        img_Angkor.append(img)
    
    X = np.array(img_machupichu + img_uyuni + img_Angkor)
    y =  np.array([0]*len(img_machupichu) + [1]*len(img_uyuni) + [2]*len(img_Angkor))
    
    rand_index = np.random.permutation(np.arange(len(X)))
    X = X[rand_index]
    y = y[rand_index]
    
    # データの分割
    X_train = X[:int(len(X)*0.8)]
    y_train = y[:int(len(y)*0.8)]
    X_test = X[int(len(X)*0.8):]
    y_test = y[int(len(y)*0.8):]
    
    # 正解ラベルをone-hotの形にします
    y_train = to_categorical(y_train)
    y_test = to_categorical(y_test)
    
    # モデルにvggを使います
    input_tensor = Input(shape=(50, 50, 3))
    vgg16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)
    
    # vggのoutputを受け取り、3クラス分類する層を定義します
    # その際中間層を下のようにいくつか入れると精度が上がります
    top_model = Sequential()
    top_model.add(Flatten(input_shape=vgg16.output_shape[1:]))
    top_model.add(Dense(32, activation='relu'))
    top_model.add(Dropout(0.5))
    top_model.add(Dense(3, activation='softmax'))
    
    # vggと、top_modelを連結します
    model = Model(vgg16.inputs, top_model(vgg16.output))
    
    # vggの層の重みを変更不能にします
    for layer in model.layers[:19]:
        layer.trainable = False
    
    # コンパイルします
    model.compile(loss='categorical_crossentropy',
                  optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
                  metrics=['accuracy'])
    
    # 学習を行います
    model.fit(X_train, y_train, batch_size=100, epochs=10, validation_data=(X_test, y_test))
    
    # 画像を一枚受け取り、世界の名所を判別する関数
    def place(img):
        img = cv2.resize(img, (50, 50))
        pred = np.argmax(model.predict(np.array([img])))
        if pred == 0:
            return 'マチュピチュ'
        elif pred == 1:
            return 'ウユニ塩湖'
        else:
            return 'アンコールワット'
    
    # 精度の評価
    scores = model.evaluate(X_test, y_test, verbose=1)
    print('Test loss:', scores[0])
    print('Test accuracy:', scores[1])
    
    # place関数に名所の写真を渡してその場所を予測します
    img = cv2.imread('/content/drive/MyDrive/Aidemy/world_data/machupichu/' + path_machupichu[0])
    b,g,r = cv2.split(img)
    img1 = cv2.merge([r,g,b])
    plt.imshow(img1)
    plt.show()
    print(place(img))
    
    # モデルデータを出力
    from google.colab import files
    
    # resultディレクトリを作成
    result_dir = "result"
    if not os.path.exists(result_dir):
      os.mkdir(result_dir)
    # 学習したモデルを保存
    model.save(os.path.join(result_dir, "place_model.h5"))
    
    files.download("/content/result/place_model.h5")

    モデルの作成中に起きたエラーや調べたこと

    「If the number of classes in the model does not match the number of classes in the target, you need to make changes to either the model or the target.」というエラーが最初に発生しChat GPTなどを利用して調べたところ、理由は、モデルのクラス数とターゲットのクラス数が一致していないためとのことでしたが、何度見直してもクラスの数は一致しており悩みました。最終的に「img_Angkor.append(img)」の部分の入力ミスに気づきそこを修正すると解決し、エラーはでなくなりました。
    また、ファイルパスについてのエラーも発生しましたが、こちらはファイルパスの最後に「/」を加えることで解決できました。
    最後にローカル環境できちんと動くか確認したところ、画像を送信するとエラーがでてしまいましたが、アプリケーション側の以下のコード(グレイスケールの部分)が「True」になっており、「False」に修正することでカラーの画像で識別できるようになり、このエラーは解決できました。

    img = image.load_img(filepath, grayscale=False, target_size=(image_size,image_size))

    HTMLの作成

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Tower Classifier</title>
        <link rel="stylesheet" href="./static/stylesheet.css">
    </head>
    <body>
        <header>   
            <!-- <img class="header_img" src="https://aidemyexstorage.blob.core.windows.net/aidemycontents/1621500180546399.png" alt="Aidemy"> -->
            <a class="header-logo" href="#">名所の識別</a>
        </header>
    
        <div class="main">    
            <h2> AIが送信された3種類の場所を識別します(マチュピチュ、ウユニ塩湖、アンコールワット)</h2>
            <p>画像を送信してください</p>
            <form method="POST" enctype="multipart/form-data">
                <input class="file_choose" type="file" name="file">
                <input class="btn" value="submit!" type="submit">
            </form>
            <div class="answer">{{answer}}</div>
        </div>
    
        <footer>
            <img class="footer_img" src="https://aidemyexstorage.blob.core.windows.net/aidemycontents/1621500180546399.png" alt="Aidemy">
            <small>&copy; 2024, M.A</small>   
        </footer>
    </body>
    </html>

    まとめ

    今回アプリケーションを作成し、学んだ内容についてより理解を深めることもできとても勉強になりました。今回はわずか三か所の判別のみでしたが、もっと増やして制度もあげられるように工夫してみようと思います。
    最後まで読んでいただきありがとうございました。

    このブログはAidemy Premiumのカリキュラムの一環で、受講修了条件を満たすために公開しています。


    あなたへのおすすめ