Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
dbolya
GitHub Repository: dbolya/tide
Path: blob/master/tidecv/functions.py
110 views
1
import matplotlib.pyplot as plt
2
import numpy as np
3
4
import os, sys
5
6
def mean(arr:list):
7
if len(arr) == 0:
8
return 0
9
return sum(arr) / len(arr)
10
11
def find_first(arr:np.array) -> int:
12
""" Finds the index of the first instance of true in a vector or None if not found. """
13
if len(arr) == 0:
14
return None
15
idx = arr.argmax()
16
17
# Numpy argmax will return 0 if no True is found
18
if idx == 0 and not arr[0]:
19
return None
20
21
return idx
22
23
def isiterable(x):
24
try:
25
iter(x)
26
return True
27
except:
28
return False
29
30
def recursive_sum(x):
31
if isinstance(x, dict):
32
return sum([recursive_sum(v) for v in x.values()])
33
elif isiterable(x):
34
return sum([recursive_sum(v) for v in x])
35
else:
36
return x
37
38
def apply_messy(x:list, func):
39
return [([func(y) for y in e] if isiterable(e) else func(e)) for e in x]
40
41
def apply_messy2(x:list, y:list, func):
42
return [[func(i, j) for i, j in zip(a, b)] if isiterable(a) else func(a, b) for a, b in zip(x, y)]
43
44
def multi_len(x):
45
try:
46
return len(x)
47
except TypeError:
48
return 1
49
50
def unzip(l):
51
return map(list, zip(*l))
52
53
54
def points(bbox):
55
bbox = [int(x) for x in bbox]
56
return (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3])
57
58
def nonepack(t):
59
if t is None:
60
return None, None
61
else:
62
return t
63
64
65
class HiddenPrints:
66
""" From https://stackoverflow.com/questions/8391411/suppress-calls-to-print-python """
67
68
def __enter__(self):
69
self._original_stdout = sys.stdout
70
sys.stdout = open(os.devnull, 'w')
71
72
def __exit__(self, exc_type, exc_val, exc_tb):
73
sys.stdout.close()
74
sys.stdout = self._original_stdout
75
76
77
78
79
def toRLE(mask:object, w:int, h:int):
80
"""
81
Borrowed from Pycocotools:
82
Convert annotation which can be polygons, uncompressed RLE to RLE.
83
:return: binary mask (numpy 2D array)
84
"""
85
import pycocotools.mask as maskUtils
86
87
if type(mask) == list:
88
# polygon -- a single object might consist of multiple parts
89
# we merge all parts into one mask rle code
90
rles = maskUtils.frPyObjects(mask, h, w)
91
return maskUtils.merge(rles)
92
elif type(mask['counts']) == list:
93
# uncompressed RLE
94
return maskUtils.frPyObjects(mask, h, w)
95
else:
96
return mask
97
98
99
def polyToBox(poly:list):
100
""" Converts a polygon in COCO lists of lists format to a bounding box in [x, y, w, h]. """
101
102
xmin = 1e10
103
xmax = -1e10
104
ymin = 1e10
105
ymax = -1e10
106
107
for poly_comp in poly:
108
for i in range(len(poly_comp) // 2):
109
x = poly_comp[2*i + 0]
110
y = poly_comp[2*i + 1]
111
112
xmin = min(x, xmin)
113
xmax = max(x, xmax)
114
ymin = min(y, ymin)
115
ymax = max(y, ymax)
116
117
return [xmin, ymin, (xmax - xmin), (ymax - ymin)]
118
119