python int32 binary_Python numpy.int32() 使用实例

本文通过多个示例详细介绍了如何在Python中使用numpy.int32()函数,涉及图像处理、数据处理和机器学习等多个场景。示例包括创建稀疏矩阵、绘制多边形框、初始化权重、序列到序列模型等操作。
摘要由CSDN通过智能技术生成

Example 1

def sparse_tuple_from(sequences, dtype=np.int32):

r"""Creates a sparse representention of ``sequences``.

Args:

* sequences: a list of lists of type dtype where each element is a sequence

Returns a tuple with (indices, values, shape)

"""

indices = []

values = []

for n, seq in enumerate(sequences):

indices.extend(zip([n]*len(seq), range(len(seq))))

values.extend(seq)

indices = np.asarray(indices, dtype=np.int64)

values = np.asarray(values, dtype=dtype)

shape = np.asarray([len(sequences), indices.max(0)[1]+1], dtype=np.int64)

return tf.SparseTensor(indices=indices, values=values, shape=shape)

Example 2

def draw_poly_box(frame, pts, color=[0, 255, 0]):

"""Draw polylines bounding box.

Parameters

----------

frame : OpenCV Mat

A given frame with an object

pts : numpy array

consists of bounding box information with size (n points, 2)

color : list

color of the bounding box, the default is green

Returns

-------

new_frame : OpenCV Mat

A frame with given bounding box.

"""

new_frame = frame.copy()

temp_pts = np.array(pts, np.int32)

temp_pts = temp_pts.reshape((-1, 1, 2))

cv2.polylines(new_frame, [temp_pts], True, color, thickness=2)

return new_frame

Example 3

def __init__(self, filename, target_map, classifier='svm'):

self.seed_ = 0

self.filename_ = filename

self.target_map_ = target_map

self.target_ids_ = (np.unique(target_map.keys())).astype(np.int32)

self.epoch_no_ = 0

self.st_time_ = time.time()

# Setup classifier

print('-------------------------------')

print('====> Building Classifier, setting class weights')

if classifier == 'svm':

self.clf_hyparams_ = {'C':[0.01, 0.1, 1.0, 10.0, 100.0], 'class_weight': ['balanced']}

self.clf_base_ = LinearSVC(random_state=self.seed_)

elif classifier == 'sgd':

self.clf_hyparams_ = {'alpha':[0.0001, 0.001, 0.01, 0.1, 1.0, 10.0], 'class_weight':['auto']} # 'loss':['hinge'],

self.clf_ = SGDClassifier(loss='log', penalty='l2', shuffle=False, random_state=self.seed_,

warm_start=True, n_jobs=-1, n_iter=1, verbose=4)

else:

raise Exception('Unknown classifier type %s. Choose from [sgd, svm, gradient-boosting, extra-trees]'

% classifier)

Example 4

def draw_flow(img, flow, step=16):

h, w = img.shape[:2]

y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1)

fx, fy = flow[y,x].T

m = np.bitwise_and(np.isfinite(fx), np.isfinite(fy))

lines = np.vstack([x[m], y[m], x[m]+fx[m], y[m]+fy[m]]).T.reshape(-1, 2, 2)

lines = np.int32(lines + 0.5)

vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

cv2.polylines(vis, lines, 0, (0, 255, 0))

for (x1, y1), (x2, y2) in lines:

cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)

return vis

Example 5

def draw_hulls(im, hulls):

assert(isinstance(hulls, list))

cv2.polylines(im, map(lambda hull: hull.astype(np.int32), hulls), 1, (0, 255, 0) if im.ndim == 3 else 255, thickness=1)

return im

Example 6

def visualize(self, vis, colored=True):

try:

tids = set(self.ids)

except:

return vis

for hid, hbox in izip(self.ids, self.bboxes):

cv2.rectangle(vis, (hbox[0], hbox[1]), (hbox[2], hbox[3]), (0,255,0), 1)

vis = super(BoundingBoxKLT, self).viz(vis, colored=colored)

# for tid, pts in self.tm_.tracks.iteritems():

# if tid not in tids: continue

# cv2.polylines(vis, [np.vstack(pts.items).astype(np.int32)[-4:]], False,

# (0,255,0), thickness=1)

# tl, br = np.int32(pts.latest_item)-2, np.int32(pts.latest_item)+2

# cv2.rectangle(vis, (tl[0], tl[1]), (br[0], br[1]), (0,255,0), -1)

