def update(self):
agents = self.simulation.agents.array
field = self.simulation.field
# FIXME: virtual obstacles add too much computational overhead
# obstacles = geom_to_linear_obstacles(
# field.obstacles.buffer(0.3, resolution=3))
obstacles = geom_to_linear_obstacles(field.obstacles)
direction_herding = leader_follower_with_herding_interaction(
agents, obstacles, self.sight_follower, self.size_nearest_other)
is_follower = agents['is_follower']
agents['target_direction'][is_follower] = direction_herding[is_follower]
# Set target direction for herding agents that do not have a target
# if field.obstacles is None:
# agents['target_direction'][is_follower] = direction_herding[is_follower]
# else:
# # Obstacle avoidance
# mgrid = field.meshgrid(self.step)
# dir_map_obs, dmap_obs = field.direction_map_obstacles(self.step)
# indices = np.fliplr(mgrid.indicer(agents['position'][is_follower]))
# direction = obstacle_handling_continuous(
# dmap_obs, dir_map_obs, direction_herding[is_follower], indices,
# self.radius, self.strength)
# agents['target_direction'][is_follower] = direction
python类fliplr()的实例源码
def augment_image(self, image, i):
if i == 0:
return np.rot90(image)
elif i == 1:
return np.rot90(image,2)
elif i == 2:
return np.rot90(image,3)
elif i == 3:
return image
elif i == 4:
return np.fliplr(image)
elif i == 5:
return np.flipud(image)
elif i == 6:
return image.transpose(1,0,2)
elif i == 7:
return np.fliplr(np.rot90(image))
def augment_image(self, image, i):
if i == 0:
return np.rot90(image)
elif i == 1:
return np.rot90(image,2)
elif i == 2:
return np.rot90(image,3)
elif i == 3:
return image
elif i == 4:
return np.fliplr(image)
elif i == 5:
return np.flipud(image)
elif i == 6:
return image.transpose(1,0,2)
elif i == 7:
return np.fliplr(np.rot90(image))
def add_hermitian_half(m_data, data_type='mag'):
if (data_type == 'mag') or (data_type == 'magnitude'):
m_data = np.hstack((m_data , np.fliplr(m_data[:,1:-1])))
elif data_type == 'phase':
m_data[:,0] = 0
m_data[:,-1] = 0
m_data = np.hstack((m_data , -np.fliplr(m_data[:,1:-1])))
elif data_type == 'zeros':
nfrms, nFFThalf = m_data.shape
m_data = np.hstack((m_data , np.zeros((nfrms,nFFThalf-2))))
elif data_type == 'complex':
m_data_real = add_hermitian_half(m_data.real)
m_data_imag = add_hermitian_half(m_data.imag, data_type='phase')
m_data = m_data_real + m_data_imag * 1j
return m_data
# Remove hermitian half of fft-based data:-------------------------------------
# Works for either even or odd fft lenghts.
def mcep_to_lin_sp_log(mgc_mat, nFFT):
nFrms, n_coeffs = mgc_mat.shape
nFFTHalf = 1 + nFFT/2
mgc_mat = np.concatenate((mgc_mat, np.zeros((nFrms, (nFFT/2 - n_coeffs + 1)))),1)
mgc_mat = np.concatenate((mgc_mat, np.fliplr(mgc_mat[:,1:-1])),1)
sp_log = (np.fft.fft(mgc_mat, nFFT,1)).real
sp_log = sp_log[:,0:nFFTHalf]
return sp_log
#Gets RMS from matrix no matter the number of bins m_data has,
#it figures out according to the FFT length.
# For example, nFFT = 128 , nBins_data= 60 (instead of 65 or 128)
def extract_symmetry(self):
"""
Calculate the symmetry of the image by substracting left from right.
Input: None
Output: None
"""
# currently this is only for horizontal symmetry
if len(self.image.shape) == 3:
height, width, _ = self.image.shape
else:
height, width = self.image.shape
if width % 2 != 0:
width -= 1
pixels = height * width
left = self.image[:, :width/2]
right = self.image[:, width/2:-1]
else:
pixels = height * width
left = self.image[:, :width/2]
right = self.image[:, width/2:]
left_gray = color.rgb2gray(left)
right_gray = color.rgb2gray(right)
self.symmetry = np.abs(left_gray -
np.fliplr(right_gray)).sum()/(pixels/1.*2)
def preprocess_A_and_B(img_A, img_B, load_size=286, fine_size=256, flip=True, is_test=False):
if is_test:
img_A = scipy.misc.imresize(img_A, [fine_size, fine_size])
img_B = scipy.misc.imresize(img_B, [fine_size, fine_size])
else:
img_A = scipy.misc.imresize(img_A, [load_size, load_size])
img_B = scipy.misc.imresize(img_B, [load_size, load_size])
h1 = int(np.ceil(np.random.uniform(1e-2, load_size-fine_size)))
w1 = int(np.ceil(np.random.uniform(1e-2, load_size-fine_size)))
img_A = img_A[h1:h1+fine_size, w1:w1+fine_size]
img_B = img_B[h1:h1+fine_size, w1:w1+fine_size]
if flip and np.random.random() > 0.5:
img_A = np.fliplr(img_A)
img_B = np.fliplr(img_B)
return img_A, img_B
# -----------------------------
def flip(image, random_flip):
if random_flip and np.random.choice([True, False]):
image = np.fliplr(image)
return image
def is_cross(self, candidate):
'''
first check the trace
then flip and check the opposite trace
'''
return (candidate.trace()+np.fliplr(candidate).trace()) == (candidate.shape[0]*2)
def load_image_array(image_file, image_size,
image_id, data_dir='Data/datasets/mscoco/train2014',
mode='train'):
img = None
if os.path.exists(image_file):
#print('found' + image_file)
img = skimage.io.imread(image_file)
else:
print('notfound' + image_file)
img = skimage.io.imread('http://mscoco.org/images/%d' % (image_id))
img_path = os.path.join(data_dir, 'COCO_%s2014_%.12d.jpg' % ( mode,
image_id))
skimage.io.imsave(img_path, img)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8')
img_new[:,:,0] = img
img_new[:,:,1] = img
img_new[:,:,2] = img
img = img_new
img_resized = skimage.transform.resize(img, (image_size, image_size))
# FLIP HORIZONTAL WIRH A PROBABILITY 0.5
if random.random() > 0.5:
img_resized = np.fliplr(img_resized)
return img_resized.astype('float32')
def randomHorizontalFlip(rand_seed,img, u=0.5):
if rand_seed < u:
img = cv2.flip(img,1) #np.fliplr(img) #cv2.flip(img,1) ##left-right
return img
def plotmultichannel(data, params=None):
# TODO Receive Labels as arguments
"""
Creates a plot to present multichannel data
Arguments
data: Multichannel Data [n_samples, n_channels]
params: information about the data acquisition device being
"""
plt.figure()
n_samples = data.shape[0]
n_channels = data.shape[1]
if params is not None:
fs = params['sampling frequency']
names = params['names of channels']
else:
fs = 1
names = [""] * n_channels
time_vec = np.arange(n_samples) / float(fs)
data = np.fliplr(data)
offset = 0
for i_channel in range (0, n_channels):
data_ac = data[:,i_channel] - np.mean(data[:,i_channel])
offset = offset + 2 * np.max(np.abs(data_ac))
plt.plot(time_vec, data_ac + offset, label=names[i_channel])
plt.xlabel('Time [s]');
plt.ylabel('Amplitude');
plt.legend()
plt.draw()
def AddNoize(i):
R = random.randint(0, 1)
if (R==1):
i=np.fliplr(i)#random mirroring
R = random.randint(0, 1)
if (R==1):
R = random.randint(-10, 10)
i= ndimage.interpolation.rotate(i,R)#random rotation
R = random.randint(0, 1)
if (R==1):
crop_left=random.randint(0,15)
crop_right = random.randint(1, 15)
crop_top = random.randint(0, 15)
crop_bot = random.randint(1, 15)
i=i[crop_left:-crop_right,crop_top:-crop_bot,:] #Randomcrop
#Next code is VERY SLOW becoase it use Python to change brightness
#need to optimase it, but i have no time yet:)
R = random.randint(0, 2)
if (R==2): #Random brightness in R channel
d = random.random()+1
i[:, :, 0] = adjust_gamma(i[:,:,0],d)
R = random.randint(0, 2)
if (R==2): #Random brightness in G channel
d = random.random()+1
i[:, :, 1] = adjust_gamma(i[:, :, 1], d)
R = random.randint(0, 2)
if (R==2): #Random brightness in B channel
d = random.random()+1
i[:, :, 2] = adjust_gamma(i[:, :, 2], d)
#misc.imsave("test.jpg",i)
return i
#Prepare data for learning
def polynomials2matrix(polynomial):
p = eqsize(polynomial)
nt = sum(nterms(p))
nv = nvars(p[0])
M = zeros((nv, nt), dtype=int32)
inds = [None] * p.size
k = 0
for i in range(0, p.size):
inds.append[i] = range(k, k + nterms(p[i]) - 1)
M[:, k:k + nterms(p[i]) - 1] = monomials(p[i])
k = k + nterms(p[i])
neg_M_sum = -1 * M.sum(axis=0)
M_trans = M.conj().T
neg_M_sum_trans = neg_M_sum.conj().T
M_fliplr = fliplr(M_trans)
new_grev_M = concatenate(neg_M_sum_trans, M_fliplr)
_, ia, ib = unique(new_grev_M)
M = float(M[:, ia])
mon = zeros(M.shape[1], 1)
for i in range(M.shape[1], -1, -1):
mon[i, 1] = Multipol.multipol(1, M[:, i])
C = zeros(p.size, M.shape[0])
for i in range(0, p.size):
ind = ib[inds[i]]
C[i, ind] = coeffs(p[i])
return C, mon
def _random_flip_leftright(batch):
for i in range(len(batch)):
if bool(random.getrandbits(1)):
batch[i] = np.fliplr(batch[i])
return batch
def predict(self, img, flip_evaluation):
"""
Predict segementation for an image.
Arguments:
img: must be rowsxcolsx3
"""
h_ori, w_ori = img.shape[:2]
if img.shape[0:2] != self.input_shape:
print("Input %s not fitting for network size %s, resizing. You may want to try sliding prediction for better results." % (img.shape[0:2], self.input_shape))
img = misc.imresize(img, self.input_shape)
input_data = self.preprocess_image(img)
# utils.debug(self.model, input_data)
regular_prediction = self.model.predict(input_data)[0]
if flip_evaluation:
print("Predict flipped")
flipped_prediction = np.fliplr(self.model.predict(np.flip(input_data, axis=2))[0])
prediction = (regular_prediction + flipped_prediction) / 2.0
else:
prediction = regular_prediction
if img.shape[0:1] != self.input_shape: # upscale prediction if necessary
h, w = prediction.shape[:2]
prediction = ndimage.zoom(prediction, (1.*h_ori/h, 1.*w_ori/w, 1.),
order=1, prefilter=False)
return prediction