Shi Tong Yuan commited on
Commit
5b2d0aa
·
1 Parent(s): 4ce77f9

add/edit some videos

Browse files
.gitattributes CHANGED
@@ -38,5 +38,10 @@ test/1.mp4 filter=lfs diff=lfs merge=lfs -text
38
  test/2.mp4 filter=lfs diff=lfs merge=lfs -text
39
  test/3.mp4 filter=lfs diff=lfs merge=lfs -text
40
  test/4.mp4 filter=lfs diff=lfs merge=lfs -text
41
- test/cat[[:space:]]bird[[:space:]]dog.mp4 filter=lfs diff=lfs merge=lfs -text
 
42
  test/horse[[:space:]]cow[[:space:]]people.mp4 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
38
  test/2.mp4 filter=lfs diff=lfs merge=lfs -text
39
  test/3.mp4 filter=lfs diff=lfs merge=lfs -text
40
  test/4.mp4 filter=lfs diff=lfs merge=lfs -text
41
+ test/bicycles.mp4 filter=lfs diff=lfs merge=lfs -text
42
+ test/cat[[:space:]]dog.mp4 filter=lfs diff=lfs merge=lfs -text
43
  test/horse[[:space:]]cow[[:space:]]people.mp4 filter=lfs diff=lfs merge=lfs -text
