freddyaboulton HF staff commited on
Commit
ba2960a
·
1 Parent(s): 38d5570
Files changed (8) hide show
  1. .gitattributes +1 -0
  2. .gitignore +1 -0
  3. README.md +2 -2
  4. app.py +14 -25
  5. requirements.txt +1 -0
  6. run.ipynb +0 -1
  7. run.py +0 -115
  8. video_example.mp4 +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ video_example.mp4 filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/
README.md CHANGED
@@ -5,8 +5,8 @@ emoji: 🔥
5
  colorFrom: indigo
6
  colorTo: indigo
7
  sdk: gradio
8
- sdk_version: 5.0.2
9
- app_file: run.py
10
  pinned: false
11
  hf_oauth: true
12
  ---
 
5
  colorFrom: indigo
6
  colorTo: indigo
7
  sdk: gradio
8
+ sdk_version: 5.1.0
9
+ app_file: app.py
10
  pinned: false
11
  hf_oauth: true
12
  ---
app.py CHANGED
@@ -5,7 +5,7 @@ from PIL import Image
5
  import torch
6
  import time
7
  import numpy as np
8
- import uuid
9
 
10
  from transformers import RTDetrForObjectDetection, RTDetrImageProcessor
11
 
@@ -21,21 +21,6 @@ SUBSAMPLE = 2
21
  def stream_object_detection(video, conf_threshold):
22
  cap = cv2.VideoCapture(video)
23
 
24
- video_codec = cv2.VideoWriter_fourcc(*"mp4v") # type: ignore
25
- fps = int(cap.get(cv2.CAP_PROP_FPS))
26
-
27
- desired_fps = fps // SUBSAMPLE
28
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) // 2
29
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) // 2
30
-
31
- iterating, frame = cap.read()
32
-
33
- n_frames = 0
34
-
35
- name = f"output_{uuid.uuid4()}.mp4"
36
- segment_file = cv2.VideoWriter(name, video_codec, desired_fps, (width, height)) # type: ignore
37
- batch = []
38
-
39
  while iterating:
40
  frame = cv2.resize( frame, (0,0), fx=0.5, fy=0.5)
41
  frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
@@ -62,15 +47,11 @@ def stream_object_detection(video, conf_threshold):
62
  frame = np.array(pil_image)
63
  # Convert RGB to BGR
64
  frame = frame[:, :, ::-1].copy()
65
- segment_file.write(frame)
66
 
67
  batch = []
68
- segment_file.release()
69
- yield name
70
  end = time.time()
71
  print("time taken for processing boxes", end - start)
72
- name = f"output_{uuid.uuid4()}.mp4"
73
- segment_file = cv2.VideoWriter(name, video_codec, desired_fps, (width, height)) # type: ignore
74
 
75
  iterating, frame = cap.read()
76
  n_frames += 1
@@ -80,7 +61,7 @@ with gr.Blocks() as app:
80
  gr.HTML(
81
  """
82
  <h1 style='text-align: center'>
83
- Video Object Detection with RT-DETR
84
  </h1>
85
  """)
86
  gr.HTML(
@@ -100,13 +81,21 @@ with gr.Blocks() as app:
100
  value=0.30,
101
  )
102
  with gr.Column():
103
- output_video = gr.Video(label="Processed Video", streaming=True, autoplay=True)
 
 
 
 
104
 
105
- video.upload(
106
  fn=stream_object_detection,
107
  inputs=[video, conf_threshold],
108
- outputs=[output_video],
 
109
  )
110
 
 
 
 
111
  if __name__ == '__main__':
112
  app.launch()
 
5
  import torch
6
  import time
7
  import numpy as np
8
+ from gradio_webrtc import WebRTC
9
 
10
  from transformers import RTDetrForObjectDetection, RTDetrImageProcessor
11
 
 
21
  def stream_object_detection(video, conf_threshold):
22
  cap = cv2.VideoCapture(video)
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  while iterating:
25
  frame = cv2.resize( frame, (0,0), fx=0.5, fy=0.5)
26
  frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
 
47
  frame = np.array(pil_image)
48
  # Convert RGB to BGR
49
  frame = frame[:, :, ::-1].copy()
50
+ yield frame
51
 
52
  batch = []
 
 
53
  end = time.time()
54
  print("time taken for processing boxes", end - start)
 
 
55
 
56
  iterating, frame = cap.read()
57
  n_frames += 1
 
61
  gr.HTML(
62
  """
63
  <h1 style='text-align: center'>
64
+ Video Object Detection with RT-DETR (Powered by WebRTC ⚡️)
65
  </h1>
66
  """)
