Python numpy.clip() Examples
The following are 30
code examples of numpy.clip().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: datasets.py From pruning_yolov3 with GNU General Public License v3.0 | 7 votes |
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5): x = (np.random.uniform(-1, 1, 3) * np.array([hgain, sgain, vgain]) + 1).astype(np.float32) # random gains img_hsv = (cv2.cvtColor(img, cv2.COLOR_BGR2HSV) * x.reshape((1, 1, 3))).clip(None, 255).astype(np.uint8) cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed # def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5): # original version # # SV augmentation by 50% # img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # hue, sat, val # # S = img_hsv[:, :, 1].astype(np.float32) # saturation # V = img_hsv[:, :, 2].astype(np.float32) # value # # a = random.uniform(-1, 1) * sgain + 1 # b = random.uniform(-1, 1) * vgain + 1 # S *= a # V *= b # # img_hsv[:, :, 1] = S if a < 1 else S.clip(None, 255) # img_hsv[:, :, 2] = V if b < 1 else V.clip(None, 255) # cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
Example #2
Source File: pgd_cw_whitebox.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def perturb(self, x_nat, y, sess): """Given a set of examples (x_nat, y), returns a set of adversarial examples within epsilon of x_nat in l_infinity norm.""" if self.rand: x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape) else: x = np.copy(x_nat) for i in range(self.k): grad = sess.run(self.grad, feed_dict={self.model.x_input: x, self.model.y_input: y}) x += self.a * np.sign(grad) x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon) x = np.clip(x, 0, 1) # ensure valid pixel range return x
Example #3
Source File: atari_game.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def play(self, a): assert not self.episode_terminate,\ "Warning, the episode seems to have terminated. " \ "We need to call either game.begin_episode(max_episode_step) to continue a new " \ "episode or game.start() to force restart." self.episode_step += 1 reward = 0.0 action = self.action_set[a] for i in range(self.frame_skip): reward += self.ale.act(action) self.ale.getScreenGrayscale(self.screen_buffer[i % self.screen_buffer_length, :, :]) self.total_reward += reward self.episode_reward += reward ob = self.get_observation() terminate_flag = self.episode_terminate self.replay_memory.append(ob, a, numpy.clip(reward, -1, 1), terminate_flag) return reward, terminate_flag
Example #4
Source File: vaegan_mxnet.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def visual(title, X, activation): '''create a grid of images and save it as a final image title : grid image name X : array of images ''' assert len(X.shape) == 4 X = X.transpose((0, 2, 3, 1)) if activation == 'sigmoid': X = np.clip((X)*(255.0), 0, 255).astype(np.uint8) elif activation == 'tanh': X = np.clip((X+1.0)*(255.0/2.0), 0, 255).astype(np.uint8) n = np.ceil(np.sqrt(X.shape[0])) buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8) for i, img in enumerate(X): fill_buf(buff, i, img, X.shape[1:3]) cv2.imwrite('%s.jpg' % (title), buff)
Example #5
Source File: structures.py From mmdetection with Apache License 2.0 | 6 votes |
def crop(self, bbox): """See :func:`BaseInstanceMasks.crop`.""" assert isinstance(bbox, np.ndarray) assert bbox.ndim == 1 # clip the boundary bbox = bbox.copy() bbox[0::2] = np.clip(bbox[0::2], 0, self.width) bbox[1::2] = np.clip(bbox[1::2], 0, self.height) x1, y1, x2, y2 = bbox w = np.maximum(x2 - x1, 1) h = np.maximum(y2 - y1, 1) if len(self.masks) == 0: cropped_masks = np.empty((0, h, w), dtype=np.uint8) else: cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w] return BitmapMasks(cropped_masks, h, w)
Example #6
Source File: utils.py From GST-Tacotron with MIT License | 6 votes |
def spectrogram2wav(mag): '''# Generate wave file from spectrogram''' # transpose mag = mag.T # de-noramlize mag = (np.clip(mag, 0, 1) * hp.max_db) - hp.max_db + hp.ref_db # to amplitude mag = np.power(10.0, mag * 0.05) # wav reconstruction wav = griffin_lim(mag) # de-preemphasis wav = signal.lfilter([1], [1, -hp.preemphasis], wav) # trim wav, _ = librosa.effects.trim(wav) return wav.astype(np.float32)
Example #7
Source File: pgd_cw_whitebox.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def perturb(self, x_nat, y, sess): """Given a set of examples (x_nat, y), returns a set of adversarial examples within epsilon of x_nat in l_infinity norm.""" if self.rand: x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape) else: x = np.copy(x_nat) for i in range(self.k): grad = sess.run(self.grad, feed_dict={self.model.x_input: x, self.model.y_input: y}) x += self.a * np.sign(grad) x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon) x = np.clip(x, 0, 1) # ensure valid pixel range return x
Example #8
Source File: pgd_whitebox.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def perturb(self, x_nat, y, sess): """Given a set of examples (x_nat, y), returns a set of adversarial examples within epsilon of x_nat in l_infinity norm.""" if self.rand: x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape) else: x = np.copy(x_nat) for i in range(self.k): grad = sess.run(self.grad, feed_dict={self.model.x_input: x, self.model.y_input: y}) x += self.a * np.sign(grad) x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon) x = np.clip(x, 0, 1) # ensure valid pixel range return x
Example #9
Source File: dataset_tool.py From disentangling_conditional_gans with MIT License | 6 votes |
def add_image(self, img): if self.print_progress and self.cur_images % self.progress_interval == 0: print('%d / %d\r' % (self.cur_images, self.expected_images), end='', flush=True) sys.stdout.flush() if self.shape is None: self.shape = img.shape self.resolution_log2 = int(np.log2(self.shape[1])) assert self.shape[0] in [1, 3] assert self.shape[1] == self.shape[2] assert self.shape[1] == 2**self.resolution_log2 tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE) for lod in range(self.resolution_log2 - 1): tfr_file = self.tfr_prefix + '-r%02d.tfrecords' % (self.resolution_log2 - lod) self.tfr_writers.append(tf.python_io.TFRecordWriter(tfr_file, tfr_opt)) assert img.shape == self.shape for lod, tfr_writer in enumerate(self.tfr_writers): if lod: img = img.astype(np.float32) img = (img[:, 0::2, 0::2] + img[:, 0::2, 1::2] + img[:, 1::2, 0::2] + img[:, 1::2, 1::2]) * 0.25 quant = np.rint(img).clip(0, 255).astype(np.uint8) ex = tf.train.Example(features=tf.train.Features(feature={ 'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=quant.shape)), 'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[quant.tostring()]))})) tfr_writer.write(ex.SerializeToString()) self.cur_images += 1
Example #10
Source File: motor.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
def convert_to_torque(self, motor_commands, current_motor_angle, current_motor_velocity): """Convert the commands (position control or torque control) to torque. Args: motor_commands: The desired motor angle if the motor is in position control mode. The pwm signal if the motor is in torque control mode. current_motor_angle: The motor angle at the current time step. current_motor_velocity: The motor velocity at the current time step. Returns: actual_torque: The torque that needs to be applied to the motor. observed_torque: The torque observed by the sensor. """ if self._torque_control_enabled: pwm = motor_commands else: pwm = (-self._kp * (current_motor_angle - motor_commands) - self._kd * current_motor_velocity) pwm = np.clip(pwm, -1.0, 1.0) return self._convert_to_torque_from_pwm(pwm, current_motor_velocity)
Example #11
Source File: common.py From cat-bbs with MIT License | 6 votes |
def draw_heatmap(img, heatmap, alpha=0.5): """Draw a heatmap overlay over an image.""" assert len(heatmap.shape) == 2 or \ (len(heatmap.shape) == 3 and heatmap.shape[2] == 1) assert img.dtype in [np.uint8, np.int32, np.int64] assert heatmap.dtype in [np.float32, np.float64] if img.shape[0:2] != heatmap.shape[0:2]: heatmap_rs = np.clip(heatmap * 255, 0, 255).astype(np.uint8) heatmap_rs = ia.imresize_single_image( heatmap_rs[..., np.newaxis], img.shape[0:2], interpolation="nearest" ) heatmap = np.squeeze(heatmap_rs) / 255.0 cmap = plt.get_cmap('jet') heatmap_cmapped = cmap(heatmap) heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2) heatmap_cmapped = heatmap_cmapped * 255 mix = (1-alpha) * img + alpha * heatmap_cmapped mix = np.clip(mix, 0, 255).astype(np.uint8) return mix
Example #12
Source File: pgd_cw_whitebox.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def perturb(self, x_nat, y, sess): """Given a set of examples (x_nat, y), returns a set of adversarial examples within epsilon of x_nat in l_infinity norm.""" if self.rand: x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape) else: x = np.copy(x_nat) for i in range(self.k): grad = sess.run(self.grad, feed_dict={self.model.x_input: x, self.model.y_input: y}) x += self.a * np.sign(grad) x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon) x = np.clip(x, 0, 1) # ensure valid pixel range return x
Example #13
Source File: pgd_whitebox.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def perturb(self, x_nat, y, sess): """Given a set of examples (x_nat, y), returns a set of adversarial examples within epsilon of x_nat in l_infinity norm.""" if self.rand: x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape) else: x = np.copy(x_nat) for i in range(self.k): grad = sess.run(self.grad, feed_dict={self.model.x_input: x, self.model.y_input: y}) x += self.a * np.sign(grad) x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon) x = np.clip(x, 0, 1) # ensure valid pixel range return x
Example #14
Source File: utils.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def cleverhans_attack_wrapper(cleverhans_attack_fn, reset=True): def attack(a): session = tf.Session() with session.as_default(): model = RVBCleverhansModel(a) adversarial_image = cleverhans_attack_fn(model, session, a) adversarial_image = np.squeeze(adversarial_image, axis=0) if reset: # optionally, reset to ignore other adversarials # found during the search a._reset() # run predictions to make sure the returned adversarial # is taken into account min_, max_ = a.bounds() adversarial_image = np.clip(adversarial_image, min_, max_) a.predictions(adversarial_image) return attack
Example #15
Source File: dataset.py From Deep_VoiceChanger with MIT License | 6 votes |
def wave2input_image(wave, window, pos=0, pad=0): wave_image = np.hstack([wave[pos+i*sride:pos+(i+pad*2)*sride+dif].reshape(height+pad*2, sride) for i in range(256//sride)])[:,:254] wave_image *= window spectrum_image = np.fft.fft(wave_image, axis=1) input_image = np.abs(spectrum_image[:,:128].reshape(1, height+pad*2, 128), dtype=np.float32) np.clip(input_image, 1000, None, out=input_image) np.log(input_image, out=input_image) input_image += bias input_image /= scale if np.max(input_image) > 0.95: print('input image max bigger than 0.95', np.max(input_image)) if np.min(input_image) < 0.05: print('input image min smaller than 0.05', np.min(input_image)) return input_image
Example #16
Source File: image.py From Deep_VoiceChanger with MIT License | 6 votes |
def Chainer2PIL(data, rescale=True): data = np.array(data) if rescale: data *= 256 # data += 128 if data.dtype != np.uint8: data = np.clip(data, 0, 255) data = data.astype(np.uint8) if data.shape[0] == 1: buf = data.astype(np.uint8).reshape((data.shape[1], data.shape[2])) else: buf = np.zeros((data.shape[1], data.shape[2], data.shape[0]), dtype=np.uint8) for i in range(3): a = data[i,:,:] buf[:,:,i] = a img = Image.fromarray(buf) return img
Example #17
Source File: robot_locomotors.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def calc_state(self): j = np.array([j.current_relative_position() for j in self.ordered_joints], dtype=np.float32).flatten() # even elements [0::2] position, scaled to -1..+1 between limits # odd elements [1::2] angular speed, scaled to show -1..+1 self.joint_speeds = j[1::2] self.joints_at_limit = np.count_nonzero(np.abs(j[0::2]) > 0.99) body_pose = self.robot_body.pose() parts_xyz = np.array([p.pose().xyz() for p in self.parts.values()]).flatten() self.body_xyz = ( parts_xyz[0::3].mean(), parts_xyz[1::3].mean(), body_pose.xyz()[2]) # torso z is more informative than mean z self.body_rpy = body_pose.rpy() z = self.body_xyz[2] if self.initial_z == None: self.initial_z = z r, p, yaw = self.body_rpy self.walk_target_theta = np.arctan2(self.walk_target_y - self.body_xyz[1], self.walk_target_x - self.body_xyz[0]) self.walk_target_dist = np.linalg.norm( [self.walk_target_y - self.body_xyz[1], self.walk_target_x - self.body_xyz[0]]) angle_to_target = self.walk_target_theta - yaw rot_speed = np.array( [[np.cos(-yaw), -np.sin(-yaw), 0], [np.sin(-yaw), np.cos(-yaw), 0], [ 0, 0, 1]] ) vx, vy, vz = np.dot(rot_speed, self.robot_body.speed()) # rotate speed back to body point of view more = np.array([ z-self.initial_z, np.sin(angle_to_target), np.cos(angle_to_target), 0.3* vx , 0.3* vy , 0.3* vz , # 0.3 is just scaling typical speed into -1..+1, no physical sense here r, p], dtype=np.float32) return np.clip( np.concatenate([more] + [j] + [self.feet_contact]), -5, +5)
Example #18
Source File: robot_manipulators.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def apply_action(self, a): assert (np.isfinite(a).all()) self.shoulder_pan_joint.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1))) self.shoulder_lift_joint.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1))) self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1))) self.elbow_flex_joint.set_motor_torque(0.05 * float(np.clip(a[3], -1, +1))) self.upper_arm_roll_joint.set_motor_torque(0.05 * float(np.clip(a[4], -1, +1))) self.wrist_flex_joint.set_motor_torque(0.05 * float(np.clip(a[5], -1, +1))) self.wrist_roll_joint.set_motor_torque(0.05 * float(np.clip(a[6], -1, +1)))
Example #19
Source File: robot_locomotors.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def potential_leak(self): z = self.body_xyz[2] # 0.00 .. 0.8 .. 1.05 normal walk, 1.2 when jumping z = np.clip(z, 0, 0.8) return z/0.8 + 1.0 # 1.00 .. 2.0
Example #20
Source File: robot_manipulators.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def apply_action(self, a): assert (np.isfinite(a).all()) self.central_joint.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1))) self.elbow_joint.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))
Example #21
Source File: robot_locomotors.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def apply_action(self, a): assert( np.isfinite(a).all() ) force_gain = 1 for i, m, power in zip(range(17), self.motors, self.motor_power): m.set_motor_torque(float(force_gain * power * self.power * np.clip(a[i], -1, +1)))
Example #22
Source File: run_audio_attack.py From Black-Box-Audio with MIT License | 5 votes |
def setup_graph(self, input_audio_batch, target_phrase): batch_size = input_audio_batch.shape[0] weird = (input_audio_batch.shape[1] - 1) // 320 logits_arg2 = np.tile(weird, batch_size) dense_arg1 = np.array(np.tile(target_phrase, (batch_size, 1)), dtype=np.int32) dense_arg2 = np.array(np.tile(target_phrase.shape[0], batch_size), dtype=np.int32) pass_in = np.clip(input_audio_batch, -2**15, 2**15-1) seq_len = np.tile(weird, batch_size).astype(np.int32) with tf.variable_scope('', reuse=tf.AUTO_REUSE): inputs = tf.placeholder(tf.float32, shape=pass_in.shape, name='a') len_batch = tf.placeholder(tf.float32, name='b') arg2_logits = tf.placeholder(tf.int32, shape=logits_arg2.shape, name='c') arg1_dense = tf.placeholder(tf.float32, shape=dense_arg1.shape, name='d') arg2_dense = tf.placeholder(tf.int32, shape=dense_arg2.shape, name='e') len_seq = tf.placeholder(tf.int32, shape=seq_len.shape, name='f') logits = get_logits(inputs, arg2_logits) target = ctc_label_dense_to_sparse(arg1_dense, arg2_dense, len_batch) ctcloss = tf.nn.ctc_loss(labels=tf.cast(target, tf.int32), inputs=logits, sequence_length=len_seq) decoded, _ = tf.nn.ctc_greedy_decoder(logits, arg2_logits, merge_repeated=True) sess = tf.Session() saver = tf.train.Saver(tf.global_variables()) saver.restore(sess, "models/session_dump") func1 = lambda a, b, c, d, e, f: sess.run(ctcloss, feed_dict={inputs: a, len_batch: b, arg2_logits: c, arg1_dense: d, arg2_dense: e, len_seq: f}) func2 = lambda a, b, c, d, e, f: sess.run([ctcloss, decoded], feed_dict={inputs: a, len_batch: b, arg2_logits: c, arg1_dense: d, arg2_dense: e, len_seq: f}) return (func1, func2)
Example #23
Source File: data_processing.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def PostprocessImage(img): img = np.resize(img, (3, img.shape[2], img.shape[3])) img[0, :] += 123.68 img[1, :] += 116.779 img[2, :] += 103.939 img = np.swapaxes(img, 1, 2) img = np.swapaxes(img, 0, 2) img = np.clip(img, 0, 255) return img.astype('uint8')
Example #24
Source File: 3_nerual_style_transfer.py From deep-learning-note with MIT License | 5 votes |
def deprocess_image(x): # 加上 ImageNet 的平均像素值 x[:, :, 0] += 103.939 x[:, :, 1] += 116.779 x[:, :, 2] += 123.68 x = x[:, :, ::-1] x = np.clip(x, 0, 255).astype('uint8') return x
Example #25
Source File: nstyle.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def PostprocessImage(img): img = np.resize(img, (3, img.shape[2], img.shape[3])) img[0, :] += 123.68 img[1, :] += 116.779 img[2, :] += 103.939 img = np.swapaxes(img, 1, 2) img = np.swapaxes(img, 0, 2) img = np.clip(img, 0, 255) return img.astype('uint8')
Example #26
Source File: gradcam.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def to_grayscale(cv2im): """Convert gradients to grayscale. This gives a saliency map.""" # How strongly does each position activate the output grayscale_im = np.sum(np.abs(cv2im), axis=0) # Normalize between min and 99th percentile im_max = np.percentile(grayscale_im, 99) im_min = np.min(grayscale_im) grayscale_im = np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1) grayscale_im = np.expand_dims(grayscale_im, axis=0) return grayscale_im
Example #27
Source File: nilearn.py From NiBetaSeries with MIT License | 5 votes |
def _fisher_r_to_z(x): import numpy as np # correct any rounding errors # correlations cannot be greater than 1. x = np.clip(x, -1, 1) return np.arctanh(x)
Example #28
Source File: utils.py From deep-learning-note with MIT License | 5 votes |
def deprocess_image(x): # 通用函数,将一个张量转换为有效图像 if K.image_data_format() == 'channels_first': x = x.reshape((3, x.shape[2], x.shape[3])) x = x.transpose((1, 2, 0)) else: x = x.reshape((x.shape[1], x.shape[2], 3)) x /= 2. x += 0.3 x *= 255. x = np.clip(x, 0, 255).astype('uint8') return x
Example #29
Source File: tensorboard.py From neural-pipeline with MIT License | 5 votes |
def update_losses(self, losses: {}) -> None: """ Update monitor :param losses: losses values with keys 'train' and 'validation' """ if self.__writer is None: return def on_loss(name: str, values: np.ndarray) -> None: self.__writer.add_scalars('loss', {name: np.mean(values)}, global_step=self.epoch_num) self.__writer.add_histogram('{}/loss_hist'.format(name), np.clip(values, -1, 1).astype(np.float32), global_step=self.epoch_num, bins=np.linspace(-1, 1, num=11).astype(np.float32)) self._iterate_by_losses(losses, on_loss)
Example #30
Source File: util.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def triangle_area(a,b,c): ''' triangle_area(a, b, c) yields the area of the triangle whose vertices are given by the points a, b, and c. ''' (a,b,c) = [np.asarray(x) for x in (a,b,c)] sides = np.sqrt(np.sum([(p1 - p2)**2 for (p1,p2) in zip([b,c,a],[c,a,b])], axis=1)) s = 0.5 * np.sum(sides, axis=0) s = np.clip(s * np.prod(s - sides, axis=0), 0.0, None) return np.sqrt(s)