44
+ test/motorbikes.mp4 filter=lfs diff=lfs merge=lfs -text
45
+ test/output.mp4 filter=lfs diff=lfs merge=lfs -text
46
+ test/planes.mp4 filter=lfs diff=lfs merge=lfs -text
47
+ test/trains.mp4 filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # 忽略 tmp 文件夹下的所有 mp4 文件
2
+ tmp/*.mp4
app.py CHANGED
@@ -8,29 +8,30 @@ import shutil
8
  import os
9
  import skvideo.io
10
 
 
 
 
 
 
 
 
 
11
  # 定义视频处理函数
12
- def process_video(input_video_path):
 
 
13
  use_gpu = False
14
-
15
- frame_display_interval = 30
16
- frame_display_counter = frame_display_interval
17
- confidence_level = 0.5
18
  writer = None
 
19
 
20
- CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
21
- "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
22
- "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
23
- "sofa", "train", "tvmonitor"]
24
-
25
- COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
26
-
27
- net = cv2.dnn.readNetFromCaffe('ssd_files/MobileNetSSD_deploy.prototxt', 'ssd_files/MobileNetSSD_deploy.caffemodel')
28
 
29
  if use_gpu:
30
  print("[INFO] setting preferable backend and target to CUDA...")
31
  net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
32
  net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
33
-
34
  print("[INFO] accessing video stream...")
35
  vs = cv2.VideoCapture(input_video_path)
36
 
@@ -49,7 +50,7 @@ def process_video(input_video_path):
49
 
50
  for i in np.arange(0, detections.shape[2]):
51
  confidence = detections[0, 0, i, 2]
52
- if confidence > confidence_level:
53
  idx = int(detections[0, 0, i, 1])
54
  box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
55
  (startX, startY, endX, endY) = box.astype("int")
@@ -58,56 +59,57 @@ def process_video(input_video_path):
58
  originEndX = int(endX*origin_w/w)
59
  originEndY = int(endY*origin_h/h)
60
 
61
- label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100)
62
- cv2.rectangle(origin_frame, (originStartX, originStartY), (originEndX, originEndY), COLORS[idx], 2)
 
 
63
 
64
- y = originStartY - 15 if originStartY - 15 > 15 else originStartY + 15
65
- cv2.putText(origin_frame, label, (originStartX, y), cv2.FONT_HERSHEY_DUPLEX, 0.5, COLORS[idx], 1)
 
66
 
67
  # 如果没有创建视频编写器,请创建它
68
  if writer is None:
69
  random_filename = "./tmp/" + str(uuid.uuid4()) + ".mp4"
70
- fourcc = cv2.VideoWriter_fourcc(*'avc1') # 可以根据需要选择适当的编解码器
71
  # writer = cv2.VideoWriter(random_filename, fourcc, 30, (origin_frame.shape[1], origin_frame.shape[0]), True)
72
- writer = skvideo.io.FFmpegWriter(random_filename, outputdict={'-vcodec': 'libx264', '-pix_fmt': 'yuv420p'})
 
73
  # 将帧写入输出视频
74
  # writer.write(origin_frame)
75
  writer.writeFrame(cv2.cvtColor(origin_frame, cv2.COLOR_BGR2RGB))
76
 
77
- display_frame = cv2.cvtColor(origin_frame, cv2.COLOR_BGR2RGB) # 将图像从BGR转换为RGB
78
- if frame_display_counter:
79
- frame_display_counter -= 1
 
80
  else:
81
  yield display_frame, None
82
- frame_display_counter = frame_display_interval
83
 
84
  vs.release()
85
  # 在循环结束后释放视频编写器
86
  # if writer is not None:
87
  # writer.release()
88
  writer.close()
89
-
90
- # 将相对路径转换为绝对路径
91
- absolute_path = os.path.abspath(random_filename)
92
- print(absolute_path)
93
-
94
  # 指定根目录路径
95
  root_directory = "./tmp"
96
  # 调用函数打印根目录的文件树
97
  print_directory_tree(root_directory)
98
 
99
- yield display_frame, absolute_path
100
 
101
 
102
  def print_directory_tree(directory):
103
  for root, dirs, files in os.walk(directory):
104
  # 打印当前目录路径
105
  print(f"Directory: {root}")
106
-
107
  # 打印当前目录下的所有文件
108
  for file in files:
109
  print(f" File: {os.path.join(root, file)}")
110
-
111
  # 打印当前目录下的所有子目录
112
  for dir in dirs:
113
  print(f" Subdirectory: {os.path.join(root, dir)}")
@@ -124,26 +126,34 @@ def cleanup_tmp_folder():
124
  except Exception as e:
125
  print(f"Error cleaning up .mp4 files in tmp folder: {str(e)}")
126
 
 
127
  def main():
128
  # 定义Gradio界面
129
  with gr.Blocks() as demo:
130
  with gr.Row():
131
- input_video = gr.Video(label="input")
132
- processed_frames = gr.Image(label="live preview")
133
- output_video = gr.Video(label="output")
134
 
135
  with gr.Row():
136
- examples = gr.Examples([f"test/{file.name}" for file in os.scandir('./test')], inputs=input_video)
 
 
 
 
 
137
  process_video_btn = gr.Button("process video")
138
 
139
- process_video_btn.click(process_video, input_video, [processed_frames, output_video])
 
 
 
140
 
141
- demo.queue().launch(share=False,debug=True,server_name="0.0.0.0",server_port=7860)
142
 
143
  if __name__ == "__main__":
144
  # 注册清理函数,确保在程序退出时执行
145
  atexit.register(cleanup_tmp_folder)
146
-
147
  # 根目录路径
148
  root_directory = "./"
149
  # tmp文件夹路径
@@ -153,4 +163,4 @@ if __name__ == "__main__":
153
  os.makedirs(tmp_directory)
154
 
155
  # 执行main()
156
- main()
 
8
  import os
9
  import skvideo.io
10
 
11
+ # 全局设置
12
+ DEFAULT_CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair",
13
+ "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
14
+ COLORS = np.random.uniform(0, 255, size=(len(DEFAULT_CLASSES), 3))
15
+ DISPLAY_INTERVAL = 30
16
+ CONFIDENCE_LEVEL = 0.5
17
+
18
+
19
  # 定义视频处理函数
20
+ def process_video(input_video_path, selected_classes):
21
+ print(selected_classes)
22
+
23
  use_gpu = False
 
 
 
 
24
  writer = None
25
+ display_counter = DISPLAY_INTERVAL
26
 
27
+ net = cv2.dnn.readNetFromCaffe(
28
+ 'ssd_files/MobileNetSSD_deploy.prototxt', 'ssd_files/MobileNetSSD_deploy.caffemodel')
 
 
 
 
 
 
29
 
30
  if use_gpu:
31
  print("[INFO] setting preferable backend and target to CUDA...")
32
  net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
33
  net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
34
+
35
  print("[INFO] accessing video stream...")
36
  vs = cv2.VideoCapture(input_video_path)
37
 
 
50
 
51
  for i in np.arange(0, detections.shape[2]):
52
  confidence = detections[0, 0, i, 2]
53
+ if confidence > CONFIDENCE_LEVEL:
54
  idx = int(detections[0, 0, i, 1])
55
  box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
56
  (startX, startY, endX, endY) = box.astype("int")
 
59
  originEndX = int(endX*origin_w/w)
60
  originEndY = int(endY*origin_h/h)
61
 
62
+ if DEFAULT_CLASSES[idx] in selected_classes:
63
+ label = "{}: {:.2f}%".format(DEFAULT_CLASSES[idx], confidence * 100)
64
+ cv2.rectangle(origin_frame, (originStartX, originStartY),
65
+ (originEndX, originEndY), COLORS[idx], 2)
66
 
67
+ y = originStartY - 15 if originStartY - 15 > 15 else originStartY + 15
68
+ cv2.putText(origin_frame, label, (originStartX, y),
69
+ cv2.FONT_HERSHEY_DUPLEX, 0.5, COLORS[idx], 1)
70
 
71
  # 如果没有创建视频编写器,请创建它
72
  if writer is None:
73
  random_filename = "./tmp/" + str(uuid.uuid4()) + ".mp4"
74
+ # fourcc = cv2.VideoWriter_fourcc(*'avc1') # 可以根据需要选择适当的编解码器
75
  # writer = cv2.VideoWriter(random_filename, fourcc, 30, (origin_frame.shape[1], origin_frame.shape[0]), True)
76
+ writer = skvideo.io.FFmpegWriter(random_filename, outputdict={
77
+ '-vcodec': 'libx264', '-pix_fmt': 'yuv420p'})
78
  # 将帧写入输出视频
79
  # writer.write(origin_frame)
80
  writer.writeFrame(cv2.cvtColor(origin_frame, cv2.COLOR_BGR2RGB))
81
 
82
+ display_frame = cv2.cvtColor(
83
+ origin_frame, cv2.COLOR_BGR2RGB) # 将图像从BGR转换为RGB
84
+ if display_counter:
85
+ display_counter -= 1
86
  else:
87
  yield display_frame, None
88
+ display_counter = DISPLAY_INTERVAL
89
 
90
  vs.release()
91
  # 在循环结束后释放视频编写器
92
  # if writer is not None:
93
  # writer.release()
94
  writer.close()
95
+
 
 
 
 
96
  # 指定根目录路径
97
  root_directory = "./tmp"
98
  # 调用函数打印根目录的文件树
99
  print_directory_tree(root_directory)
100
 
101
+ yield display_frame, random_filename
102
 
103
 
104
  def print_directory_tree(directory):
105
  for root, dirs, files in os.walk(directory):
106
  # 打印当前目录路径
107
  print(f"Directory: {root}")
108
+
109
  # 打印当前目录下的所有文件
110
  for file in files:
111
  print(f" File: {os.path.join(root, file)}")
112
+
113
  # 打印当前目录下的所有子目录
114
  for dir in dirs:
115
  print(f" Subdirectory: {os.path.join(root, dir)}")
 
126
  except Exception as e:
127
  print(f"Error cleaning up .mp4 files in tmp folder: {str(e)}")
128
 
129
+
130
  def main():
131
  # 定义Gradio界面
132
  with gr.Blocks() as demo:
133
  with gr.Row():
134
+ input_video = gr.Video(label="Video Input")
135
+ processed_frames = gr.Image(label="Live Preview")
136
+ output_video = gr.Video(label="Video Output")
137
 
138
  with gr.Row():
139
+ with gr.Column():
140
+ input_classes = gr.Dropdown(
141
+ DEFAULT_CLASSES, value=DEFAULT_CLASSES, multiselect=True, label="Detection Classes", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
142
+ )
143
+ examples = gr.Examples(
144
+ [f"test/{file.name}" for file in os.scandir('./test')], inputs=input_video)
145
  process_video_btn = gr.Button("process video")
146
 
147
+ process_video_btn.click(process_video, inputs=[
148
+ input_video, input_classes], outputs=[processed_frames, output_video])
149
+
150
+ demo.queue().launch(share=False, debug=True, server_name="0.0.0.0", server_port=7860)
151
 
 
152
 
153
  if __name__ == "__main__":
154
  # 注册清理函数,确保在程序退出时执行
155
  atexit.register(cleanup_tmp_folder)
156
+
157
  # 根目录路径
158
  root_directory = "./"
159
  # tmp文件夹路径
 
163
  os.makedirs(tmp_directory)
164
 
165
  # 执行main()
166
+ main()
test.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+
4
+ def sentence_builder(quantity, animal, countries, place, activity_list, morning):
5
+ return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
6
+
7
+
8
+ demo = gr.Interface(
9
+ sentence_builder,
10
+ [
11
+ gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"),
12
+ gr.Dropdown(
13
+ ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
14
+ ),
15
+ gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
16
+ gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
17
+ gr.Dropdown(
18
+ ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
19
+ ),
20
+ gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
21
+ ],
22
+ "text",
23
+ examples=[
24
+ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
25
+ [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
26
+ [10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
27
+ [8, "cat", ["Pakistan"], "zoo", ["ate"], True],
28
+ ]
29
+ )
30
+
31
+ if __name__ == "__main__":
32
+ demo.launch()
test/{cat bird dog.mp4 → bicycles.mp4} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3d73e8c7dbf12a35bf7d82ef881a46d58e33fa0058a72414b53ce5cfcaec78ab
3
- size 6629220
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d4077002a5d0627599091ed8c204a149e354433a764baeb50ce3747ddcf3844
3
+ size 5031955
test/cat dog.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a08b4bae4486c30d8af2b8f4e2e736e5d7bf6789934f38615ec9208453508957
3
+ size 9481934
test/motorbikes.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a3ee65ea65d844baef575d966aa76ad5780af97cb3d56b1e855c1784a6fefaf
3
+ size 8739256
test/output.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:332483edafc4761b39f3ec5eeb1f58baa7a1fd9635f12db02f96871bc79ff04f
3
+ size 28810171
test/planes.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:848fe543a4653a4d224d1fed284f50e6c69332aa2f0f05f9fc06b89c2e278425
3
+ size 13107364
test/trains.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e94002af4a980959103201b58b3200f2980b5c9bf2a202e66832a8f9d3966730
3
+ size 10075560