oskarastrom commited on
Commit
034aaec
·
1 Parent(s): 193f172

Batch Annotation Loading

Browse files
app.py CHANGED
@@ -11,14 +11,16 @@ from zipfile import ZipFile
11
  import os
12
  from gradio_scripts.upload_ui import Upload_Gradio
13
  from gradio_scripts.result_ui import Result_Gradio, update_result, table_headers, info_headers, js_update_tab_labels
14
-
 
15
 
16
  #Initialize State & Result
17
  state = {
18
  'files': [],
19
  'index': 1,
20
  'total': 1,
21
- 'annotation_index': -1
 
22
  }
23
  result = {}
24
 
@@ -180,40 +182,71 @@ def cancel_inference():
180
  def prepare_annotation(index):
181
 
182
  state['annotation_index'] = index
 
183
 
 
 
 
 
 
184
  return {
185
- annotation_progress: gr.update(value="<p align='center' style='font-size: large;font-style: italic;'>Loading annotation...</p><!--" + str(np.random.rand()) + "-->", visible=True),
186
- master_tabs: gr.update(selected=2)
187
  }
188
 
189
- # Load frames and annotation information and show
190
- def open_annotation(_, progress=gr.Progress()):
 
 
 
 
 
191
  result_index = state['annotation_index']
192
 
193
  set_progress = lambda pct, msg: progress(pct, desc=msg)
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  annotation_html = ""
196
- if result["aris_input"][result_index]:
197
- annotations = init_frames(result["aris_input"][result_index], result['json_result'][result_index], gp=set_progress)
198
-
199
- # Header
200
- annotation_html += "<div id='annotation_header'>"
201
- annotation_html += " <h1 id='annotation_frame_nbr'>Frame 0/100</h1>"
202
- annotation_html += " <p id='annotation_edited'>(edited)</p>"
203
- annotation_html += "</div>"
204
-
205
- # Annotation Body
206
- annotation_html += "<div style='display:flex'>"
207
- annotation_html += " <canvas id='canvas' style='width:50%' onmousedown='mouse_down(event)' onmousemove='mouse_move(event)' onmouseup='mouse_up()' onmouseleave='mouse_up()'></canvas>"
208
- annotation_html += " <div id='annotation_display' style='width:50%'></div>"
209
- annotation_html += "</div>"
210
-
211
- # Dummy objects
212
- annotation_html += "<p id='annotation_info' style='display:none'>" + json.dumps(annotations) + "</p>"
213
- annotation_html += "<img id='annotation_img' onload='draw()' style='display:none'></img>"
214
- annotation_html += "<!--" + str(np.random.rand()) + "-->"
215
 
