forked from xiaobai1217/MBMD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdnet_utils.py
76 lines (60 loc) · 2.35 KB
/
mdnet_utils.py
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
from scipy.misc import imresize
import numpy as np
def overlap_ratio(rect1, rect2):
'''
Compute overlap ratio between two rects
- rect: 1d array of [x,y,w,h] or
2d array of N x [x,y,w,h]
'''
if rect1.ndim==1:
rect1 = rect1[None,:]
if rect2.ndim==1:
rect2 = rect2[None,:]
left = np.maximum(rect1[:,0], rect2[:,0])
right = np.minimum(rect1[:,0]+rect1[:,2], rect2[:,0]+rect2[:,2])
top = np.maximum(rect1[:,1], rect2[:,1])
bottom = np.minimum(rect1[:,1]+rect1[:,3], rect2[:,1]+rect2[:,3])
intersect = np.maximum(0,right - left) * np.maximum(0,bottom - top)
union = rect1[:,2]*rect1[:,3] + rect2[:,2]*rect2[:,3] - intersect
iou = np.clip(intersect / union, 0, 1)
return iou
def crop_image(img, bbox, img_size=107, padding=16, valid=False):
x,y,w,h = np.array(bbox,dtype='float32')
half_w, half_h = w/2, h/2
center_x, center_y = x + half_w, y + half_h
if padding > 0:
pad_w = padding * w/img_size
pad_h = padding * h/img_size
half_w += pad_w
half_h += pad_h
img_h, img_w, _ = img.shape
min_x = int(center_x - half_w + 0.5)
min_y = int(center_y - half_h + 0.5)
max_x = int(center_x + half_w + 0.5)
max_y = int(center_y + half_h + 0.5)
if valid:
min_x = max(0, min_x)
min_y = max(0, min_y)
max_x = min(img_w, max_x)
max_y = min(img_h, max_y)
if min_x >=0 and min_y >= 0 and max_x <= img_w and max_y <= img_h:
cropped = img[min_y:max_y, min_x:max_x, :]
else:
min_x_val = max(0, min_x)
min_y_val = max(0, min_y)
max_x_val = min(img_w, max_x)
max_y_val = min(img_h, max_y)
cropped = 128 * np.ones((max_y-min_y, max_x-min_x, 3), dtype='uint8')
cropped[min_y_val-min_y:max_y_val-min_y, min_x_val-min_x:max_x_val-min_x, :] \
= img[min_y_val:max_y_val, min_x_val:max_x_val, :]
try:
scaled = imresize(cropped, (img_size, img_size))
except ValueError:
print "a"
return scaled
def extract_regions(image,samples,crop_size=107,padding=16,shuffle=False):
regions = np.zeros((samples.shape[0], crop_size,crop_size,3), dtype = 'uint8')
for t in range(samples.shape[0]):
regions[t] = crop_image(image,samples[t],crop_size,padding)
regions = regions - 128.
return regions