簡単機械学習⑤ 分類用スクリプトの作成

 前準備が長いのが、機械学習の面倒なところ。ここでいよいよ、学習済みモデルを使って対象物を認識させます。ここが機械学習のコア的な部分だろうけど、最初は面倒な理屈は抜きで、基本おまかせで。失敗したら工夫しながら何度でもやり直せばOKよ!

手順1 スクリプトの作成

  セキュリティとか、そういうのは完全無視スクリプトです。

python
###############################################################
# RTSP映像を表示しながら、2秒ごとに推論し結果を映像に表示
###############################################################

import cv2
import numpy as np
import time
from tensorflow.keras.models import load_model

# --- モデル読み込み ---
model_path = 'toy_X_model_flatten.keras'
model = load_model(model_path)

# --- 入力画像サイズ ---
img_width = 400
img_height = 200

# --- クラスラベル(学習時と一致)---
class_labels = ['00_toyA', '01_toyB', '02_toyC', '03_toyD', '04_toyE']
class_labels = [label.split('_')[1] for label in class_labels]  

# --- RTSP URL(カメラに合わせて変更)---
rtsp_url = "rtsp://*name*:*pass*@*ipadress*/***"
# --- ユーザ名+パスワード+IPアドレス+RTSP カメラの指定パス

# --- 推論間隔(秒)---
predict_interval = 2.0  # 2秒ごとに推論
last_predict_time = 0
last_result_text = "推論中..."

# --- RTSPストリーム接続 ---
cap = cv2.VideoCapture(rtsp_url)

# --- メインループ ---
while True:
    ret, frame = cap.read()

    # --- 表示用にリサイズ ---
    display_frame = cv2.resize(frame, (800, 442))

    # --- 現在時刻取得 ---
    current_time = time.time()

    # --- 一定間隔で推論実行 ---
    if current_time - last_predict_time >= predict_interval:
        # 前処理:リサイズ&グレースケール
        resized_frame = cv2.resize(frame, (img_width, img_height))
        gray_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2GRAY)
        img_input = gray_frame.astype('float32') / 255.0
        img_input = img_input.reshape(1, img_height, img_width, 1)

        # 推論
        predictions = model.predict(img_input)[0]
        top2_idx = predictions.argsort()[-2:][::-1]

        top1_label = class_labels[top2_idx[0]]
        top1_score = float(predictions[top2_idx[0]])
        top2_label = class_labels[top2_idx[1]]
        top2_score = float(predictions[top2_idx[1]])

        # 表示用テキスト更新
        last_result_text = f"Top1: {top1_label} ({top1_score:.2f}) | Top2: {top2_label} ({top2_score:.2f})"
        last_predict_time = current_time

    # --- 推論結果を映像に重ねる ---
    cv2.putText(display_frame, last_result_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
                0.8, (0, 255, 0), 2, cv2.LINE_AA)

    # --- 映像表示 ---
    cv2.imshow("RTSP Wind Viewer (Interval Prediction)", display_frame)

    # --- 'q'キーで終了 ---
    if cv2.waitKey(1) & 0xFF == ord('q'):
        print(" 終 了 ")
        break

# --- 後処理 ---
cap.release()
cv2.destroyAllWindows()

手順2 改造するなら

 完全クローズドなんだけど、セキュリティを考えて、まずは、RTSPのアドレスを外に出すといいでしょうね。AIの奴がうるさいので。他にも色々言ってくるけど、無視!そのとき考えればいい感じで。   

 とりあえず何か動けば勝ち!