Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tensorflow.keras.preprocessing import image
|
| 5 |
+
from tensorflow.keras.models import load_model
|
| 6 |
+
|
| 7 |
+
# TensorFlow.jsモデルのURL
|
| 8 |
+
URL = "https://teachablemachine.withgoogle.com/models/ZPfAhDYCh/"
|
| 9 |
+
|
| 10 |
+
# モデルのロード
|
| 11 |
+
model_url = URL + "model.json"
|
| 12 |
+
metadata_url = URL + "metadata.json"
|
| 13 |
+
model = load_model(model_url)
|
| 14 |
+
|
| 15 |
+
# クラスの数を取得
|
| 16 |
+
max_predictions = model.layers[-1].output_shape[1]
|
| 17 |
+
|
| 18 |
+
# カメラの初期化
|
| 19 |
+
def init():
|
| 20 |
+
global cap
|
| 21 |
+
cap = cv2.VideoCapture(0) # カメラのデフォルトデバイスを使用
|
| 22 |
+
|
| 23 |
+
# 画像を予測
|
| 24 |
+
def predict():
|
| 25 |
+
global cap
|
| 26 |
+
ret, frame = cap.read() # カメラからフレームをキャプチャ
|
| 27 |
+
if not ret:
|
| 28 |
+
print("Failed to capture image from camera.")
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
frame = cv2.resize(frame, (200, 200)) # 画像サイズをモデルの入力サイズに変更
|
| 32 |
+
img_array = image.img_to_array(frame)
|
| 33 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 34 |
+
img_array /= 255.0 # 画像データの正規化
|
| 35 |
+
|
| 36 |
+
# 予測
|
| 37 |
+
prediction = model.predict(img_array)
|
| 38 |
+
|
| 39 |
+
# 結果の表示
|
| 40 |
+
result = {}
|
| 41 |
+
for i in range(max_predictions):
|
| 42 |
+
result[f"Class {i}"] = prediction[0][i]
|
| 43 |
+
|
| 44 |
+
return result
|
| 45 |
+
|
| 46 |
+
# インターフェースの作成
|
| 47 |
+
iface = gr.Interface(fn=predict, live=True, capture_session=True)
|
| 48 |
+
iface.launch()
|