Binssin commited on
Commit
a155a1c
·
1 Parent(s): ea2b490

Add video input tab

Browse files
Files changed (1) hide show
  1. app.py +71 -12
app.py CHANGED
@@ -2,6 +2,9 @@ import gradio as gr
2
  from PIL import Image
3
  import numpy as np
4
  from ultralytics import YOLO
 
 
 
5
 
6
  # 載入模型
7
  model = YOLO('last.pt') # 使用您的模型
@@ -25,22 +28,78 @@ def process_image(input_image):
25
 
26
  return result_pil
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # 創建 Gradio 介面
29
  with gr.Blocks() as demo:
30
  gr.Markdown("# 磁磚檢測系統")
31
 
32
- with gr.Row():
33
- input_image = gr.Image(label="上傳圖片")
34
- output_image = gr.Image(label="檢測結果")
35
-
36
- submit_btn = gr.Button("開始檢測")
37
-
38
- # 設置事件處理
39
- submit_btn.click(
40
- fn=process_image,
41
- inputs=input_image,
42
- outputs=output_image
43
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  if __name__ == "__main__":
46
  demo.launch()
 
2
  from PIL import Image
3
  import numpy as np
4
  from ultralytics import YOLO
5
+ import cv2
6
+ import tempfile
7
+ import os
8
 
9
  # 載入模型
10
  model = YOLO('last.pt') # 使用您的模型
 
28
 
29
  return result_pil
30
 
31
+ def process_video(input_video):
32
+ # 創建臨時檔案來保存處理後的影片
33
+ temp_output = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False)
34
+ output_path = temp_output.name
35
+ temp_output.close()
36
+
37
+ # 讀取輸入影片
38
+ cap = cv2.VideoCapture(input_video)
39
+
40
+ # 獲取影片屬性
41
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
42
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
43
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
44
+
45
+ # 創建影片寫入器
46
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
47
+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
48
+
49
+ # 處理每一幀
50
+ while cap.isOpened():
51
+ ret, frame = cap.read()
52
+ if not ret:
53
+ break
54
+
55
+ # 使用模型進行預測
56
+ results = model.predict(frame)
57
+ result = results[0]
58
+
59
+ # 獲取處理後的幀
60
+ result_frame = result.plot()
61
+
62
+ # 寫入處理後的幀
63
+ out.write(result_frame)
64
+
65
+ # 釋放資源
66
+ cap.release()
67
+ out.release()
68
+
69
+ return output_path
70
+
71
  # 創建 Gradio 介面
72
  with gr.Blocks() as demo:
73
  gr.Markdown("# 磁磚檢測系統")
74
 
75
+ with gr.Tabs():
76
+ with gr.TabItem("圖片檢測"):
77
+ with gr.Row():
78
+ input_image = gr.Image(label="上傳圖片")
79
+ output_image = gr.Image(label="檢測結果")
80
+
81
+ submit_btn = gr.Button("開始檢測")
82
+
83
+ # 設置事件處理
84
+ submit_btn.click(
85
+ fn=process_image,
86
+ inputs=input_image,
87
+ outputs=output_image
88
+ )
89
+
90
+ with gr.TabItem("影片檢測"):
91
+ with gr.Row():
92
+ input_video = gr.Video(label="上傳影片")
93
+
94
+ video_submit_btn = gr.Button("開始檢測")
95
+ output_file = gr.File(label="下載處理後的影片")
96
+
97
+ # 設置事件處理
98
+ video_submit_btn.click(
99
+ fn=process_video,
100
+ inputs=input_video,
101
+ outputs=output_file
102
+ )
103
 
104
  if __name__ == "__main__":
105
  demo.launch()