Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,46 +1,30 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
import cv2
|
| 3 |
-
import numpy as np
|
| 4 |
-
import tensorflow as tf
|
| 5 |
-
from tensorflow.keras.applications.mobilenet import preprocess_input
|
| 6 |
-
from tensorflow.keras.applications.mobilenet import decode_predictions
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
|
|
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
model = tf.keras.applications.MobileNet(weights="imagenet")
|
| 17 |
-
|
| 18 |
-
def detect_objects(frame):
|
| 19 |
-
# 预处理图像
|
| 20 |
-
image_resized = cv2.resize(frame, (224, 224))
|
| 21 |
-
image_array = np.expand_dims(image_resized, axis=0)
|
| 22 |
-
processed_image = preprocess_input(image_array)
|
| 23 |
-
|
| 24 |
-
# 使用模型进行预测
|
| 25 |
-
preds = model.predict(processed_image)
|
| 26 |
-
decoded_preds = decode_predictions(preds, top=3)[0] # 取前3个结果
|
| 27 |
-
objects = [f"{label}: {round(score * 100, 2)}%" for (_, label, score) in decoded_preds]
|
| 28 |
-
return objects
|
| 29 |
-
|
| 30 |
-
# 读取摄像头流并显示
|
| 31 |
while True:
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
if not ret:
|
| 34 |
-
|
| 35 |
break
|
| 36 |
-
|
| 37 |
-
# 检测物体
|
| 38 |
-
objects = detect_objects(frame)
|
| 39 |
-
detected_text = " | ".join(objects)
|
| 40 |
-
|
| 41 |
-
# 显示检测结果
|
| 42 |
-
cv2.putText(frame, detected_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2, cv2.LINE_AA)
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import cv2
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
# 打开默认摄像头,通常为0
|
| 4 |
+
cap = cv2.VideoCapture(0)
|
| 5 |
|
| 6 |
+
# 检查摄像头是否成功打开
|
| 7 |
+
if not cap.isOpened():
|
| 8 |
+
print("无法打开摄像头")
|
| 9 |
+
exit()
|
| 10 |
|
| 11 |
+
# 读取并显示摄像头画面
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
while True:
|
| 13 |
+
# 从摄像头读取一帧
|
| 14 |
+
ret, frame = cap.read()
|
| 15 |
+
|
| 16 |
+
# 检查是否成功读取帧
|
| 17 |
if not ret:
|
| 18 |
+
print("无法接收帧,结束程序")
|
| 19 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# 显示帧
|
| 22 |
+
cv2.imshow('摄像头', frame)
|
| 23 |
+
|
| 24 |
+
# 按下 'q' 键退出
|
| 25 |
+
if cv2.waitKey(1) & 0xFF == ord('q'):
|
| 26 |
+
break
|
| 27 |
+
|
| 28 |
+
# 释放摄像头并关闭所有窗口
|
| 29 |
+
cap.release()
|
| 30 |
+
cv2.destroyAllWindows()
|