def predict(image,the_net):
inputs = []
try:
tmp_input = image
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[11:11+128,11:11+128];
tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
raise Exception("Image damaged or illegal file format")
return
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = the_net.blobs['prob'].data[0]
return copy.deepcopy(scores)
python类require()的实例源码
predict_video_res10.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
extract_res10.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def predict(the_net,image):
inputs = []
if not os.path.exists(image):
raise Exception("Image path not exist")
return
try:
tmp_input = cv2.imread(image)
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[11:11+128,11:11+128]
tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
#raise Exception("Image damaged or illegal file format")
return None
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = copy.deepcopy(the_net.blobs['feature'].data)
return scores
test_vgg.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def predict(image,the_net):
inputs = []
try:
tmp_input = image
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[13:13+224,13:13+224];
tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
raise Exception("Image damaged or illegal file format")
return
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = the_net.blobs['prob'].data[0]
return copy.deepcopy(scores)
test_res10.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def predict(image,the_net):
inputs = []
try:
tmp_input = image
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[11:11+128,11:11+128];
tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
raise Exception("Image damaged or illegal file format")
return
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = the_net.blobs['prob'].data[0]
return copy.deepcopy(scores)
extract_emotion.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def predict(the_net,image):
inputs = []
if not os.path.exists(image):
raise Exception("Image path not exist")
return
try:
tmp_input = cv2.imread(image)
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[13:13+224,13:13+224]
#tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
#raise Exception("Image damaged or illegal file format")
return None
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = copy.deepcopy(the_net.blobs['fc6'].data)
return scores
predict_video.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 33
收藏 0
点赞 0
评论 0
def predict(image,the_net):
inputs = []
try:
tmp_input = image
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[13:13+224,13:13+224];
tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
raise Exception("Image damaged or illegal file format")
return
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = the_net.blobs['prob'].data[0]
return copy.deepcopy(scores)
test_afew_face_vgg.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def predict(image,the_net):
inputs = []
try:
tmp_input = image
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[13:13+224,13:13+224];
tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
raise Exception("Image damaged or illegal file format")
return
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = the_net.blobs['prob'].data[0]
return copy.deepcopy(scores)
extract_emotion_bak.py 文件源码
项目:EmotiW-2017-Audio-video-Emotion-Recognition
作者: xujinchang
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def predict(the_net,image):
inputs = []
if not os.path.exists(image):
raise Exception("Image path not exist")
return
try:
tmp_input = cv2.imread(image)
tmp_input = cv2.resize(tmp_input,(SIZE,SIZE))
tmp_input = tmp_input[13:13+224,13:13+224]
tmp_input = np.subtract(tmp_input,mean)
tmp_input = tmp_input.transpose((2, 0, 1))
tmp_input = np.require(tmp_input, dtype=np.float32)
except Exception as e:
#raise Exception("Image damaged or illegal file format")
return None
the_net.blobs['data'].reshape(1, *tmp_input.shape)
the_net.reshape()
the_net.blobs['data'].data[...] = tmp_input
the_net.forward()
scores = copy.deepcopy(the_net.blobs['fc6'].data)
return scores
def _propagate_boxes(boxes, annot_proto, frame_id):
pred_boxes = []
annots = []
for annot in annot_proto['annotations']:
for idx, box in enumerate(annot['track']):
if box['frame'] == frame_id and len(annot['track']) > idx + 1:
gt1 = box['bbox']
gt2 = annot['track'][idx+1]['bbox']
delta = bbox_transform(np.asarray([gt1]), np.asarray([gt2]))
annots.append((gt1, delta))
gt1 = [annot[0] for annot in annots]
overlaps = bbox_overlaps(np.require(boxes, dtype=np.float),
np.require(gt1, dtype=np.float))
assert len(overlaps) == len(boxes)
for gt_overlaps, box in zip(overlaps, boxes):
max_overlap = np.max(gt_overlaps)
max_gt = np.argmax(gt_overlaps)
if max_overlap < 0.5:
pred_boxes.append(box)
else:
delta = annots[max_gt][1]
pred_boxes.append(bbox_transform_inv(np.asarray([box]), delta)[0].tolist())
return pred_boxes
def epoch_to_epoch16(self, epoch):
"""
Converts a CDF EPOCH to a CDF EPOCH16 value
Parameters
==========
epoch : double
EPOCH to convert. Lists and numpy arrays are acceptable.
Returns
=======
out : (double, double)
EPOCH16 corresponding to epoch
"""
e = numpy.require(epoch, numpy.float64)
s = numpy.trunc(e / 1000.0)
#ugly numpy stuff, probably a better way....
res = numpy.hstack((s, (e - s * 1000.0) * 1e9))
if len(res) <= 2:
return res
newshape = list(res.shape[0:-2])
newshape.append(res.shape[-1] // 2)
newshape.append(2)
return numpy.rollaxis(res.reshape(newshape), -1, -2)
def epoch16_to_epoch(self, epoch16):
"""
Converts a CDF EPOCH16 to a CDF EPOCH value
Parameters
==========
epoch16 : (double, double)
EPOCH16 to convert. Lists and numpy arrays are acceptable.
LAST dimension should be 2: the two pairs of EPOCH16
Returns
=======
out : double
EPOCH corresponding to epoch16
"""
e = numpy.require(epoch16, numpy.float64)
return e[..., 0] * 1000.0 + numpy.round(e[..., 1] / 1e9)
def create_array(self):
"""Creates a numpy array to hold the data from this slice
Returns
=======
out : numpy.array
array sized, typed, and dimensioned to hold data from
this slice
"""
counts = self.counts
degen = self.degen
if self.column:
counts = self.reorder(counts)
degen = self.reorder(degen)
#TODO: Forcing C order for now, revert to using self.column later
array = numpy.empty(
[counts[i] for i in range(len(counts)) if not degen[i]],
self.zvar._np_type(), order='C')
return numpy.require(array, requirements=('C', 'A', 'W'))
def unique_rows(A, return_index=False, return_inverse=False):
"""
Similar to MATLAB's unique(A, 'rows'), this returns B, I, J
where B is the unique rows of A and I and J satisfy
A = B[J,:] and B = A[I,:]
Returns I if return_index is True
Returns J if return_inverse is True
"""
A = np.require(A, requirements='C')
assert A.ndim == 2, "array must be 2-dim'l"
B = np.unique(A.view([('', A.dtype)]*A.shape[1]),
return_index=return_index,
return_inverse=return_inverse)
if return_index or return_inverse:
return (B[0].view(A.dtype).reshape((-1, A.shape[1]), order='C'),) \
+ B[1:]
else:
return B.view(A.dtype).reshape((-1, A.shape[1]), order='C')
def test_fft(backend, batch, x, y, z):
b = backend()
N = (z, y, x, batch)
v = np.random.rand(*N) + 1j*np.random.rand(*N)
v = np.require(v, dtype=np.dtype('complex64'), requirements='F')
ax = (0,1,2)
# check forward
w_exp = np.fft.fftn(v, axes=ax)
v_d = b.copy_array(v)
u_d = b.copy_array(v)
b.fftn(u_d, v_d)
w_act = u_d.to_host()
np.testing.assert_allclose(w_act, w_exp, atol=1e-2)
# check adjoint
v_exp = np.fft.ifftn(w_act, axes=ax) * (x*y*z)
v_d = b.copy_array(w_act)
u_d = b.copy_array(w_act)
b.ifftn(u_d, v_d)
v_act = u_d.to_host()
np.testing.assert_allclose(v_act, v_exp, atol=1e-2)
# check unitary
np.testing.assert_allclose(v, v_act / (x*y*z), atol=1e-6)
def test_csr_matrix(backend, M, N, K, density):
b = backend()
c = np.dtype('complex64')
A = indigo.util.randM(M, N, density)
A_d = b.csr_matrix(b, A)
# forward
x = (np.random.rand(N,K) + 1j * np.random.rand(N,K))
x = np.require(x, dtype=c, requirements='F')
y_exp = A.astype(c) * x
x_d = b.copy_array(x)
y_d = b.zero_array(y_exp.shape, x.dtype)
A_d.forward(y_d, x_d)
y_act = y_d.to_host()
np.testing.assert_allclose(y_exp, y_act, atol=1e-5)
# adjoint
x = (np.random.rand(M,K) + 1j * np.random.rand(M,K))
x = np.require(x, dtype=c, requirements='C')
y_exp = A.H.astype(c) * x
x_d = b.copy_array(x)
y_d = b.zero_array(y_exp.shape, x.dtype)
A_d.adjoint(y_d, x_d)
y_act = y_d.to_host()
np.testing.assert_allclose(y_exp, y_act, atol=1e-5)
def test_blas_axpby(backend, n, alpha, alpha_i, beta):
b = backend()
x = (np.random.rand(n) + 1j * np.random.rand(n))
y = (np.random.rand(n) + 1j * np.random.rand(n))
x = np.require(x, dtype=np.dtype('complex64'), requirements='F')
y = np.require(y, dtype=np.dtype('complex64'), requirements='F')
x_d = b.copy_array(x)
y_d = b.copy_array(y)
alpha = alpha + 1j*alpha_i
y_exp = beta*y + alpha*x
b.axpby(beta, y_d, alpha, x_d)
y_act = y_d.to_host()
np.testing.assert_allclose(y_exp, y_act, atol=1e-6)
def write(fname, data, psz=1, origin=None, fast=False):
""" Writes a MRC file. The header will be blank except for nx,ny,nz,datatype=2 for float32.
data should be (nx,ny,nz), and will be written in Fortran order as MRC requires."""
header = np.zeros(256, dtype=np.int32) # 1024 byte header
header_f = header.view(np.float32)
header[:3] = data.shape # nx, ny, nz
header[3] = 2 # mode, 2 = float32 datatype
header[7:10] = data.shape # mx, my, mz (grid size)
header_f[10:13] = [psz * i for i in data.shape] # xlen, ylen, zlen
header_f[13:16] = 90.0 # CELLB
header[16:19] = [1, 2, 3] # axis order
if not fast:
header_f[19:22] = [data.min(), data.max(), data.mean()] # data stats
if origin is None:
header_f[49:52] = [0, 0, 0]
elif origin is "center":
header_f[49:52] = [psz * i / 2 for i in data.shape]
else:
header_f[49:52] = origin
header[52] = 542130509 # 'MAP ' chars
header[53] = 16708
with open(fname, 'wb') as f:
header.tofile(f)
np.require(np.reshape(data, (-1,), order='F'), dtype=np.float32).tofile(f)
def append(fname, data):
with open(fname, 'r+b') as f:
nx, ny, nz = np.fromfile(f, dtype=np.int32, count=3) # First 12 bytes of stack.
f.seek(36) # First byte of zlen.
zlen = np.fromfile(f, dtype=np.float32, count=1)
if data.shape[0] != nx or data.shape[1] != ny:
raise Exception
f.seek(0, os.SEEK_END)
np.require(np.reshape(data, (-1,), order='F'), dtype=np.float32).tofile(f)
# Update header after new data is written.
apix = zlen / nz
nz += data.shape[2]
zlen += apix * data.shape[2]
f.seek(8)
nz.tofile(f)
f.seek(36)
zlen.tofile(f)
def deprocess_net_image(image):
image = image.copy() # use copy don't modify destructively
image = image[::-1] # BGR to RGB
image = image.transpose(1,2,0) # CHW to HCW
image += [123,117,104] # undo mean subtraction
# clamp values in [0,255]
image[image < 0], image[image > 255] = 0 , 255
# round and cast form float32 to uint8
image = np.round(image)
image = np.require(image,dtype=np.uint8)
return image
# Load the 1000 ImageNet labels from
# ilsvrc12/synset_words.txt, and the 5 style labels from finetune_flickr_style/style_names.txt.
# Load ImageNet labels to imagenet_labels
def _KeenerMatrix(self, A, C, regularization, func, epsilon):
"""func is a regularization function imposed on every element of matrix.
"""
# Apply Laplace Law
B = A+A.T+2;
A = A+1
A = A/B
# Regularization
if func is not None:
h = np.frompyfunc(func, 1, 1)
A = np.require(h(A), dtype=np.float32)
# divide by contest number
C = C+C.T
c = np.sum(C, axis=1)
if regularization:
A = A/np.expand_dims(c, axis=1)
A[C==0]=0
if epsilon is not None:
A += epsilon*np.ones(A.shape, A.dtype)
return A
def __init__(self, table=None, filename=''):
"""
table: the pandas DataFrame that records rankable objects competition
record
filename: the hdf5 filename that stores the DataFrame. The DataFrame
must be indexed by 'item_pair_rate'.
"""
if table is None:
table = pd.read_hdf(filename, "item_pair_rate")
table = table[['primary','secondary','rate1','rate2','weight']]
self.table = table
# itemid to index table
idx = self._extract_list(self.table)
self.itemlist = idx
temptable = table.iloc[:,:2].values
pair = np.fromfunction(np.vectorize(lambda i, j: idx[temptable[i,j]]),
temptable.shape)
pair = np.require(pair, dtype=np.int32)
self.pair = pair
def RateDifferenceVoteMatrix(self):
"""This function outputs only Point Difference Matrix.
It can be ensured that every element of the matrix are not less than 0
"""
idx = self.itemlist
table = self.table
icnt = len(idx)
# allocate space for computing
D = np.zeros((icnt, icnt), dtype=np.float32)
pair = self.pair
fast_rate_diff_vote_matrix_build(pair,
np.require(table.iloc[:,2:].values, dtype=np.float32),
D)
return D
def SimpleDifferenceVoteMatrix(self):
"""This function outputs only Simple Difference Vote Matrix.
"""
idx = self.itemlist
table = self.table
icnt = len(idx)
# allocate space for computing
D = np.zeros((icnt, icnt), dtype=np.float32)
pair = self.pair
fast_simple_diff_vote_matrix_build(pair,
np.require(table.iloc[:,2:].values, dtype=np.float32),
D)
return D
def RateVoteMatrix(self):
"""This function outputs only Simple Difference Vote Matrix.
"""
idx = self.itemlist
table = self.table
icnt = len(idx)
# allocate space for computing
D = np.zeros((icnt, icnt), dtype=np.float32)
pair = self.pair
fast_rate_vote_matrix_build(pair,
np.require(table.iloc[:,2:].values, dtype=np.float32),
D)
return D
def MasseyVector(self):
"""This function produces X'Wy
"""
idx = self.itemlist
table = self.table
pair = self.pair
j = np.ravel(pair)
i = np.repeat(np.arange(table.shape[0], dtype=np.int32), 2, axis=0)
data = np.array([[1,-1]],dtype=np.float32)
data = np.ravel(np.repeat(data, table.shape[0], axis=0))
X = coo_matrix((data, (i, j)), shape=(table.shape[0], len(idx)))
X = X.tocsr()
W = np.require(table.iloc[:,4].values, np.float32)
y = table.iloc[:, 2].values - table.iloc[:, 3].values;
Wy=np.multiply(W, y)
return X.T*Wy
def isIntegral(solution):
return np.all(solution == np.require(solution, dtype = 'int_'))
def filter(self, filter_ind):
filter_ind = np.require(filter_ind, dtype = 'bool')
new = self.copy()
new.objvals = self.objvals[filter_ind]
new.solutions = self.solutions[filter_ind]
return new
def generate_binary_data(n_rows = 1000000, n_cols = 20):
X = np.random.randint(low=0, high=2, size=(n_rows, n_cols))
Y = np.random.randint(low=0, high=2, size=(n_rows, 1))
pos_ind = Y == 1
Y[~pos_ind] = -1
Z = X * Y
Z = np.require(Z, requirements=['F'], dtype=np.float64)
return Z
def generate_integer_model(n_cols = 20, rho_ub = 100, rho_lb = -100, sparse_pct = 0.5):
rho = np.random.randint(low=rho_lb, high=rho_ub, size=n_cols)
rho = np.require(rho, dtype=Z.dtype, requirements=['F'])
nnz_count = int(sparse_pct * np.floor(n_cols / 2))
set_to_zero = np.random.choice(range(0, n_cols), size=nnz_count, replace=False)
rho[set_to_zero] = 0.0
return rho
def is_integer(rho):
"""
checks if numpy array is an integer vector
Parameters
----------
rho
Returns
-------
"""
return np.array_equal(rho, np.require(rho, dtype=np.int_))