Spaces:
Runtime error
Runtime error
File size: 10,407 Bytes
7e4e0ac 738002f 7e4e0ac f7827d6 7e4e0ac b39c376 f7827d6 7e4e0ac |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import collections as mc
import matplotlib.pyplot as plt
import math
from aris import BEAM_WIDTH_DIR
import cv2
from dataloader import create_dataloader_aris
STANDARD_FIG_SIZE = (16, 9)
OUT_PDF_FILE_NAME = 'multipage_pdf.pdf'
def make_pdf(i, state, result, table_headers):
fish_info = result["fish_info"][i]
fish_table = result["fish_table"][i]
json_result = result['json_result'][i]
metadata = json_result['metadata']
aris_input = result["aris_input"][i]
with PdfPages(OUT_PDF_FILE_NAME) as pdf:
plt.rcParams['text.usetex'] = False
generate_title_page(pdf, metadata, state)
generate_global_result(pdf, fish_info)
generate_fish_list(pdf, table_headers, fish_table)
dataset = None
if (aris_input is not None):
dataloader, dataset = create_dataloader_aris(aris_input, BEAM_WIDTH_DIR, None)
for i, fish in enumerate(json_result['fish']):
calculate_fish_paths(json_result, dataset, i)
draw_combined_fish_graphs(pdf, json_result)
for i, fish in enumerate(json_result['fish']):
generate_fish_tracks(pdf, json_result, i)
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = 'Oskar Åström'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = ''
d['CreationDate'] = datetime.datetime.today()
d['ModDate'] = datetime.datetime.today()
def generate_title_page(pdf, metadata, state):
# set up figure that will be used to display the opening banner
fig = plt.figure(figsize=STANDARD_FIG_SIZE)
plt.axis('off')
title_font_size = 40
minor_font_size = 20
# stuff to be printed out on the first page of the report
plt.text(0.5,-0.5,f'{metadata["FILE_NAME"].split("/")[-1]}',fontsize=title_font_size, horizontalalignment='center')
plt.text(0,1,f'Duration: {metadata["TOTAL_TIME"]}',fontsize=minor_font_size)
plt.text(0,1.5,f'Frames: {metadata["TOTAL_FRAMES"]}',fontsize=minor_font_size)
plt.text(0,2,f'Frame Rate: {metadata["FRAME_RATE"]}',fontsize=minor_font_size)
plt.text(0.5,1,f'Time of filming: {metadata["DATE"]} ({metadata["START"]} - {metadata["END"]})',fontsize=minor_font_size)
plt.text(0.5,1.5,f'Web app version: {state["version"]}',fontsize=minor_font_size)
plt.text(1.1,4.5,f'PDF generated on {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}',fontsize=minor_font_size, horizontalalignment='right')
plt.ylim([-1, 4])
plt.xlim([0, 1])
plt.gca().invert_yaxis()
pdf.savefig(fig)
plt.close(fig)
def generate_global_result(pdf, fish_info):
# set up figure that will be used to display the opening banner
fig = plt.figure(figsize=STANDARD_FIG_SIZE)
plt.axis('off')
# stuff to be printed out on the first page of the report
minor_font_size = 18
headers = ["Result", "Camera Info", "Hyperparameters"]
info_col_1 = []
info_col_2 = []
info_col = info_col_1
row_state = -1
for row in fish_info:
if row_state >= 0:
info_col.append([row[0].replace("**","").replace("_", " ").lower(), row[1], 'normal'])
if (row[0] == "****"):
row_state += 1
if row_state == 2: info_col = info_col_2
info_col.append([headers[row_state], "", 'bold'])
for row_i, row in enumerate(info_col_1):
h = -1 + 5*row_i/len(info_col_1)
plt.text(0, h, row[0], fontsize=minor_font_size, weight=row[2])
plt.text(0.25, h, row[1], fontsize=minor_font_size, weight=row[2])
for row_i, row in enumerate(info_col_2):
h = -1 + 5*row_i/len(info_col_2)
plt.text(0.5, h, row[0], fontsize=minor_font_size, weight=row[2])
plt.text(0.75, h, row[1], fontsize=minor_font_size, weight=row[2])
plt.ylim([-1, 4])
plt.xlim([0, 1])
plt.gca().invert_yaxis()
pdf.savefig(fig)
plt.close(fig)
def generate_fish_list(pdf, table_headers, fish_table):
# set up figure that will be used to display the opening banner
fig = plt.figure(figsize=STANDARD_FIG_SIZE)
plt.axis('off')
# stuff to be printed out on the first page of the report
title_font_size = 40
header_font_size = 12
body_font_size = 20
# Title
plt.text(0.5,-1.3,f'{"Identified Fish"}',fontsize=title_font_size, horizontalalignment='center', weight='bold')
# Identified fish
row_h = 0.25
col_start = 0
row_l = 1
dropout_i = None
for col_i, col in enumerate(table_headers):
x = col_start + row_l*(col_i+0.5)/len(table_headers)
if col == "TOTAL": col = "ID"
if col == "DETECTION_DROPOUT":
col = "frame drop rate"
dropout_i = col_i
col = col.lower().replace("_", " ")
plt.text(x, -1, col, fontsize=header_font_size, horizontalalignment='center', weight="bold")
plt.plot([col_start*2, -col_start*2 + row_l], [-1 + 0.05, -1 + 0.05], color='black')
for row_i, row in enumerate(fish_table):
y = -1 + (row_i+1)*row_h
plt.plot([col_start*2, -col_start*2 + row_l], [y+0.05, y+0.05], color='black')
for col_i, col in enumerate(row):
x = col_start + row_l*(col_i+0.5)/len(row)
if (col_i == dropout_i and type(col) is not str):
col = str(int(col*100)) + "%"
elif type(col) == float:
col = "{:.4f}".format(col)
plt.text(x, y, col, fontsize=body_font_size, horizontalalignment='center')
plt.ylim([-1, 4])
plt.xlim([0, 1])
plt.gca().invert_yaxis()
pdf.savefig(fig)
plt.close(fig)
def calculate_fish_paths(result, dataset, id):
fish = result['metadata']['FISH'][id]
start_frame = fish['START_FRAME']
end_frame = fish['END_FRAME']
# Extract base frame (first frame for that fish)
w, h = 1, 2
img = None
if (dataset is not None):
images = dataset.didson.load_frames(start_frame=start_frame, end_frame=start_frame+1)
img = images[0]
frame_height = 2
scale_factor = frame_height / h
h = frame_height
w = int(scale_factor*w)
fish['base_frame'] = img
fish['scaled_frame_size'] = (w, h)
# Find frames for this fish
bboxes = []
for frame in result['frames'][start_frame:end_frame+1]:
bbox = None
for ann in frame['fish']:
if ann['fish_id'] == id+1:
bbox = ann
bboxes.append(bbox)
# Calculate tracks through frames
missed = 0
X = []
Y = []
V = []
certainty = []
for bbox in bboxes:
if bbox is not None:
# Find fish centers
x = (bbox['bbox'][0] + bbox['bbox'][2])/2
y = (bbox['bbox'][1] + bbox['bbox'][3])/2
# Calculate velocity
v = None
if len(X) > 0:
last_x = X[-1]
last_y = Y[-1]
dx = result['image_meter_width']*(last_x - x)/(missed+1)
dy = result['image_meter_height']*(last_y - y)/(missed+1)
v = math.sqrt(dx*dx + dy*dy)
# Interpolate over missing frames
if missed > 0:
for i in range(missed):
p = (i+1)/(missed+1)
X.append(last_x*(1-p) + p*x)
Y.append(last_y*(1-p) + p*y)
V.append(v)
certainty.append(False)
# Append new track frame
X.append(x)
Y.append(y)
if v is not None: V.append(v)
certainty.append(True)
missed = 0
else:
missed += 1
fish['path'] = {
'X': X,
'Y': Y,
'certainty': certainty,
'V': V
}
def draw_combined_fish_graphs(pdf, result):
vel = []
log_vel = []
for fish in result['metadata']['FISH']:
vel += fish['path']['V']
log_vel += [math.log(v) for v in fish['path']['V']]
fig, axs = plt.subplots(2, 2, sharey=True, figsize=STANDARD_FIG_SIZE)
axs[0,0].hist(log_vel, bins=20)
axs[0,0].set_title('Fish Log-Velocities between frames')
axs[0,0].set_xlabel("Log-Velocity (log(m/frame))")
axs[0,1].hist(vel, bins=20)
axs[0,1].set_title('Fish Velocities between frames')
axs[0,1].set_xlabel("Velocity (m/frame)")
pdf.savefig(fig)
plt.close(fig)
def generate_fish_tracks(pdf, result, id):
fish = result['metadata']['FISH'][id]
start_frame = fish['START_FRAME']
end_frame = fish['END_FRAME']
fig, ax = plt.subplots(figsize=STANDARD_FIG_SIZE)
plt.axis('off')
w, h = fish['scaled_frame_size']
if (fish['base_frame'] is not None):
img = fish['base_frame']
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
plt.imshow(img, extent=(0, h, 0, w), cmap=plt.colormaps['Greys'])
# Title
plt.text(h/2,1.1,f'Fish {id+1} (frames {start_frame}-{end_frame})',fontsize=40, color="red", horizontalalignment='center', zorder=5)
X = fish['path']['X']
Y = fish['path']['Y']
certainty = fish['path']['certainty']
plt.text(h*(1-Y[0]), w*(1-X[0]), "Start", fontsize=15, weight="bold")
plt.text(h*(1-Y[-1]), w*(1-X[-1]), "End", fontsize=15, weight="bold")
colors = [""]
for i in range(1, len(X)):
certain = certainty[i]
fully_certain = certain
half_certain = certain
if i > 0:
fully_certain &= certainty[i-1]
half_certain |= certainty[i-1]
#color = 'yellow' if certain else 'orangered'
#plt.plot(h*(1-y), w*(1-x), marker='o', markersize=3, color=color, zorder=3)
col = 'yellow' if fully_certain else ('darkorange' if half_certain else 'orangered')
colors.append(col)
ax.plot([h*(1-Y[i-1]), h*(1-Y[i])], [w*(1-X[i-1]), w*(1-X[i])], color=col, linewidth=1)
print(len(X))
print(len(Y))
print(len(colors))
for i in range(1, len(X)):
ax.plot(h*(1-Y[i]), w*(1-X[i]), color=colors[i], marker='o', markersize=3)
plt.ylim([0, w])
plt.xlim([0, h])
pdf.savefig(fig)
plt.close(fig) |