216
- return gr.update(value=annotation_html, visible=True), gr.update(visible=False), gr.update(visible=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
 
219
  components = {}
@@ -290,8 +323,23 @@ with demo:
290
  # Add annotation editor component
291
  annotation_editor = gr.HTML("", visible=False)
292
 
 
 
293
  # Event listener for opening annotation
294
- annotation_progress.change(open_annotation, annotation_progress, [annotation_editor, annotation_progress])
 
 
 
 
 
 
 
 
 
 
 
 
 
295
 
296
  # Event listener for running javascript defined in 'annotation_editor.js'
297
  with open('gradio_scripts/annotation_editor.js', 'r') as f:
 
11
  import os
12
  from gradio_scripts.upload_ui import Upload_Gradio
13
  from gradio_scripts.result_ui import Result_Gradio, update_result, table_headers, info_headers, js_update_tab_labels
14
+ from dataloader import create_dataloader_aris
15
+ from aris import BEAM_WIDTH_DIR
16
 
17
  #Initialize State & Result
18
  state = {
19
  'files': [],
20
  'index': 1,
21
  'total': 1,
22
+ 'annotation_index': -1,
23
+ 'frame_index': 0
24
  }
25
  result = {}
26
 
 
182
  def prepare_annotation(index):
183
 
184
  state['annotation_index'] = index
185
+ state['frame_index'] = 0
186
 
187
+ if result["aris_input"][index]:
188
+ return {
189
+ annotation_progress: gr.update(value="<p id='annotation_info' style='display:none'>[]</p><!--" + str(np.random.rand()) + "-->", visible=True),
190
+ master_tabs: gr.update(selected=2)
191
+ }
192
  return {
193
+ annotation_progress: gr.update(),
194
+ master_tabs: gr.update()
195
  }
196
 
197
+ annotation_info = None
198
+ annotation_dataset = None
199
+ # annotation_progress.change
200
+ def load_annotation(_, progress=gr.Progress()):
201
+ global annotation_info, annotation_dataset
202
+
203
+ # Get result index
204
  result_index = state['annotation_index']
205
 
206
  set_progress = lambda pct, msg: progress(pct, desc=msg)
207
 
208
+ if state['frame_index'] == 0:
209
+ if set_progress: set_progress(0, "Loading Frames")
210
+ dataloader, annotation_dataset = create_dataloader_aris(result["aris_input"][result_index], BEAM_WIDTH_DIR, None)
211
+
212
+ # Check that frames remain to be loaded
213
+ if state['frame_index'] < len(result['json_result'][result_index]['frames']):
214
+
215
+ # load frames and annotation
216
+ annotation_info, state['frame_index'] = init_frames(annotation_dataset, result['json_result'][result_index], state['frame_index'], gp=set_progress)
217
+
218
+ # save as html element
219
+ annotation_storage = "<p id='annotation_info' style='display:none'>" + json.dumps(annotation_info) + "</p>"
220
+
221
+ return {
222
+ annotation_editor: gr.update(),
223
+ annotation_progress: gr.update(value=annotation_storage)
224
+ }
225
+
226
+ # If complete, start annotation editor
227
+
228
  annotation_html = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
+ # Header
231
+ annotation_html += "<div id='annotation_header'>"
232
+ annotation_html += " <h1 id='annotation_frame_nbr'>Frame 0/100</h1>"
233
+ annotation_html += " <p id='annotation_edited'>(edited)</p>"
234
+ annotation_html += "</div>"
235
+
236
+ # Annotation Body
237
+ annotation_html += "<div style='display:flex'>"
238
+ annotation_html += " <canvas id='canvas' style='width:50%' onmousedown='mouse_down(event)' onmousemove='mouse_move(event)' onmouseup='mouse_up()' onmouseleave='mouse_up()'></canvas>"
239
+ annotation_html += " <div id='annotation_display' style='width:50%'></div>"
240
+ annotation_html += "</div>"
241
+
242
+ # Dummy objects
243
+ annotation_html += "<img id='annotation_img' onload='draw()' style='display:none'></img>"
244
+ annotation_html += "<!--" + str(np.random.rand()) + "-->"
245
+
246
+ return {
247
+ annotation_editor: gr.update(value=annotation_html, visible=True),
248
+ annotation_progress: gr.update(visible=False)
249
+ }
250
 
251
 
252
  components = {}
 
323
  # Add annotation editor component
324
  annotation_editor = gr.HTML("", visible=False)
325
 
326
+ annotation_storage = gr.HTML("", visible=False)
327
+
328
  # Event listener for opening annotation
329
+ annotation_progress.change(load_annotation, annotation_progress, [annotation_editor, annotation_progress], _js="""
330
+ () => {
331
+ info_string = document.getElementById("annotation_info").innerHTML;
332
+ info = JSON.parse(info_string);
333
+ console.log(info)
334
+ if (info.length == 0) {
335
+ window.annotation_info = [];
336
+ return false;
337
+ }
338
+ window.annotation_info = window.annotation_info.concat(info)
339
+ console.log(window.annotation_info)
340
+ return true;
341
+ }
342
+ """)
343
 
344
  # Event listener for running javascript defined in 'annotation_editor.js'
345
  with open('gradio_scripts/annotation_editor.js', 'r') as f:
gradio_scripts/annotation_editor.js CHANGED
@@ -17,7 +17,8 @@
17
 
18
 
19
  window.init = () => {
20
- window.frames = JSON.parse(document.getElementById("annotation_info").innerHTML);
 
21
  window.frame_index = 0;
22
 
23
  document.removeEventListener('keydown', keydown);
@@ -51,8 +52,8 @@
51
  window.dragging = false;
52
 
53
  // Load frame image
54
- const frame_img = frame['frame'];
55
- document.getElementById("annotation_img").src = "annotation_frame_dir/" + frame_index + ".jpg";
56
  // Draw function is called by this element using the onloaded callback
57
 
58
  document.getElementById("annotation_frame_nbr").innerHTML = "Frame " + window.frame_index + "/" + window.frames.length;
 
17
 
18
 
19
  window.init = () => {
20
+ window.frames = window.annotation_info;
21
+ console.log(window.frames);
22
  window.frame_index = 0;
23
 
24
  document.removeEventListener('keydown', keydown);
 
52
  window.dragging = false;
53
 
54
  // Load frame image
55
+ const frame_img = frame['base64'];
56
+ document.getElementById("annotation_img").src = "data:image/jpeg;base64," + frame_img;
57
  // Draw function is called by this element using the onloaded callback
58
 
59
  document.getElementById("annotation_frame_nbr").innerHTML = "Frame " + window.frame_index + "/" + window.frames.length;
gradio_scripts/annotation_handler.py CHANGED
@@ -1,5 +1,3 @@
1
- from dataloader import create_dataloader_aris
2
- from aris import BEAM_WIDTH_DIR
3
  import json
4
  import cv2
5
  import base64
@@ -7,7 +5,7 @@ import base64
7
  VIDEO_HEIGHT = 700
8
 
9
 
10
- def init_frames(video, preds, gp=None):
11
  """Load frames for annotation editing
12
 
13
 
@@ -21,10 +19,6 @@ def init_frames(video, preds, gp=None):
21
  )
22
  })
23
  """
24
-
25
- if gp: gp(0, "Loading Frames")
26
-
27
- dataloader, dataset = create_dataloader_aris(video, BEAM_WIDTH_DIR, None)
28
  images = dataset.didson.load_frames(start_frame=0, end_frame=1)
29
 
30
  # assumes all frames the same size
@@ -40,17 +34,21 @@ def init_frames(video, preds, gp=None):
40
  if gp: gp(0, "Extracting Frames")
41
  if len(preds['frames']):
42
 
43
- for i, frame_info in enumerate(preds['frames']):
44
- if gp: gp(i/len(preds['frames']), "Extracting Frames")
 
45
 
46
  # Extract frames
47
  img_raw = dataset.didson.load_frames(start_frame=i, end_frame=i+1)[0]
48
  image = cv2.resize(cv2.cvtColor(img_raw, cv2.COLOR_GRAY2BGR), (w, h))
49
- cv2.imwrite("annotation_frame_dir/" + str(i) + ".jpg", image)
 
 
50
 
51
  # Extract annotations
52
  frame = {
53
  'annotations': [],
 
54
  }
55
  for fish in frame_info['fish']:
56
  xmin, ymin, xmax, ymax = fish['bbox']
@@ -66,5 +64,5 @@ def init_frames(video, preds, gp=None):
66
  })
67
  annotations.append(frame)
68
 
69
- return annotations
70
 
 
 
 
1
  import json
2
  import cv2
3
  import base64
 
5
  VIDEO_HEIGHT = 700
6
 
7
 
8
+ def init_frames(dataset, preds, index, gp=None):
9
  """Load frames for annotation editing
10
 
11
 
 
19
  )
20
  })
21
  """
 
 
 
 
22
  images = dataset.didson.load_frames(start_frame=0, end_frame=1)
23
 
24
  # assumes all frames the same size
 
34
  if gp: gp(0, "Extracting Frames")
35
  if len(preds['frames']):
36
 
37
+ end_index = min(index+1000, len(preds['frames']))
38
+ for i, frame_info in enumerate(preds['frames'][index:end_index]):
39
+ if gp: gp((index + i)/len(preds['frames']), "Extracting Frames")
40
 
41
  # Extract frames
42
  img_raw = dataset.didson.load_frames(start_frame=i, end_frame=i+1)[0]
43
  image = cv2.resize(cv2.cvtColor(img_raw, cv2.COLOR_GRAY2BGR), (w, h))
44
+ #cv2.imwrite("annotation_frame_dir/" + str(i) + ".jpg", image)
45
+ retval, buffer = cv2.imencode('.jpg', image)
46
+ b64 = base64.b64encode(buffer).decode("utf-8")
47
 
48
  # Extract annotations
49
  frame = {
50
  'annotations': [],
51
+ 'base64': b64
52
  }
53
  for fish in frame_info['fish']:
54
  xmin, ymin, xmax, ymax = fish['bbox']
 
64
  })
65
  annotations.append(frame)
66
 
67
+ return annotations, end_index
68