a b/helpers.py
1
import numpy as np
2
import matplotlib
3
from matplotlib import pyplot as plt
4
import cv2
5
from PIL import Image, ImageDraw
6
7
8
def pop_and_add(l, val, max_length):
9
    if len(l) == max_length:
10
        l.pop(0)
11
    l.append(val)
12
13
14
def last_ip(ips):
15
    for i, ip in enumerate(reversed(ips)):
16
        if ip is not None:
17
            return ip, len(ips) - i
18
19
def last_valid_hist(ips):
20
    for i,ip in enumerate(reversed(ips)):
21
        if valid_candidate_hist(ip):
22
            return ip
23
24
def dist(ip1, ip2):
25
    ip1 = ip1["keypoints"]
26
    ip2 = ip2["keypoints"]
27
    return np.sqrt(np.sum((ip1['N']-ip2['N'])**2 + (ip1['B']-ip2['B'])**2))
28
29
30
def move_figure(f, x, y):
31
    """Move figure's upper left corner to pixel (x, y)"""
32
    backend = matplotlib.get_backend()
33
    if backend == 'TkAgg':
34
        f.canvas.manager.window.wm_geometry("+%d+%d" % (x, y))
35
    elif backend == 'WXAgg':
36
        f.canvas.manager.window.SetPosition((x, y))
37
    else:
38
        # This works for QT and GTK
39
        # You can also use window.setGeometry
40
        f.canvas.manager.window.move(x, y)
41
42
def valid_candidate_hist(ip):
43
    if ip is not None:
44
        return ip["up_hist"] is not None
45
    else:
46
        return False
47
48
def dist_hist(ips1,ips2):
49
50
    ip1 = last_valid_hist(ips1)
51
    ip2 = last_valid_hist(ips2)
52
53
    uhist1 = ip1["up_hist"]
54
    uhist2 = ip2["up_hist"]
55
56
    assert uhist1 is not None
57
    assert uhist2 is not None
58
59
    assert type(uhist1) == np.ndarray
60
61
    return np.sum(np.absolute(uhist1-uhist2))
62
63
def get_hist(img, bbox, nbins=3):
64
65
    if not np.any(bbox):
66
        return None
67
68
    mask = Image.new('L', (img.shape[1], img.shape[0]), 0)
69
    ImageDraw.Draw(mask).polygon(list(bbox.flatten()), outline=1, fill=1)
70
    mask = np.array(mask)
71
    hist = cv2.calcHist([img], [0, 1], mask, [nbins, 2*nbins], [0, 180, 0, 256])
72
    cv2.normalize(hist, hist, alpha=1, norm_type=cv2.NORM_L1)
73
74
75
    return hist