def __init__(self, start, end, size, gap, angle=None, align='center', layer=None, datatype=None): self.start=np.array(start) self.end=np.array(end) self.size=np.array(size) self.gap=gap self.align=align pts=np.array([[0,0], [0, size[1]], size, [size[0], 0]]) if angle is not None: pts=rotate(pts, angle, 'com') if align.lower()=='bottom': pass elif align.lower()=='top': pts=translate(pts, (0, -self.size[1])) elif align.lower()=='center': pts=translate(pts, (0, -self.size[1]/2)) else: raise ValueError('Align parameter must be one of bottom/top/center') strip_width=size[0]+gap v=self.end-self.start l=np.sqrt(np.dot(v,v)) N=int(np.floor(l/strip_width)) spacing=v/N rotation=math.atan2(v[1], v[0])*180/np.pi pts=rotate(pts, rotation) origin = start + 0.5* v* (l-(N*strip_width - gap))/l polys=[translate(pts, origin + i*spacing) for i in range(N)] Elements.__init__(self, polys, layer, datatype)
def vicreb_rot(deltas, seed, dim, nA, nB, t_max, v, R_v, L, D_rot, out=None): n = nA + nB np.random.seed(seed) r = np.random.uniform(-L / 2.0, L / 2.0, [n, dim]) u = utils.sphere_pick(n=n, d=dim) As = np.zeros([n], dtype=np.bool) As[:nA] = True Bs = np.logical_not(As) r0 = r.copy() wraps = np.zeros_like(r, dtype=np.int) if out is not None: np.savez(os.path.join(out, 'static.npz'), L=L, As=As, r0=r0, v=v) ums, ums_A, ums_B = [], [], [] for t in range(t_max): abssep = np.abs(r[:, np.newaxis] - r[np.newaxis, :]) seps = np.minimum(abssep, L - abssep) withins = utils.vector_mag_sq(seps) < R_v ** 2.0 u_o = u.copy() u[...] = 0.0 for i_n in range(n): delta_A, delta_B = deltas[not As[i_n]] w_As = np.logical_and(withins[i_n], As) w_Bs = np.logical_and(withins[i_n], Bs) u_net_A = np.sum(u_o[w_As], axis=0) u_net_B = np.sum(u_o[w_Bs], axis=0) u[i_n] += utils.rotate(u_net_A, delta_A)[0] u[i_n] += utils.rotate(u_net_B, delta_B)[0] if np.all(u[i_n] == 0.0): u[i_n] = u_o[i_n] u = utils.vector_unit_nonull(u) u = utils.rot_diff(u, D_rot, 1.0) r += v * u wraps_cur = ((r > L / 2.0).astype(np.int) - (r < -L / 2.0).astype(np.int)) wraps += wraps_cur r -= wraps_cur * L if out is not None: np.savez(os.path.join(out, 'dyn_{:010d}'.format(t)), t=t, r=r, u=u, w=wraps) ums_A.append(utils.vector_mag(np.mean(u[As], axis=0))) ums_B.append(utils.vector_mag(np.mean(u[Bs], axis=0))) ums.append(utils.vector_mag(np.mean(u, axis=0))) return (np.mean(ums_A), scipy.stats.sem(ums_A), np.mean(ums_B), scipy.stats.sem(ums_B), np.mean(ums), scipy.stats.sem(ums), )
def random_full_rotation(img): # rotate either 0, 90, 180 or 270 degrees rot = np.random.randint(0, 4) if rot == 0: return img elif rot == 1: img, _ = utils.rotate(img, 90) elif rot == 2: img, _ = utils.rotate(img, 180) elif rot == 3: img, _ = utils.rotate(img, 270) return img
def process_frame(self, thresholded_frame): if self.area and self.area.is_complete: thresholded_frame = thresholded_frame[self.area.y1:self.area.y2, self.area.x1:self.area.x2] processed_frame = Frame() points = numpy.transpose(thresholded_frame.nonzero()) if not len(points): return # Precalculations tan_half_fov_x = math.tan(self.fov_x/2) tan_half_fov_y = math.tan(self.fov_y/2) # m is the vector from the camera position to the origin m = self.camera_position * -1 w = self.width/2 h = self.height/2 for point in points: img_y, img_x = point if self.area and self.area.is_complete: img_y += self.area.y1 img_x += self.area.x1 # Horizontal angle between platform middle (in image) and point delta_x = float(img_x - self.platform_middle[0])/2 tau = math.atan(delta_x/w*tan_half_fov_x) # Vertical angle delta_y = float(img_y - self.platform_middle[1])/2 rho = math.atan(delta_y/h*tan_half_fov_y) # Rotate vector m around tau and rho to point towards 'point' v = m v = rotate('z', v, tau) # Rotate around z axis for horizontal angle v = rotate('x', v, rho) # Rotate around x axis for vertical angle v = self.get_laser_plane_intersection(v) # Ignore any vertices that have negative z coordinates (pre scaling) if v[2] < 0: continue x,y,z = v*self.scale x,y,z = rotate('z', v, self.rotation_angle) vertex = Vertex(x, y, z) processed_frame.append(vertex) self.processed_frames.append(processed_frame)
def physicsStep_(self): gravity = utils.rotate(self.original_gravity, self.world_angle.get()) self.world.SetGravity(gravity) self.world.Step( self.settings.time_step, self.settings.vel_iters, self.settings.pos_iters)
def findAngle2(data, lat_spacing_guess_px, rot_angle_scan_range_deg=(-10, -5)): """ Find the angle phi (degrees) in scan_range for each lattice axis, under which the image "data" is rotated with respect to the imaging coordinates. Returns [[xphi, xamp, xrchisq, yphi, yamp, yrchisq], [x, xamps, yamps]] """ xamps = [] yamps = [] dx = 0.1 x = numpy.arange(rot_angle_scan_range_deg[0], rot_angle_scan_range_deg[1], dx) for phi in x: temp = data.copy() temp = utils.rotate(temp, phi) xlinescan = temp.sum(axis=0) ylinescan = temp.sum(axis=1) xamps.append(analyzeAutocorrelation(xlinescan, lat_spacing_guess_px)[1]) yamps.append(analyzeAutocorrelation(ylinescan, lat_spacing_guess_px)[1]) xfit, xpars = gauss1d(xamps) yfit, ypars = gauss1d(yamps) xchisq = ((xamps - xfit) ** 2).sum() / 0.003 ** 2 ychisq = ((yamps - yfit) ** 2).sum() / 0.003 ** 2 xrchisq = xchisq / (len(xamps) - 4) yrchisq = ychisq / (len(yamps) - 4) xphi = x[0] + xpars[1] * dx yphi = x[0] + ypars[1] * dx return [[xphi, xpars[0], xrchisq, yphi, ypars[0], yrchisq], [x, xamps, yamps]]
def apply(self, wrench, dt): if self.drag_model.enabled: self.drag_model.u[0] = (self.state.twist.linear[0] - self.wind[0]) self.drag_model.u[1] = -(self.state.twist.linear[1] - self.wind[1]) self.drag_model.u[2] = -(self.state.twist.linear[2] - self.wind[2]) self.drag_model.u[3] = self.state.twist.angular[0] self.drag_model.u[4] = -self.state.twist.angular[1] self.drag_model.u[5] = -self.state.twist.angular[2] self.drag_model.u[0:3] = utils.rotate(self.drag_model.u[0:3], self.state.quaternion) self.drag_model.u[3:6] = utils.rotate(self.drag_model.u[3:6], self.state.quaternion) self.drag_model.limit(-100.0, 100.0) if self.verbose: print utils.pv('self.__class__.__name__') self.f(self.drag_model.u, dt, self.drag_model.y) if self.verbose: utils.pv('self.drag_model') if self.verbose: utils.pv('wrench') if len(wrench): wrench.force.x += -self.drag_model.y[0] wrench.force.y += self.drag_model.y[1] wrench.force.z += self.drag_model.y[2] wrench.torque.x += -self.drag_model.y[3] wrench.torque.y += self.drag_model.y[4] wrench.torque.z += self.drag_model.y[5] else: wrench.force.x = -self.drag_model.y[0] wrench.force.y = self.drag_model.y[1] wrench.force.z = self.drag_model.y[2] wrench.torque.x = -self.drag_model.y[3] wrench.torque.y = self.drag_model.y[4] wrench.torque.z = self.drag_model.y[5] if self.verbose: utils.pv('wrench') return wrench
def resize(self, vec1, vec2): level = self.level self.destroy() w,h = self.size vec1 = utils.rotate(vec1 - self.position, -self.angle) vec2 = utils.rotate(vec2 - self.position, -self.angle) try: w *= 1. * vec2[0] / vec1[0] h *= 1. * vec2[1] / vec1[1] except ZeroDivisionError: pass #whatever w = max(w, 0.1) h = max(h, 0.1) self.size = (w,h) self.create(level)
def actonK(self,k,ig): ''' Get the k' vector after group action on k specified by ig k: the input k-vector. ig: specify the group element to act on k. ''' #get the transformation to k: G^-1(ig)*k k1=rotate(k,ig*pi*2/self.n) return k1
def stopGrab(self): if self.grabJoint: self.level.world.DestroyJoint(self.grabJoint) self.grabJoint = None offs = b2d.b2Vec2(self.radius*1.5, self.radius*1.5) offs = utils.rotate(offs, self.level.world_angle.get()) saypos = self.body.position + offs self.level.putStaticActor(SaySomething(saypos), removeAfter = 1) self.candy.release() self.candy = None
def ai(self, themap, engine): if self.hp > 0: lx,ly = self.lp[0] rx,ry = self.rp[0] pcoords = tuple(themap.player.coords) if pcoords in self.los: self.playermemory = pcoords if pcoords in self.loe: engine.attack(self,themap.player) else: self.move(themap) elif pcoords in self.lp and themap.passable(lx,ly): rotate(self,"snwe"[self.facing]) elif pcoords in self.rp and themap.passable(rx,ry): rotate(self,"nswe"[self.facing]) else: self.move(themap)
def straighten(self, stepsize=3, low_angle=-5, high_angle=5): # width is shape[1], height is shape[0] #cv2.imwrite("tmp//before.jpg", self.img) origWidth = self.img.shape[1] if low_angle < -20 or high_angle > 20: raise Exception("Photo is too skewed. Please straighten photo before trying to process it") img = resize(self.img, width=600) # for some reason, straightening works better at this width :-?? # straighten out images # using histograms: rotate +-5 in .3 steps, get max of each histogram # and ideal rotation is argmax of those maxes simg = img hists = [] rng = list(range(low_angle*stepsize, high_angle*stepsize)) bincount = 600 if img.shape[0] > 600 else img.shape[0] for ang in rng: pimg = rotate(simg, ang/float(stepsize), fixed=True) # was true, but doesn't make sense and doens't work # pimg = rotate(simg, ang/float(stepsize)) # cv2.imwrite("tmp//rotate %d.jpg" % ang, pimg) hist, _ = np.histogram(pimg.sum(axis=1), bincount) #plt.plot(hist) #plt.savefig('tmp//hist %d.png' % ang, bbox_inches='tight') #plt.close() hists.append(max(hist)) rot = np.argmax(hists) # if the best rotation angle is the one on the edge of our threshold, try to rotate again with an extended # threshold in that direction if rot == 0: self.straighten(low_angle=low_angle-5, high_angle=high_angle-5) elif rot == len(rng) - 1: self.straighten(low_angle=low_angle+5, high_angle=high_angle+5) img = rotate(self.img, rng[rot]/float(stepsize), fixed=False) # otsu's method removes # background noise better # self.img = img.resize(w=origWidth//2) # so that all letters are small enough self.img = resize(img, width=600) # maybe I should look at average size of a blob ?
def stupid_user(usernum, rotate_tested = 10, rotate_module=10, accepted_results=15, test=False): results = dict.fromkeys(range(0,150), 0) reached_leafs = [1000] * 150 train_set = complete_train_set(usernum) all_sets = parted_all_for_user(usernum) for jj in range(0, rotate_module): pztree = PZFTree(rotate(train_set, randint(0,5000))) print "Avg tree depth = {0}".format(pztree.avg_tree_depth) # for i, run_set in enumerate(all_sets[50:], start=50): for i, run_set in enumerate(all_sets, start=0): for j in range(0,3): run_set= rotate(run_set,randint(0,len(run_set))) res_p, leafs_run = pztree.run_seq_weigted(run_set, factor=25) if res_p > results[i]: results[i] = res_p if leafs_run < reached_leafs[i]: reached_leafs[i] = leafs_run lst_leafs = pick_best_leafs(reached_leafs, accepted_results) lst_prob = pick_best(results, test_data[usernum], reached_leafs, rotate_module, accepted_results) # lst_prob = [] to_csv = [0]*150 hits_leafs = 0 hits_prob = 0 # compare_results(lst_leafs,lst_prob, test_data[usernum]) for loc in lst_leafs: to_csv[loc] = 1 if test: if test_data[usernum][loc]==1: print "Hit Leafs: " + str(loc) hits_leafs += 1 for loc in lst_prob: # to_csv[loc] = 1 if test: if test_data[usernum][loc]==1: print "Hit prob: " + str(loc) hits_prob += 1 return hits_leafs, hits_prob, len(lst_leafs), len(lst_prob), to_csv
def actonK(self,k,ig): ''' Get the k' vector after group action on k specified by ig k: the input k-vector. ig: specify the group element to act on k. ''' #get the transformation to k: G^-1(ig)*k k1=rotate(k,ig*pi*2/self.n) if ig>=self.ng/2: #image about the y axis k1=sv(k1,n=array([1.0,0.0])) return k1
def drawHand(self, graphics): if not self.grabJoint: return a = self.grabJoint.GetAnchor1() b = self.grabJoint.GetAnchor2() pos = (a+b)/2. h = (a-b).Length()/2. w = h/4. right = utils.rotate(b2d.b2Vec2(-10,0), self.level.world_angle.get()) angle = utils.angle_between(right, b-a)*180/math.pi-90 graphics.putSprite( pos, self.grab_spr_name, (w,h), angle=angle)
def findAngle(data, length_guess, scan_range=(-12, -4)): """ Finds the angle phi in scan_range, under which the image in "data" is rotated with respect to the imaging coordinates. The image must contain at least one lattice structure in one direction for this to work. """ breiten_neu = [] breiten_alt = [] x = numpy.arange(scan_range[0], scan_range[1], 0.1) for phi in x: temp = data.copy() temp = utils.rotate(temp, phi) linescan_neu = temp.sum(axis=0) linescan_alt = temp.sum(axis=1) breiten_neu.append(analyzeAutocorrelation(linescan_neu, length_guess)[1]) breiten_alt.append(analyzeAutocorrelation(linescan_alt, length_guess)[1]) def fitfunction(p, xachse): return p[0] * numpy.exp(-((xachse - p[1]) / p[2]) ** 2) + p[3] def errorfunction(p, xachse, data): return data - fitfunction(p, xachse) (pars_neu, success_neu) = optimize.leastsq( errorfunction, [0.15, scan_range[len(scan_range) // 2], 5, 0], args=(x, breiten_neu) ) (pars_alt, success_alt) = optimize.leastsq( errorfunction, [0.15, scan_range[len(scan_range) // 2], 5, 0], args=(x, breiten_alt) ) (neu, alt) = (True, True) if pars_neu[0] < 0.12: neu = False if pars_alt[0] < 0.12: alt = False if not alt and not neu: raise Exception, "No lattice structure found" phi = (pars_neu[1] * neu + pars_alt[1] * alt) / (alt + neu) return phi
def draw(self, graphics): #super(Gorilla, self).draw(graphics) right = utils.rotate(b2d.b2Vec2(-10,0), self.level.world_angle.get()) if self.body.linearVelocity.Length()<1: angle = 0. else: angle = utils.angle_between(right, self.body.linearVelocity-right) angle = int(angle * 180 / math.pi) if self.hasCandy(): sprite = self.happy_spr_name else: sprite = self.spr_name graphics.putSprite( self.body.position, sprite, (self.radius, self.radius), angle=angle, flipX = True, flipY = abs(angle)>90) self.drawHand(graphics)
def vicrot(delta, n, seed, dim, t_max, v, R_v, L, D_rot, out=None): np.random.seed(seed) r = np.random.uniform(-L / 2.0, L / 2.0, [n, dim]) u = utils.sphere_pick(n=n, d=dim) r0 = r.copy() wraps = np.zeros_like(r, dtype=np.int) if out is not None: np.savez(os.path.join(out, 'static.npz'), L=L, r0=r0, v=v) ums = [] for t in range(t_max): abssep = np.abs(r[:, np.newaxis] - r[np.newaxis, :]) seps = np.minimum(abssep, L - abssep) withins = utils.vector_mag_sq(seps) < R_v ** 2.0 u_o = u.copy() u[...] = 0.0 for i_n in range(n): u_net = np.sum(u_o[withins[i_n]], axis=0) u[i_n] = utils.rotate(u_net, delta) u = utils.vector_unit_nonull(u) u = utils.rot_diff(u, D_rot, 1.0) r += v * u wraps_cur = ((r > L / 2.0).astype(np.int) - (r < -L / 2.0).astype(np.int)) wraps += wraps_cur r -= wraps_cur * L if out is not None: np.savez(os.path.join(out, 'dyn_{:010d}'.format(t)), t=t, r=r, u=u, w=wraps) ums.append(utils.vector_mag(np.mean(u, axis=0))) return np.mean(ums), scipy.stats.sem(ums)
def key_expand(key, nr, nk): expanded = [k for k in key] tmp = [0]*4 rcon_iter = 1 # size is either 16, 24 or 42 byte size = nk*4 # length of the expended keysize is either # 176, 208 or 240, depending on the keysize expanded_keysize = (nr+1)*16 currentsize = size while currentsize < expanded_keysize: for i in range(4): tmp[i] = expanded[(currentsize-4)+i] if currentsize%size == 0: tmp = rotate(tmp) for i in range(4): tmp[i] = S[tmp[i]] tmp[0] = tmp[0]^RCON[rcon_iter] rcon_iter += 1 # Add an extra s-box for 256 bit keys if currentsize%size == 16 and size==32: for i in range(4): tmp[i] = S[tmp[i]] for i in range(4): expanded.append(expanded[currentsize-size]^tmp[i]) currentsize += 1 return expanded
def to_body(self, v): """ Convert vel/accel from world frame to body frame """ return utils.rotate(v, self.inverse_quaternion)
def admin_inner(client, nick, crawler): if nick not in client.mod_conf['admin']['admins']: return 'You do not have administrator privileges!' try: cmd = crawler.normal().lower() text = crawler.chain except IndexError: cmd = 'help' ### Position ############# if cmd == 'sit': client.sit() elif cmd == 'stand': client.stand() elif cmd == 'face': client.face(crawler.chain[0]) ### Joke moves ########### elif cmd == 'spin': args = ['l', 's', '4'] if not text else text.split() rot = ['n', 'e', 's', 'w'] rot = rotate(rot, rot.index(args[1][0].lower())) if args[0][0].lower() == 'l': rot.reverse() rot *= int(args[2]) client.emote(10) client.sleep(600) for d in rot: client.face(d) client.sleep(300) client.sleep(300) client.emote(115) elif cmd == 'juke': # 2 args or no args if len(crawler) not in (0, 2): return 'Bad args! See the help sub-command.' args = ['u', 's'] if not text else text.lower().split() e_up = args[0][0] == 'u' s_dir = args[1][0] f2 = 'n' if s_dir in 'ew' else 'w' f3 = 's' if s_dir in 'ew' else 'e' main = ['d', s_dir, '.500', ':122', '.500'] routine = ['u', 'd', 'u', 'd', 'u', f2, s_dir, f2, s_dir, f3, s_dir, f3, s_dir, 'd', 'u', 'd', ':127'] routine += ['u'] if e_up else [] for p in routine: main.append(p) main.append('.500') for p in main: if p[0] == '.': client.sleep(int(p[1:])) elif p[0] == ':': client.emote(int(p[1:])) elif p == 'u': client.stand() elif p == 'd': client.sit() else: client.face(p) ### Communications ####### elif cmd == 'emote': client.emote(crawler.chain) elif cmd == 'say': client.msg(crawler.chain) elif cmd == 'whisper': # Need the last arg first :-/ crawler.flip() to = crawler.quoted() crawler.flip() client.whisper(to, crawler.chain) ### Interaction ########## elif cmd == 'attack': whom = crawler.quoted() being_id = client.mod_whois_nmap.get(whom) if not being_id: if whom.isdigit(): being_id = int(whom) else: return 'Sorry, I don\'t know that name.' name = client.mod_whois_imap.get(being_id) if name: more = ' (%s)' % name else: more = '' client.whois(being_id) text = crawler.chain keep = not text or text[0].lower() in 'yt' client.attack(being_id, keep) return 'Attacking %s%s!' % (being_id, more) elif cmd == 'goto': x, y = text.split() client.goto(int(x), int(y)) ### Information ########## elif cmd == 'names': return ',\n'.join( ', '.join('%s=%s' % pair for pair in ten) for ten in isection(client.mod_whois_imap.items(), 10) ) elif cmd == 'pos': return 'x=%s, y=%s' % tuple(client.pos) ### Resetters ############ elif cmd == 'quit': client.done = True elif cmd == 'respawn': client.respawn() elif cmd == 'refresh': if rebuild_prices.rebuild(): return 'Successfully rebuilt TMW price DB!' else: return 'Rebuilding the TMW price DB failed!' elif cmd == 'reload': for mod in client.installed_mods.values(): reload(mod) commands.setup_commands(client) return 'Successfully reloaded all mods installed on this bot.' ### Help ################# elif cmd == 'help': return '\n'.join([ '`sit` to sit; `stand` to stand; ' '`face n|s|e|w` to face a particular direction;', '`spin [l|r] [n|s|e|w] [num]` to make the bot spin rapidly; ' '`juke [u|d] [n|s|e|w]` to execute a lame move sequence;', '`emote <number>` to display an emote; ' '`say <some message>` to say something; ' '`whisper <some thing> to <player>` to whisper to a player;', '`goto <x> <y>` to move the bot;', '`names` to see all the names that the bot recognizes;', '`respawn` to respawn; ' '`refresh` to update the db of TMW prices (long!); ' '`reload` to reload all mods installed on this bot.' ]) else: return 'Unknown command `%s`; see the `help` sub-command.' % cmd
def from_body(self, v): """ Conver vel/accel from body frame to world frame """ return utils.rotate(v, self.quaternion)
def getOriginalVec(self, *args): vec = b2d.b2Vec2(*args) return utils.rotate(vec, self.world_angle.get())
def generate_hdf5(ftxt, output, fname, argument=False): data = getDataFromTxt(ftxt) F_imgs = [] F_landmarks = [] EN_imgs = [] EN_landmarks = [] NM_imgs = [] NM_landmarks = [] for (imgPath, bbox, landmarkGt) in data: img = cv2.imread(imgPath, cv2.CV_LOAD_IMAGE_GRAYSCALE) assert(img is not None) logger("process %s" % imgPath) # F f_bbox = bbox.subBBox(-0.05, 1.05, -0.05, 1.05) f_face = img[f_bbox.top:f_bbox.bottom+1,f_bbox.left:f_bbox.right+1] ## data argument if argument and np.random.rand() > -1: ### flip face_flipped, landmark_flipped = flip(f_face, landmarkGt) face_flipped = cv2.resize(face_flipped, (39, 39)) F_imgs.append(face_flipped.reshape((1, 39, 39))) F_landmarks.append(landmark_flipped.reshape(10)) ### rotation if np.random.rand() > 0.5: face_rotated_by_alpha, landmark_rotated = rotate(img, f_bbox, \ bbox.reprojectLandmark(landmarkGt), 5) landmark_rotated = bbox.projectLandmark(landmark_rotated) face_rotated_by_alpha = cv2.resize(face_rotated_by_alpha, (39, 39)) F_imgs.append(face_rotated_by_alpha.reshape((1, 39, 39))) F_landmarks.append(landmark_rotated.reshape(10)) ### flip with rotation face_flipped, landmark_flipped = flip(face_rotated_by_alpha, landmark_rotated) face_flipped = cv2.resize(face_flipped, (39, 39)) F_imgs.append(face_flipped.reshape((1, 39, 39))) F_landmarks.append(landmark_flipped.reshape(10)) ### rotation if np.random.rand() > 0.5: face_rotated_by_alpha, landmark_rotated = rotate(img, f_bbox, \ bbox.reprojectLandmark(landmarkGt), -5) landmark_rotated = bbox.projectLandmark(landmark_rotated) face_rotated_by_alpha = cv2.resize(face_rotated_by_alpha, (39, 39)) F_imgs.append(face_rotated_by_alpha.reshape((1, 39, 39))) F_landmarks.append(landmark_rotated.reshape(10)) ### flip with rotation face_flipped, landmark_flipped = flip(face_rotated_by_alpha, landmark_rotated) face_flipped = cv2.resize(face_flipped, (39, 39)) F_imgs.append(face_flipped.reshape((1, 39, 39))) F_landmarks.append(landmark_flipped.reshape(10)) f_face = cv2.resize(f_face, (39, 39)) en_face = f_face[:31, :] nm_face = f_face[8:, :] f_face = f_face.reshape((1, 39, 39)) f_landmark = landmarkGt.reshape((10)) F_imgs.append(f_face) F_landmarks.append(f_landmark) # EN # en_bbox = bbox.subBBox(-0.05, 1.05, -0.04, 0.84) # en_face = img[en_bbox.top:en_bbox.bottom+1,en_bbox.left:en_bbox.right+1] ## data argument if argument and np.random.rand() > 0.5: ### flip face_flipped, landmark_flipped = flip(en_face, landmarkGt) face_flipped = cv2.resize(face_flipped, (31, 39)).reshape((1, 31, 39)) landmark_flipped = landmark_flipped[:3, :].reshape((6)) EN_imgs.append(face_flipped) EN_landmarks.append(landmark_flipped) en_face = cv2.resize(en_face, (31, 39)).reshape((1, 31, 39)) en_landmark = landmarkGt[:3, :].reshape((6)) EN_imgs.append(en_face) EN_landmarks.append(en_landmark) # NM # nm_bbox = bbox.subBBox(-0.05, 1.05, 0.18, 1.05) # nm_face = img[nm_bbox.top:nm_bbox.bottom+1,nm_bbox.left:nm_bbox.right+1] ## data argument if argument and np.random.rand() > 0.5: ### flip face_flipped, landmark_flipped = flip(nm_face, landmarkGt) face_flipped = cv2.resize(face_flipped, (31, 39)).reshape((1, 31, 39)) landmark_flipped = landmark_flipped[2:, :].reshape((6)) NM_imgs.append(face_flipped) NM_landmarks.append(landmark_flipped) nm_face = cv2.resize(nm_face, (31, 39)).reshape((1, 31, 39)) nm_landmark = landmarkGt[2:, :].reshape((6)) NM_imgs.append(nm_face) NM_landmarks.append(nm_landmark) #imgs, landmarks = process_images(ftxt, output) F_imgs, F_landmarks = np.asarray(F_imgs), np.asarray(F_landmarks) EN_imgs, EN_landmarks = np.asarray(EN_imgs), np.asarray(EN_landmarks) NM_imgs, NM_landmarks = np.asarray(NM_imgs),np.asarray(NM_landmarks) F_imgs = processImage(F_imgs) shuffle_in_unison_scary(F_imgs, F_landmarks) EN_imgs = processImage(EN_imgs) shuffle_in_unison_scary(EN_imgs, EN_landmarks) NM_imgs = processImage(NM_imgs) shuffle_in_unison_scary(NM_imgs, NM_landmarks) # full face base = join(OUTPUT, '1_F') createDir(base) output = join(base, fname) logger("generate %s" % output) with h5py.File(output, 'w') as h5: h5['data'] = F_imgs.astype(np.float32) h5['landmark'] = F_landmarks.astype(np.float32) # eye and nose base = join(OUTPUT, '1_EN') createDir(base) output = join(base, fname) logger("generate %s" % output) with h5py.File(output, 'w') as h5: h5['data'] = EN_imgs.astype(np.float32) h5['landmark'] = EN_landmarks.astype(np.float32) # nose and mouth base = join(OUTPUT, '1_NM') createDir(base) output = join(base, fname) logger("generate %s" % output) with h5py.File(output, 'w') as h5: h5['data'] = NM_imgs.astype(np.float32) h5['landmark'] = NM_landmarks.astype(np.float32)
print 'regenerating '+pair[0]+' with label '+pair[1] image = skimage.io.imread(Image_Path+filename) transformed_img = random_crop(image) skimage.io.imsave(Image_Path+str(next_image_num)+'.png',transformed_img) rep_image_label_file.write(str(next_image_num)+'.png '+pair[1].split('\n')[0]+'\n') next_image_num += 1 # do random rotate # int(augment_fraction*train_image_num) aug_idxs = np.random.choice(train_image_num, int(augment_fraction*train_image_num), replace=False)+1 for augidx in aug_idxs: filename = str(augidx)+'.png' pair = train_image_labels[augidx-1].split(' ') print 'regenerating '+pair[0]+' with label '+pair[1] image = skimage.io.imread(Image_Path+filename) transformed_img = rotate(image) skimage.io.imsave(Image_Path+str(next_image_num)+'.png',transformed_img) rep_image_label_file.write(str(next_image_num)+'.png '+pair[1].split('\n')[0]+'\n') next_image_num += 1 # for augidx in aug_idxs: # filename = str(augidx)+'.png' # image = skimage.io.imread(Image_Path+filename) # # do some transform here # print image.shape # # skimage.io.imshow(image) # skimage.io.show() # # test_img = random_crop(image)
modo = [TONO, TONO, SEMITONO, TONO, TONO, TONO, SEMITONO] inicio = 0 # Existen 8 modos, se obtienen rotando los intervalos de la escala for i in range(8): actual = inicio frecuencias_modo = [frecuencias[actual]] for intervalo in modo: actual += intervalo frecuencias_modo.append(frecuencias[actual]) notas += frecuencias_modo inicio += modo[0] modo = rotate(modo) muestras_por_segundo = 44100 duracion = 0.5 muestras_totales = duracion * muestras_por_segundo muestras = [] for frecuencia in notas: ciclos_por_muestra = frecuencia / muestras_por_segundo incremento = 2 * math.pi * ciclos_por_muestra fase = 0 for i in range(int(muestras_totales)):
def set_state(self, state): self.tf = utils.rotate(state[0]) for line in self.lines: line.set_tf(self.tf)
escala = [TONO, TONO, SEMITONO, TONO, TONO, TONO, SEMITONO] # Pueden obtenerse 7 acordes por cada escala inicio = 0 for x in range(8): actual = inicio notas = [frecuencias[actual]] for grupo in grouper(escala, 2, 0): actual += sum(grupo) notas.append(frecuencias[actual]) acordes.append(notas) inicio += escala[0] escala = rotate(escala) muestras_por_segundo = 44100 duracion = 2 muestras_totales = duracion * muestras_por_segundo muestras = [] for indice, acorde in enumerate(acordes): inicio_acorde = indice * duracion * muestras_por_segundo for frecuencia in acorde: ciclos_por_muestra = frecuencia / muestras_por_segundo incremento = 2 * math.pi * ciclos_por_muestra