67
  gr.HTML(
 
81
  value=0.30,
82
  )
83
  with gr.Column():
84
+ output = WebRTC(label="WebRTC Stream",
85
+ rtc_configuration=None,
86
+ mode="receive",
87
+ modality="video")
88
+ detect = gr.Button("Detect", variant="primary")
89
 
90
+ output.stream(
91
  fn=stream_object_detection,
92
  inputs=[video, conf_threshold],
93
+ outputs=[output],
94
+ trigger=detect.click
95
  )
96
 
97
+ gr.Examples(examples=["video_example.mp4"],
98
+ inputs=[video])
99
+
100
  if __name__ == '__main__':
101
  app.launch()
requirements.txt CHANGED
@@ -3,3 +3,4 @@ opencv-python
3
  torch
4
  transformers>=4.43.0
5
  Pillow
 
 
3
  torch
4
  transformers>=4.43.0
5
  Pillow
6
+ gradio-webrtc
run.ipynb DELETED
@@ -1 +0,0 @@
1
- {"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: rt-detr-object-detection"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio safetensors==0.4.3 opencv-python torch transformers>=4.43.0 Pillow "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "!wget -q https://github.com/gradio-app/gradio/raw/main/demo/rt-detr-object-detection/draw_boxes.py"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import spaces\n", "import gradio as gr\n", "import cv2\n", "from PIL import Image\n", "import torch\n", "import time\n", "import numpy as np\n", "import uuid\n", "\n", "from transformers import RTDetrForObjectDetection, RTDetrImageProcessor # type: ignore\n", "\n", "from draw_boxes import draw_bounding_boxes\n", "\n", "image_processor = RTDetrImageProcessor.from_pretrained(\"PekingU/rtdetr_r50vd\")\n", "model = RTDetrForObjectDetection.from_pretrained(\"PekingU/rtdetr_r50vd\").to(\"cuda\")\n", "\n", "\n", "SUBSAMPLE = 2\n", "\n", "\n", "@spaces.GPU\n", "def stream_object_detection(video, conf_threshold):\n", " cap = cv2.VideoCapture(video)\n", "\n", " video_codec = cv2.VideoWriter_fourcc(*\"mp4v\") # type: ignore\n", " fps = int(cap.get(cv2.CAP_PROP_FPS))\n", "\n", " desired_fps = fps // SUBSAMPLE\n", " width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) // 2\n", " height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) // 2\n", "\n", " iterating, frame = cap.read()\n", "\n", " n_frames = 0\n", "\n", " name = f\"output_{uuid.uuid4()}.mp4\"\n", " segment_file = cv2.VideoWriter(name, video_codec, desired_fps, (width, height)) # type: ignore\n", " batch = []\n", "\n", " while iterating:\n", " frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)\n", " frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n", " if n_frames % SUBSAMPLE == 0:\n", " batch.append(frame)\n", " if len(batch) == 2 * desired_fps:\n", " inputs = image_processor(images=batch, return_tensors=\"pt\").to(\"cuda\")\n", "\n", " print(f\"starting batch of size {len(batch)}\")\n", " start = time.time()\n", " with torch.no_grad():\n", " outputs = model(**inputs)\n", " end = time.time()\n", " print(\"time taken for inference\", end - start)\n", "\n", " start = time.time()\n", " boxes = image_processor.post_process_object_detection(\n", " outputs,\n", " target_sizes=torch.tensor([(height, width)] * len(batch)),\n", " threshold=conf_threshold,\n", " )\n", "\n", " for _, (array, box) in enumerate(zip(batch, boxes)):\n", " pil_image = draw_bounding_boxes(\n", " Image.fromarray(array), box, model, conf_threshold\n", " )\n", " frame = np.array(pil_image)\n", " # Convert RGB to BGR\n", " frame = frame[:, :, ::-1].copy()\n", " segment_file.write(frame)\n", "\n", " batch = []\n", " segment_file.release()\n", " yield name\n", " end = time.time()\n", " print(\"time taken for processing boxes\", end - start)\n", " name = f\"output_{uuid.uuid4()}.mp4\"\n", " segment_file = cv2.VideoWriter(\n", " name, video_codec, desired_fps, (width, height)\n", " ) # type: ignore\n", "\n", " iterating, frame = cap.read()\n", " n_frames += 1\n", "\n", "\n", "with gr.Blocks() as demo:\n", " gr.HTML(\n", " \"\"\"\n", " <h1 style='text-align: center'>\n", " Video Object Detection with <a href='https://huggingface.co/PekingU/rtdetr_r101vd_coco_o365' target='_blank'>RT-DETR</a>\n", " </h1>\n", " \"\"\"\n", " )\n", " with gr.Row():\n", " with gr.Column():\n", " video = gr.Video(label=\"Video Source\")\n", " conf_threshold = gr.Slider(\n", " label=\"Confidence Threshold\",\n", " minimum=0.0,\n", " maximum=1.0,\n", " step=0.05,\n", " value=0.30,\n", " )\n", " with gr.Column():\n", " output_video = gr.Video(\n", " label=\"Processed Video\", streaming=True, autoplay=True\n", " )\n", "\n", " video.upload(\n", " fn=stream_object_detection,\n", " inputs=[video, conf_threshold],\n", " outputs=[output_video],\n", " )\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
 
 
run.py DELETED
@@ -1,115 +0,0 @@
1
- import spaces
2
- import gradio as gr
3
- import cv2
4
- from PIL import Image
5
- import torch
6
- import time
7
- import numpy as np
8
- import uuid
9
-
10
- from transformers import RTDetrForObjectDetection, RTDetrImageProcessor # type: ignore
11
-
12
- from draw_boxes import draw_bounding_boxes
13
-
14
- image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
15
- model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd").to("cuda")
16
-
17
-
18
- SUBSAMPLE = 2
19
-
20
-
21
- @spaces.GPU
22
- def stream_object_detection(video, conf_threshold):
23
- cap = cv2.VideoCapture(video)
24
-
25
- video_codec = cv2.VideoWriter_fourcc(*"mp4v") # type: ignore
26
- fps = int(cap.get(cv2.CAP_PROP_FPS))
27
-
28
- desired_fps = fps // SUBSAMPLE
29
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) // 2
30
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) // 2
31
-
32
- iterating, frame = cap.read()
33
-
34
- n_frames = 0
35
-
36
- name = f"output_{uuid.uuid4()}.mp4"
37
- segment_file = cv2.VideoWriter(name, video_codec, desired_fps, (width, height)) # type: ignore
38
- batch = []
39
-
40
- while iterating:
41
- frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
42
- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
43
- if n_frames % SUBSAMPLE == 0:
44
- batch.append(frame)
45
- if len(batch) == 2 * desired_fps:
46
- inputs = image_processor(images=batch, return_tensors="pt").to("cuda")
47
-
48
- print(f"starting batch of size {len(batch)}")
49
- start = time.time()
50
- with torch.no_grad():
51
- outputs = model(**inputs)
52
- end = time.time()
53
- print("time taken for inference", end - start)
54
-
55
- start = time.time()
56
- boxes = image_processor.post_process_object_detection(
57
- outputs,
58
- target_sizes=torch.tensor([(height, width)] * len(batch)),
59
- threshold=conf_threshold,
60
- )
61
-
62
- for _, (array, box) in enumerate(zip(batch, boxes)):
63
- pil_image = draw_bounding_boxes(
64
- Image.fromarray(array), box, model, conf_threshold
65
- )
66
- frame = np.array(pil_image)
67
- # Convert RGB to BGR
68
- frame = frame[:, :, ::-1].copy()
69
- segment_file.write(frame)
70
-
71
- batch = []
72
- segment_file.release()
73
- yield name
74
- end = time.time()
75
- print("time taken for processing boxes", end - start)
76
- name = f"output_{uuid.uuid4()}.mp4"
77
- segment_file = cv2.VideoWriter(
78
- name, video_codec, desired_fps, (width, height)
79
- ) # type: ignore
80
-
81
- iterating, frame = cap.read()
82
- n_frames += 1
83
-
84
-
85
- with gr.Blocks() as demo:
86
- gr.HTML(
87
- """
88
- <h1 style='text-align: center'>
89
- Video Object Detection with <a href='https://huggingface.co/PekingU/rtdetr_r101vd_coco_o365' target='_blank'>RT-DETR</a>
90
- </h1>
91
- """
92
- )
93
- with gr.Row():
94
- with gr.Column():
95
- video = gr.Video(label="Video Source")
96
- conf_threshold = gr.Slider(
97
- label="Confidence Threshold",
98
- minimum=0.0,
99
- maximum=1.0,
100
- step=0.05,
101
- value=0.30,
102
- )
103
- with gr.Column():
104
- output_video = gr.Video(
105
- label="Processed Video", streaming=True, autoplay=True
106
- )
107
-
108
- video.upload(
109
- fn=stream_object_detection,
110
- inputs=[video, conf_threshold],
111
- outputs=[output_video],
112
- )
113
-
114
- if __name__ == "__main__":
115
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
video_example.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58f4485e53ab6877244b23c73c74151475a7f3814b8832e32ca02562e37ea0a5
3
+ size 5373394