# OpenCVKLT.draw_tracks(self, vis, colored=colored, max_track_length=10)

return vis

Example 7

def warpImage(src, theta, phi, gamma, scale, fovy):

halfFovy = fovy * 0.5

d = math.hypot(src.shape[1], src.shape[0])

sideLength = scale * d / math.cos(deg2Rad(halfFovy))

sideLength = np.int32(sideLength)

M = warpMatrix(src.shape[1], src.shape[0], theta, phi, gamma, scale, fovy)

dst = cv2.warpPerspective(src, M, (sideLength, sideLength))

mid_x = mid_y = dst.shape[0] // 2

target_x = target_y = src.shape[0] // 2

offset = (target_x % 2)

if len(dst.shape) == 3:

dst = dst[mid_y - target_y:mid_y + target_y + offset,

mid_x - target_x:mid_x + target_x + offset,

:]

else:

dst = dst[mid_y - target_y:mid_y + target_y + offset,

mid_x - target_x:mid_x + target_x + offset]

return dst

Example 8

def _load_data_graph(self):

"""

Loads the data graph consisting of the encoder and decoder input placeholders, Label (Target tip summary)

placeholders and the weights of the hidden layer of the Seq2Seq model.

:return: None

"""

# input

with tf.variable_scope("train_test", reuse=True):

# review input - Both original and reversed

self.enc_inp_fwd = [tf.placeholder(tf.int32, shape=(None,), name="input%i" % t)

for t in range(self.seq_length)]

self.enc_inp_bwd = [tf.placeholder(tf.int32, shape=(None,), name="input%i" % t)

for t in range(self.seq_length)]

# desired output

self.labels = [tf.placeholder(tf.int32, shape=(None,), name="labels%i" % t)

for t in range(self.seq_length)]

# weight of the hidden layer

self.weights = [tf.ones_like(labels_t, dtype=tf.float32)

for labels_t in self.labels]

# Decoder input: prepend some "GO" token and drop the final

# token of the encoder input

self.dec_inp = ([tf.zeros_like(self.labels[0], dtype=np.int32, name="GO")] + self.labels[:-1])

Example 9

def _load_data_graph(self):

"""

Loads the data graph consisting of the encoder and decoder input placeholders, Label (Target tip summary)

placeholders and the weights of the hidden layer of the Seq2Seq model.

:return: None

"""

# input

with tf.variable_scope("train_test", reuse=True):

self.enc_inp = [tf.placeholder(tf.int32, shape=(None,),

name="input%i" % t)

for t in range(self.seq_length)]

# desired output

self.labels = [tf.placeholder(tf.int32, shape=(None,),

name="labels%i" % t)

for t in range(self.seq_length)]

# weight of the hidden layer

self.weights = [tf.ones_like(labels_t, dtype=tf.float32)

for labels_t in self.labels]

# Decoder input: prepend some "GO" token and drop the final

# token of the encoder input

self.dec_inp = ([tf.zeros_like(self.labels[0], dtype=np.int32, name="GO")]

+ self.labels[:-1])

Example 10

def _load_data_graph(self):

"""

Loads the data graph consisting of the encoder and decoder input placeholders, Label (Target tip summary)

placeholders and the weights of the hidden layer of the Seq2Seq model.

:return: None

"""

# input

with tf.variable_scope("train_test", reuse=True):

self.enc_inp = [tf.placeholder(tf.int32, shape=(None,), name="input%i" % t)

for t in range(self.seq_length)]

# desired output

self.labels = [tf.placeholder(tf.int32, shape=(None,), name="labels%i" % t)

for t in range(self.seq_length)]

# weight of the hidden layer

self.weights = [tf.ones_like(labels_t, dtype=tf.float32)

for labels_t in self.labels]

# Decoder input: prepend some "GO" token and drop the final

# token of the encoder input

self.dec_inp = ([tf.zeros_like(self.labels[0], dtype=np.int32, name="GO")] + self.labels[:-1])

Example 11

def _load_data_graph(self):

"""

Loads the data graph consisting of the encoder and decoder input placeholders, Label (Target tip summary)

placeholders and the weights of the hidden layer of the Seq2Seq model.

:return: None

"""

# input

with tf.variable_scope("train_test", reuse=True):

# review input - Both original and reversed

self.enc_inp_fwd = [tf.placeholder(tf.int32, shape=(None,), name=

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值