本文整理汇总了Python中numpy.nonzero方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.nonzero方法的具体用法?Python numpy.nonzero怎么用?Python numpy.nonzero使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.nonzero方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vis_mask
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def vis_mask(img, mask, bbox_color, show_parss=False):
"""Visualizes a single binary mask."""
img = img.astype(np.float32)
idx = np.nonzero(mask)
border_color = cfg.VIS.SHOW_SEGMS.BORDER_COLOR
border_thick = cfg.VIS.SHOW_SEGMS.BORDER_THICK
mask_color = bbox_color if cfg.VIS.SHOW_SEGMS.MASK_COLOR_FOLLOW_BOX else _WHITE
mask_color = np.asarray(mask_color)
mask_alpha = cfg.VIS.SHOW_SEGMS.MASK_ALPHA
_, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
if cfg.VIS.SHOW_SEGMS.SHOW_BORDER:
cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA)
if cfg.VIS.SHOW_SEGMS.SHOW_MASK and not show_parss:
img[idx[0], idx[1], :] *= 1.0 - mask_alpha
img[idx[0], idx[1], :] += mask_alpha * mask_color
return img.astype(np.uint8)
示例2: vis_parsing
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def vis_parsing(img, parsing, colormap, show_segms=True):
"""Visualizes a single binary parsing."""
img = img.astype(np.float32)
idx = np.nonzero(parsing)
parsing_alpha = cfg.VIS.SHOW_PARSS.PARSING_ALPHA
colormap = colormap_utils.dict2array(colormap)
parsing_color = colormap[parsing.astype(np.int)]
border_color = cfg.VIS.SHOW_PARSS.BORDER_COLOR
border_thick = cfg.VIS.SHOW_PARSS.BORDER_THICK
img[idx[0], idx[1], :] *= 1.0 - parsing_alpha
# img[idx[0], idx[1], :] += alpha * parsing_color
img += parsing_alpha * parsing_color
if cfg.VIS.SHOW_PARSS.SHOW_BORDER and not show_segms:
_, contours, _ = cv2.findContours(parsing.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA)
return img.astype(np.uint8)
示例3: plot_force_arrows
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def plot_force_arrows(self, f):
"""Add arrows to the plot for each force."""
arrowprops = {"arrowstyle": "->", "connectionstyle": "arc3",
"lw": "2", "color": 0}
cmap = plt.cm.get_cmap("hsv", f.shape[1] + 1)
for load_i in range(f.shape[1]):
nz = np.nonzero(f[:, load_i])
arrowprops["color"] = cmap(load_i)
for i in range(nz[0].shape[0]):
x, y = id_to_xy(nz[0][i] // 2, self.nelx, self.nely)
x = max(min(x, self.nelx - 1), 0)
y = max(min(y, self.nely - 1), 0)
z = int(nz[0][i] % 2)
mag = -50 * f[nz[0][i], load_i]
self.ax.annotate("", xy=(x, y), xycoords="data",
xytext = (0 if z else mag, mag if z else 0),
textcoords="offset points", arrowprops=arrowprops)
示例4: prune_non_overlapping_boxes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
"""Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.
For each box in boxlist1, we want its IOA to be more than minoverlap with
at least one of the boxes in boxlist2. If it does not, we remove it.
Args:
boxlist1: BoxList holding N boxes.
boxlist2: BoxList holding M boxes.
minoverlap: Minimum required overlap between boxes, to count them as
overlapping.
Returns:
A pruned boxlist with size [N', 4].
"""
intersection_over_area = ioa(boxlist2, boxlist1) # [M, N] tensor
intersection_over_area = np.amax(intersection_over_area, axis=0) # [N] tensor
keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
keep_inds = np.nonzero(keep_bool)[0]
new_boxlist1 = gather(boxlist1, keep_inds)
return new_boxlist1
示例5: rollout_iterator
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def rollout_iterator(self):
"""
Iterate through all the rollouts in the dataset sequentially
"""
end_indices = np.nonzero(self._dones)[0] + 1
states = np.asarray(self._states)
actions = np.asarray(self._actions)
next_states = np.asarray(self._next_states)
rewards = np.asarray(self._rewards)
dones = np.asarray(self._dones)
start_idx = 0
for end_idx in end_indices:
indices = np.arange(start_idx, end_idx)
yield states[indices], actions[indices], next_states[indices], rewards[indices], dones[indices]
start_idx = end_idx
示例6: random_iterator
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def random_iterator(self, batch_size):
"""
Iterate once through all (s, a, r, s') in batches in a random order
"""
all_indices = np.nonzero(np.logical_not(self._dones))[0]
np.random.shuffle(all_indices)
states = np.asarray(self._states)
actions = np.asarray(self._actions)
next_states = np.asarray(self._next_states)
rewards = np.asarray(self._rewards)
dones = np.asarray(self._dones)
i = 0
while i < len(all_indices):
indices = all_indices[i:i+batch_size]
yield states[indices], actions[indices], next_states[indices], rewards[indices], dones[indices]
i += batch_size
###############
### Logging ###
###############
示例7: log
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def log(self):
end_idxs = np.nonzero(self._dones)[0] + 1
returns = []
start_idx = 0
for end_idx in end_idxs:
rewards = self._rewards[start_idx:end_idx]
returns.append(np.sum(rewards))
start_idx = end_idx
logger.record_tabular('ReturnAvg', np.mean(returns))
logger.record_tabular('ReturnStd', np.std(returns))
logger.record_tabular('ReturnMin', np.min(returns))
logger.record_tabular('ReturnMax', np.max(returns))
##################
### Tensorflow ###
##################
示例8: _step1
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def _step1(state):
"""Steps 1 and 2 in the Wikipedia page."""
# Step 1: For each row of the matrix, find the smallest element and
# subtract it from every element in its row.
state.C -= state.C.min(axis=1)[:, np.newaxis]
# Step 2: Find a zero (Z) in the resulting matrix. If there is no
# starred zero in its row or column, star Z. Repeat for each element
# in the matrix.
for i, j in zip(*np.nonzero(state.C == 0)):
if state.col_uncovered[j] and state.row_uncovered[i]:
state.marked[i, j] = 1
state.col_uncovered[j] = False
state.row_uncovered[i] = False
state._clear_covers()
return _step3
示例9: pred_to_dict
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def pred_to_dict(text, pred, prob):
res = {"company": ("", 0), "date": ("", 0), "address": ("", 0), "total": ("", 0)}
keys = list(res.keys())
seps = [0] + (numpy.nonzero(numpy.diff(pred))[0] + 1).tolist() + [len(pred)]
for i in range(len(seps) - 1):
pred_class = pred[seps[i]] - 1
if pred_class == -1:
continue
new_key = keys[pred_class]
new_prob = prob[seps[i] : seps[i + 1]].max()
if new_prob > res[new_key][1]:
res[new_key] = (text[seps[i] : seps[i + 1]], new_prob)
return {k: regex.sub(r"[\t\n]", " ", v[0].strip()) for k, v in res.items()}
示例10: _complexity_dimension
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def _complexity_dimension(signal, delay=1, dimension_max=20, method="afnn", R=10.0, A=2.0):
# Initalize vectors
if isinstance(dimension_max, int):
dimension_seq = np.arange(1, dimension_max + 1)
else:
dimension_seq = np.array(dimension_max)
# Method
method = method.lower()
if method in ["afnn"]:
E, Es = _embedding_dimension_afn(signal, dimension_seq=dimension_seq, delay=delay, show=False)
E1 = E[1:] / E[:-1]
E2 = Es[1:] / Es[:-1]
min_dimension = [i for i, x in enumerate(E1 >= 0.85 * np.max(E1)) if x][0] + 1
optimize_indices = [E1, E2]
return dimension_seq, optimize_indices, min_dimension
if method in ["fnn"]:
f1, f2, f3 = _embedding_dimension_ffn(signal, dimension_seq=dimension_seq, delay=delay, R=R, A=A)
min_dimension = [i for i, x in enumerate(f3 <= 1.85 * np.min(f3[np.nonzero(f3)])) if x][0]
optimize_indices = [f1, f2, f3]
return dimension_seq, optimize_indices, min_dimension
else:
raise ValueError("NeuroKit error: complexity_dimension(): 'method' not recognized.")
示例11: _fractal_correlation
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def _fractal_correlation(signal, r_vals, dist):
"""References
-----------
- `nolds <https://github.com/CSchoel/nolds/blob/master/nolds/measures.py>`_
"""
n = len(signal)
corr = np.zeros(len(r_vals))
for i, r in enumerate(r_vals):
corr[i] = 1 / (n * (n - 1)) * np.sum(dist < r)
# filter zeros from csums
nonzero = np.nonzero(corr)[0]
r_vals = r_vals[nonzero]
corr = corr[nonzero]
return r_vals, corr
示例12: pixel_list_to_array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def pixel_list_to_array(pixel_locations, shape):
''' Transforms a list of pixel locations into a 2D array.
:param tuple pixel_locations: A tuple of two lists representing the x and y
coordinates of the locations of a set of pixels (i.e. the output of
numpy.nonzero(valid_pixels) where valid_pixels is a 2D boolean array
representing the pixel locations)
:param list active_pixels: A list the same length as the x and y coordinate
lists within pixel_locations representing whether a pixel location
should be represented in the mask or not
:param tuple shape: The shape of the output array consisting of a tuple
of (height, width)
:returns: A 2-D boolean array representing active pixels
'''
mask = numpy.zeros(shape, dtype=numpy.bool)
mask[pixel_locations] = True
return mask
示例13: trim_pixel_list
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def trim_pixel_list(pixel_locations, active_pixels):
''' Trims the list of pixel locations to only the active pixels.
:param tuple pixel_locations: A tuple of two lists representing the x and y
coordinates of the locations of a set of pixels (i.e. the output of
numpy.nonzero(valid_pixels) where valid_pixels is a 2D boolean array
representing the pixel locations)
:param list active_pixels: A list the same length as the x and y coordinate
lists within pixel_locations representing whether a pixel location
should be represented in the mask or not
:returns: A tuple of two lists representing the x and y coordinates of the
locations of active pixels
'''
active_pixels = numpy.nonzero(active_pixels)[0]
return (pixel_locations[0][active_pixels],
pixel_locations[1][active_pixels])
示例14: _uniform_weight_alpha
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def _uniform_weight_alpha(sum_masked_arrays, output_datatype):
'''Calculates the cumulative mask of a list of masked array
Input:
sum_masked_arrays (list of numpy masked arrays): The list of
masked arrays to find the cumulative mask of, each element
represents one band.
(sums_masked_array.mask has a 1 for a no data pixel and
a 0 otherwise)
output_datatype (numpy datatype): The output datatype
Output:
output_alpha (numpy uint16 array): The output mask
(0 for a no data pixel, uint16 max value otherwise)
'''
output_alpha = numpy.ones(sum_masked_arrays[0].shape)
for band_sum_masked_array in sum_masked_arrays:
output_alpha[numpy.nonzero(band_sum_masked_array.mask == 1)] = 0
output_alpha = output_alpha.astype(output_datatype) * \
numpy.iinfo(output_datatype).max
return output_alpha
示例15: create_pixel_plots
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import nonzero [as 别名]
def create_pixel_plots(candidate_path, reference_path, base_name,
last_band_alpha=False, limits=None, custom_alpha=None):
c_ds, c_alpha, c_band_count = _open_image_and_get_info(
candidate_path, last_band_alpha)
r_ds, r_alpha, r_band_count = _open_image_and_get_info(
reference_path, last_band_alpha)
_assert_consistent(c_alpha, r_alpha, c_band_count, r_band_count)
if custom_alpha != None:
combined_alpha = custom_alpha
else:
combined_alpha = numpy.logical_and(c_alpha, r_alpha)
valid_pixels = numpy.nonzero(combined_alpha)
for band_no in range(1, c_band_count + 1):
c_band = gimage.read_single_band(c_ds, band_no)
r_band = gimage.read_single_band(r_ds, band_no)
file_name = '{}_{}.png'.format(base_name, band_no)
display.plot_pixels(file_name, c_band[valid_pixels],
r_band[valid_pixels], limits)