def view_trigger_snippets(trigger_snippets, chans, save=None):
# Create output directory if necessary.
if os.path.exists(save):
for f in os.listdir(save):
p = os.path.join(save, f)
os.remove(p)
os.removedirs(save)
os.makedirs(save)
# Plot figures.
fig = pylab.figure()
for (c, chan) in enumerate(chans):
ax = fig.add_subplot(1, 1, 1)
for n in xrange(0, trigger_snippets.shape[2]):
y = trigger_snippets[:, c, n]
x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
b = 0.5 + 0.5 * numpy.random.rand()
ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid')
y = numpy.mean(trigger_snippets[:, c, :], axis=1)
x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid')
ax.grid(True)
ax.set_xlim([numpy.amin(x), numpy.amax(x)])
ax.set_title("Channel %d" %chan)
ax.set_xlabel("time")
ax.set_ylabel("amplitude")
if save is not None:
# Save plot.
filename = "channel-%d.png" %chan
path = os.path.join(save, filename)
pylab.savefig(path)
fig.clf()
if save is None:
pylab.show()
else:
pylab.close(fig)
return
python类amin()的实例源码
def imgSeg_logo(approx, himg, wimg):
w = np.amax(approx[:,:,0])-np.amin(approx[:,:,0]); h = np.amax(approx[:,:,1])-np.amin(approx[:,:,1])
if float(w)/float(h+0.001) > 4.5:
h = int(float(w)/3.5)
w0 = np.amin(approx[:,:,0]); h0 = np.amin(approx[:,:,1])
h1 = h0-int(3.5*h); h2 = h0;
w1 = max(w0+w/2-int(0.5*(h2-h1)), 0); w2 = min(w0+w/2+int(0.5*(h2-h1)), wimg-1)
return h1, h2, w1, w2
def imgSeg_rect(approx, himg, wimg):
w = np.amax(approx[:,:,0])-np.amin(approx[:,:,0]); h = np.amax(approx[:,:,1])-np.amin(approx[:,:,1])
if float(w)/float(h+0.001) > 4.5:
h = int(float(w)/3.5)
w0 = np.amin(approx[:,:,0]); h0 = np.amin(approx[:,:,1])
h1 = h0-int(3.6*h); h2 = min(h0+int(3*h), himg-1)
w1 = max(w0+w/2-(h2-h1), 0); w2 = min(w0+w/2+(h2-h1), wimg-1)
return h1, h2, w1, w2
def collect_point_label(anno_path, out_filename, file_format='txt'):
""" Convert original dataset files to data_label file (each line is XYZRGBL).
We aggregated all the points from each instance in the room.
Args:
anno_path: path to annotations. e.g. Area_1/office_2/Annotations/
out_filename: path to save collected points and labels (each line is XYZRGBL)
file_format: txt or numpy, determines what file format to save.
Returns:
None
Note:
the points are shifted before save, the most negative point is now at origin.
"""
points_list = []
for f in glob.glob(os.path.join(anno_path, '*.txt')):
cls = os.path.basename(f).split('_')[0]
if cls not in g_classes: # note: in some room there is 'staris' class..
cls = 'clutter'
points = np.loadtxt(f)
labels = np.ones((points.shape[0],1)) * g_class2label[cls]
points_list.append(np.concatenate([points, labels], 1)) # Nx7
data_label = np.concatenate(points_list, 0)
xyz_min = np.amin(data_label, axis=0)[0:3]
data_label[:, 0:3] -= xyz_min
if file_format=='txt':
fout = open(out_filename, 'w')
for i in range(data_label.shape[0]):
fout.write('%f %f %f %d %d %d %d\n' % \
(data_label[i,0], data_label[i,1], data_label[i,2],
data_label[i,3], data_label[i,4], data_label[i,5],
data_label[i,6]))
fout.close()
elif file_format=='numpy':
np.save(out_filename, data_label)
else:
print('ERROR!! Unknown file format: %s, please use txt or numpy.' % \
(file_format))
exit()
def collect_bounding_box(anno_path, out_filename):
""" Compute bounding boxes from each instance in original dataset files on
one room. **We assume the bbox is aligned with XYZ coordinate.**
Args:
anno_path: path to annotations. e.g. Area_1/office_2/Annotations/
out_filename: path to save instance bounding boxes for that room.
each line is x1 y1 z1 x2 y2 z2 label,
where (x1,y1,z1) is the point on the diagonal closer to origin
Returns:
None
Note:
room points are shifted, the most negative point is now at origin.
"""
bbox_label_list = []
for f in glob.glob(os.path.join(anno_path, '*.txt')):
cls = os.path.basename(f).split('_')[0]
if cls not in g_classes: # note: in some room there is 'staris' class..
cls = 'clutter'
points = np.loadtxt(f)
label = g_class2label[cls]
# Compute tightest axis aligned bounding box
xyz_min = np.amin(points[:, 0:3], axis=0)
xyz_max = np.amax(points[:, 0:3], axis=0)
ins_bbox_label = np.expand_dims(
np.concatenate([xyz_min, xyz_max, np.array([label])], 0), 0)
bbox_label_list.append(ins_bbox_label)
bbox_label = np.concatenate(bbox_label_list, 0)
room_xyz_min = np.amin(bbox_label[:, 0:3], axis=0)
bbox_label[:, 0:3] -= room_xyz_min
bbox_label[:, 3:6] -= room_xyz_min
fout = open(out_filename, 'w')
for i in range(bbox_label.shape[0]):
fout.write('%f %f %f %f %f %f %d\n' % \
(bbox_label[i,0], bbox_label[i,1], bbox_label[i,2],
bbox_label[i,3], bbox_label[i,4], bbox_label[i,5],
bbox_label[i,6]))
fout.close()
def read_testing_inputs(file, roi, im_size, output_path=None):
f_h5 = h5py.File(file, 'r')
if roi == -1:
images = np.asarray(f_h5['resized_images'], dtype=np.float32)
read_info = {}
read_info['shape'] = np.asarray(f_h5['images'], dtype=np.float32).shape
else:
images = np.asarray(f_h5['images'], dtype=np.float32)
output = h5py.File(os.path.join(output_path, 'All_' + os.path.basename(file)), 'r')
predictions = np.asarray(output['predictions'], dtype=np.float32)
output.close()
# Select the roi
roi_labels = (predictions == roi + 1).astype(np.float32)
nz = np.nonzero(roi_labels)
extract = []
for c in range(3):
start = np.amin(nz[c])
end = np.amax(nz[c])
r = end - start
extract.append((np.maximum(int(np.rint(start - r * 0.1)), 0),
np.minimum(int(np.rint(end + r * 0.1)), images.shape[c])))
extract_images = images[extract[0][0] : extract[0][1], extract[1][0] : extract[1][1], extract[2][0] : extract[2][1]]
read_info = {}
read_info['shape'] = images.shape
read_info['extract_shape'] = extract_images.shape
read_info['extract'] = extract
images = resize(extract_images, im_size, mode='constant')
f_h5.close()
return images, read_info
def normalize(im):
mini = np.amin(im)
maxi = np.amax(im)
rng = maxi-mini
im -= mini
if rng > 0:
im /= rng
return im
# ----- Type transformations --------------------------------------------------
def to_rgb(img):
img = img.reshape(img.shape[0], img.shape[1])
img[np.isnan(img)] = 0
img -= np.amin(img)
img /= np.amax(img)
blue = np.clip(4*(0.75-img), 0, 1)
red = np.clip(4*(img-0.25), 0, 1)
green= np.clip(44*np.fabs(img-0.5)-1., 0, 1)
rgb = np.stack((red, green, blue), axis=2)
return rgb
def _process_data(self, data):
# normalization
data = np.clip(np.fabs(data), self.a_min, self.a_max)
data -= np.amin(data)
data /= np.amax(data)
return data
def plot_prediction(x_test, y_test, prediction, save=False):
import matplotlib
import matplotlib.pyplot as plt
test_size = x_test.shape[0]
fig, ax = plt.subplots(test_size, 3, figsize=(12,12), sharey=True, sharex=True)
x_test = crop_to_shape(x_test, prediction.shape)
y_test = crop_to_shape(y_test, prediction.shape)
ax = np.atleast_2d(ax)
for i in range(test_size):
cax = ax[i, 0].imshow(x_test[i])
plt.colorbar(cax, ax=ax[i,0])
cax = ax[i, 1].imshow(y_test[i, ..., 1])
plt.colorbar(cax, ax=ax[i,1])
pred = prediction[i, ..., 1]
pred -= np.amin(pred)
pred /= np.amax(pred)
cax = ax[i, 2].imshow(pred)
plt.colorbar(cax, ax=ax[i,2])
if i==0:
ax[i, 0].set_title("x")
ax[i, 1].set_title("y")
ax[i, 2].set_title("pred")
fig.tight_layout()
if save:
fig.savefig(save)
else:
fig.show()
plt.show()
def computeallcpus(self):
""" overall stats for all cores on the nodes """
ratios = numpy.empty((self._ncpumetrics, self._totalcores), numpy.double)
coreindex = 0
for host, last in self._last.iteritems():
try:
elapsed = last - self._first[host]
if numpy.amin(numpy.sum(elapsed, 0)) < 1.0:
# typically happens if the job was very short and the datapoints are too close together
return {"error": ProcessingError.JOB_TOO_SHORT}
coresperhost = len(last[0, :])
ratios[:, coreindex:(coreindex+coresperhost)] = 1.0 * elapsed / numpy.sum(elapsed, 0)
coreindex += coresperhost
except ValueError:
# typically happens if the linux pmda crashes during the job
return {"error": ProcessingError.INSUFFICIENT_DATA}
results = {}
for i, name in enumerate(self._outnames):
results[name] = calculate_stats(ratios[i, :])
results['all'] = {"cnt": self._totalcores}
return results
def plot_slice_3d_2_patch(ct_scan, mask, pid, img_dir=None, idx=None):
# to convert cuda arrays to numpy array
ct_scan = np.asarray(ct_scan)
mask = np.asarray(mask)
fig, ax = plt.subplots(2, 3, figsize=[8, 8])
fig.canvas.set_window_title(pid)
if idx == None:
#just plot in the middle of the cube
in_sh = ct_scan.shape
idx = [in_sh[0]/2,in_sh[1]/2,in_sh[2]/2]
print np.amin(ct_scan), np.amax(ct_scan)
print np.amin(mask), np.amax(mask)
ax[0, 0].imshow(ct_scan[idx[0], :, :], cmap=plt.cm.gray)
ax[0, 1].imshow(ct_scan[:, idx[1], :], cmap=plt.cm.gray)
ax[0, 2].imshow(ct_scan[:, :, idx[2]], cmap=plt.cm.gray)
ax[1, 0].imshow(mask[idx[0], :, :], cmap=plt.cm.gray)
ax[1, 1].imshow(mask[:, idx[1], :], cmap=plt.cm.gray)
ax[1, 2].imshow(mask[:, :, idx[2]], cmap=plt.cm.gray)
if img_dir is not None:
fig.savefig(img_dir + '/%s.png' % pid, bbox_inches='tight')
else:
plt.show()
fig.clf()
plt.close('all')
def calculate_likelihoods(ScoreList, NumInfoSites):
num_lines = len(ScoreList)
LikeLiHoods = [likeliTest(NumInfoSites[i], int(ScoreList[i])) for i in range(num_lines)]
LikeLiHoods = np.array(LikeLiHoods).astype("float")
TopHit = np.amin(LikeLiHoods)
LikeLiHoodRatios = [LikeLiHoods[i]/TopHit for i in range(num_lines)]
LikeLiHoodRatios = np.array(LikeLiHoodRatios).astype("float")
return (LikeLiHoods, LikeLiHoodRatios)
def normalize(self):
self.X = (self.X - np.amin(self.X, 0)) \
/ (np.amax(self.X, 0) - np.amin(self.X, 0))
def normalize_points(self, x):
return np.divide(x - np.amin(self.X, 0) ,
np.amax(self.X, 0) - np.amin(self.X, 0), np.empty_like(x))
def compute_patches_at_scale(self, scale_idx, scale, p_id_base):
debug("Processing {} scale_idx:{} scale:{}".format(self.file_name, scale_idx, scale))
shape = np.array(self.shape)
size = (np.amin(shape)-1) / scale
num_samples = np.ceil( (shape-1) / size)
num_samples = [int(n*2) if n > 1 else int(n) for n in num_samples]
patches = []
sample_locs = [ self.sample_locs_for_dim( self.shape[0], size, num_samples[0]),
self.sample_locs_for_dim( self.shape[1], size, num_samples[1])]
p_id = p_id_base
for sample_loc_0 in sample_locs[0]:
for sample_loc_1 in sample_locs[1]:
patch = ImagePatch( p_id, self, (sample_loc_0, sample_loc_1), size, scale)
patch.label, patch.matched_roi_idx = \
self.get_label_for_patch(patch)
if patch.label != PASCAL_VOC_BACKGROUND_CLASS:
self.non_background_patches.append(patch)
else:
self.background_patches.append(patch)
patches.append(patch)
p_id += 1
debug("Compute {} patches".format(p_id-p_id_base))
return p_id
# Sample the Pascal VOC dataset
def lower_bounds(self):
return Vector2f(*numpy.amin(self.particles['position'], axis=0))
def test_all(self):
a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
for i in range(a.ndim):
amin = a.min(i)
aargmin = a.argmin(i)
axes = list(range(a.ndim))
axes.remove(i)
assert_(np.all(amin == aargmin.choose(*a.transpose(i,*axes))))
def test_scalar(self):
assert_raises(ValueError, np.amax, 1, 1)
assert_raises(ValueError, np.amin, 1, 1)
assert_equal(np.amax(1, axis=0), 1)
assert_equal(np.amin(1, axis=0), 1)
assert_equal(np.amax(1, axis=None), 1)
assert_equal(np.amin(1, axis=None), 1)