def get_diffs(mod_frame, inp_frame): model_points, ratios_m = get_points(mod_frame, 368, 368) input_points, ratios_i = get_points(inp_frame, 368, 368) right_arm = [[2, 3], [3, 4], [2, 4], [2, 3, 4]] left_arm = [[5, 6], [6, 7], [5, 7], [5, 6, 7]] right_leg = [[8, 9], [9, 10], [8, 10], [8, 9, 10]] left_leg = [[11, 12], [12, 13], [11, 13], [11, 12, 13]] funcs = [abs_angle, abs_angle, abs_angle, rel_angle] limbs = [right_arm, left_arm, right_leg, left_leg] limb_diffs = [] limb_diff = [] weights = [.5, .5, .75, .25] for limb in limbs: input_angles = [] model_angles = [] for i in range(len(limb)): model_angles.append(funcs[i](model_points, limb[i])) input_angles.append(funcs[i](input_points, limb[i])) diffs = [] total_diff = 0 for i in range(len(model_angles)): di = abs(model_angles[i] - input_angles[i]) diffs.append(min([di, 360 - di])) total_diff += diffs[i] / 360.0 * weights[i] total_diff /= len(diffs) limb_diffs.append(diffs) limb_diff.append(total_diff) return limb_diff, model_points, input_points, ratios_i, ratios_m
def predict_fiducial(): svm = mlpy.LibSvm.load_model("svm.model") image = "/home/varun/Projects/FEAR/Dataset/cohn-kanade-images/S005/001/S005_001_00000001.png" landmarks = "/home/varun/Projects/FEAR/Dataset/Landmarks/S005/001/S005_001_00000001_landmarks.txt" points = utils.get_points(landmarks) gabor = fear.get_gabor_images(image) x = pack_gabor_images(gabor) y = svm.pred(x) img = cv2.imread(image) (h, w, c) = img.shape # utils.mark(image, points[0][0], points[0][1]) print y[points[0][0] * h + points[0][1]] # for i in range(len(x)): for i in y: # y = svm.pred(numpy.array(x[i])) if i > 0.0: print i # utils.mark(image, i/490, i%640) print y
def show_component(self, from_, to_, leads_names, component): centers = get_points(self.ecg_node, component, n_in_triple=1) center = centers[1] from_ = center - from_ to_ = center + to_ self.ecg_to_fig(leads_names, from_, to_) plt.show()
def train(self): self.start_time = time() for epoch_no in range(1, self.agent.nb_epochs + 1): for game_no in tqdm(range(len(self.env.games))): obs, infos = self.env.reset() self.agent.train() scores = [0] * len(obs) dones = [False] * len(obs) steps = [0] * len(obs) while not all(dones): # Increase step counts. steps = [ step + int(not done) for step, done in zip(steps, dones) ] commands = self.agent.act(obs, scores, dones, infos) obs, scores, dones, infos = self.env.step(commands) # Let the agent know the game is done. self.agent.act(obs, scores, dones, infos) score = sum(scores) / self.agent.batch_size score, possible_points, percentage = get_points( score, infos['extra.walkthrough'][0]) print('Score: {}/{}'.format(score, possible_points))
def _preprocess(self, warped_img): ''' Preprocess the warped and rotated image. @warped_img: np.array, it should be the output of self._polar_warp_and_rotate(). @return: (s_mask, output_img), saturation mask and image after preprocessing. ''' warped_img = cv.GaussianBlur(warped_img, (3, 3), 1.5) hsv = cv.cvtColor(warped_img, cv.COLOR_BGR2HSV) warped_img = cv.cvtColor(warped_img, cv.COLOR_BGR2GRAY) warped_img = cv.equalizeHist(warped_img) # Enhance contrast _, s, _ = cv.split(hsv) _, s = cv.threshold(s, 0, 255, cv.THRESH_OTSU) s = cv.morphologyEx(s, cv.MORPH_ERODE, np.ones((5, 5))) _, contours, _ = cv.findContours(s, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=lambda ctr: cv.contourArea(ctr) ) # Sort to choose the largest area mask = cv.drawContours(np.zeros((warped_img.shape), np.uint8), contours, len(contours) - 1, (255, 255, 255), thickness=1) box = cv.boundingRect(get_points(mask)) # Largest area box-bouding mask = cv.rectangle(mask, (box[0], box[1]), (box[0] + box[2], box[1] + box[3]), (255, 255, 255), cv.FILLED) # Fill the area that is to be removed mask = cv.bitwise_not(mask) # Ensure tooth existing area return mask, warped_img
def predict_fiducial(): svm = mlpy.LibSvm.load_model('svm.model') image = "/home/varun/Projects/FEAR/Dataset/cohn-kanade-images/S005/001/S005_001_00000001.png" landmarks = "/home/varun/Projects/FEAR/Dataset/Landmarks/S005/001/S005_001_00000001_landmarks.txt" points = utils.get_points(landmarks) gabor = fear.get_gabor_images(image) x = pack_gabor_images(gabor) y = svm.pred(x) img = cv2.imread(image) (h, w, c) = img.shape #utils.mark(image, points[0][0], points[0][1]) print y[points[0][0]*h + points[0][1]] #for i in range(len(x)): for i in y: #y = svm.pred(numpy.array(x[i])) if i > 0.0: print i #utils.mark(image, i/490, i%640) print y
def command_beg(self, data): if get_points(self, self.user) < 5: success = add_points(self, self.user, 5) if success: return '%s tosses %s 5 %s out of pity.' % (NICKNAME, self.user, self.currency_name) else: return 'Get outta here %s! You\'re not broke!' % self.user
def give_points(from_usr, to_usr, amount): if from_usr not in ADMIN: return '@{} you are not permitted to do that'.format(from_usr) points = get_points(to_usr) points += int(amount) store_points(to_usr, points) return '@{} just received {} points from admin {}!!!'\ .format(to_usr, from_usr, amount)
def point_transfer(from_usr, to_usr, amount): if amount < 1: return '@{} transfer value must be more zero'.format(from_usr) usr_points = get_points(from_usr) recipient_points = get_points(to_usr) if usr_points < amount: return '@{} You only have {} points!'.format(from_usr, usr_points) usr_points -= int(amount) recipient_points += int(amount) store_points(from_usr, usr_points) store_points(to_usr, recipient_points) return '@{} sent @{} {} points, what a pal'.format( from_usr, to_usr, amount)
def get_raw_kernel(): json_data = get_7_helthy_json() json_node = json_data[list(json_data.keys())[0]] points = get_points(json_node, "qrs", 1) point = points[1] signal = get_lead_signal(json_node, 'i') from_= point - 100 to_ = point + 100 return signal[from_:to_]
def run_sfx(user, effect_name): points = get_points() if points >= MIN_POINTS: # if true, the sfx played and the file existed if play_sfx(user, effect_name): points -= 5 store_points(user, points) return '@{} played {}'.format(user.effect_name) # if false the sfx does not exist return False, '@{} that effect doesnt exist'.format(user) return '@{} you dont have enough points'.format(user)
def show_dataset(): root_dir = '/home/varun/Projects/FEAR/Dataset/' image_root = root_dir + 'cohn-kanade-images' landmarks_root = root_dir + 'Landmarks' image1_list = os.listdir(image_root) image1_list.sort() landmark1_list = os.listdir(landmarks_root) landmark1_list.sort() #print len(image1_list) for f1 in image1_list[:1]: image1 = os.path.join(image_root, f1) landmark1 = os.path.join(landmarks_root, f1) image2_list = os.listdir(image1) image2_list.sort() landmark2_list = os.listdir(landmark1) landmark2_list.sort() for f2 in image2_list: image2 = os.path.join(image1, f2) landmark2 = os.path.join(landmark1, f2) images = os.listdir(image2) images.sort() landmarks = os.listdir(landmark2) landmarks.sort() for i in range(len(images)): image_file = os.path.join(image2, images[i]) landmark_file = os.path.join(landmark2, landmarks[i]) print "File: %s" % image_file points = utils.get_points(landmark_file) gabors = fear.get_gabor_images(image_file) train_SVMs(gabors, points)
def show_dataset(): root_dir = "/home/varun/Projects/FEAR/Dataset/" image_root = root_dir + "cohn-kanade-images" landmarks_root = root_dir + "Landmarks" image1_list = os.listdir(image_root) image1_list.sort() landmark1_list = os.listdir(landmarks_root) landmark1_list.sort() # print len(image1_list) for f1 in image1_list[:1]: image1 = os.path.join(image_root, f1) landmark1 = os.path.join(landmarks_root, f1) image2_list = os.listdir(image1) image2_list.sort() landmark2_list = os.listdir(landmark1) landmark2_list.sort() for f2 in image2_list: image2 = os.path.join(image1, f2) landmark2 = os.path.join(landmark1, f2) images = os.listdir(image2) images.sort() landmarks = os.listdir(landmark2) landmarks.sort() for i in range(len(images)): image_file = os.path.join(image2, images[i]) landmark_file = os.path.join(landmark2, landmarks[i]) print "File: %s" % image_file points = utils.get_points(landmark_file) gabors = fear.get_gabor_images(image_file) train_SVMs(gabors, points)
import cv2 import utils as utils IMAGE_REPLACE = "../images/dog.jpeg" cap = cv2.VideoCapture(0) gabarito = cv2.imread("../images/board_aruco.png") foto = utils.read_img(IMAGE_REPLACE, gabarito) corners_or, ids_or = utils.detect_markers(gabarito) while (True): ret, frame = cap.read() corners_dest, ids_dest = utils.detect_markers(frame) if len(corners_dest) > 0: origin, dest = utils.get_points(ids_or, ids_dest, corners_or, corners_dest) warped_img = utils.warp_image(origin, dest, (frame.shape[0], frame.shape[1]), foto) frame = utils.merge_images(warped_img, frame) cv2.namedWindow('frame', cv2.WINDOW_NORMAL) cv2.resizeWindow('frame', 1920, 1080) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
import sys import utils import time start__ = time.time() input_file = sys.argv[1] k = int(sys.argv[2]) output_file = sys.argv[3] data = utils.get_points(input_file) ds, retain_set, ds_track = utils.bfr_init(data, k) retain_set, cs, cs_track = utils.bfr_form_cs(retain_set, {}) f = open(output_file, "w+") f.write("The intermediate results:\n") f.write("Round 1: " + str(utils.get_number_of_points_in_ds(ds)) + "," + str(len(cs)) + "," + str(utils.get_number_of_points_in_ds(cs)) + "," + str(len(retain_set))) f.write("\n") start = 0.2 end = 0.4 for i in range(4): ds, cs, retain_set, ds_track, cs_track = utils.bfr_main(ds, cs, retain_set, data[int(len(data)*start):int(len(data)*end)], ds_track, cs_track)
height = utils.get_height(bita) last_layer = int(height * n_layers // bita.shape[2]) # indx of the highest slice flags = segmentation.find_chin(bita, flags) ll, rl, bd, la, hd, ra = segmentation.frame_parser(x, y, z, b, d, flags) flags = segmentation.flag_parser(flags, ll, rl, bd, la, hd, ra, last_layer) flags = segmentation.find_chest_th(bita, bd, flags) segs = [ll, rl, bd, la, hd, ra] segs = [interp(x) for x in segs] tic = time() # with raw data bita_, _ = utils.ostu3d(data_) pts_ = utils.get_points(bita_, thresh=0) labels_ = segmentation.get_labels(pts_, flags, segs, ratio=ratio) print('labling takes {}s.'.format(time() - tic)) # for vis # tic = time() # pts = utils.get_points(bita, thresh=0) # labels = segmentation.get_labels(pts, flags, segs, ratio=1) if ifplot: utils.seg_vis2d(pts, labels, bita, savefig=True, fname=fname) print('visualization takes {}s'.format(time() - tic)) segs_ = [ np.array([ np.hstack([
def command_random(instance, data): global timeout if instance.user in timeout: d = datetime.now() - timeout[instance.user] if d.seconds < 60: return True timeout[instance.user] = datetime.now() # ##temp joke # global dj_joke # if dj_joke == False: # global dj_count # if dj_count > 10: # if 'dj_rezurrection' in instance.recent_chatters: # instance.cur.execute('SELECT amount FROM currency WHERE user = "******"') # current_points = instance.cur.fetchone()[0] # dj_joke = True # return 'dj_rezurrection loses %s gil (100%%)' % current_points # dj_count += 1 # ##end temp joke users = list(instance.recent_chatters) users.append(settings.CHANNEL_NAME) users += [instance.user] * 95 user = random.choice(users) other_users = list(instance.recent_chatters) if settings.CHANNEL_NAME not in other_users: other_users.append(settings.CHANNEL_NAME) if user in other_users: other_users.pop(other_users.index(user)) if len(other_users) == 0: other_user = None else: other_user = random.choice(other_users) verb = random.choice(VERBS) if other_user == None and verb == 'gives': verb = 'gains' percent = random.choice(RAND_OPTS) # if verb == 'loses': current_points = get_points(instance, user) change_points = int(round(current_points * (float(percent)/float(100)), 0)) if change_points == 0: change_points = 1 if current_points != 0: percent = int(round((float(change_points)/float(current_points)) * 100)) else: percent = 'inf' # else: # change_points = percent # percent = None if verb in ['gains', 'loses']: if verb == 'gains': instance.cur.execute('UPDATE currency SET amount = amount + ? WHERE user = ?', (change_points, user)) elif verb == 'loses': instance.cur.execute('UPDATE currency SET amount = amount - ? WHERE user = ?', (change_points, user)) instance.con.commit() if percent: return '%s %s %s %s (%s%%)' % (user, verb, change_points, instance.fmt_currency_name(change_points), percent) else: return '%s %s %s %s' % (user, verb, change_points, instance.fmt_currency_name(change_points)) elif verb == 'gives': instance.cur.execute('UPDATE currency SET amount = amount - ? WHERE user = ?', (change_points, user)) instance.cur.execute('UPDATE currency SET amount = amount + ? WHERE user = ?', (change_points, other_user)) instance.con.commit() if percent: return '%s %s %s %s (%s%%) to %s' % (user, verb, change_points, instance.fmt_currency_name(change_points), percent, other_user) else: return '%s %s %s %s to %s' % (user, verb, change_points, instance.fmt_currency_name(change_points), other_user)
def algorithm_wrapper(start_point, end_point, node_layer, input_data_path, output_file, algorithm, node_id_attribute='nodeID'): """ `start_point` : the starting point as QgsPointXY `end_point` : the end point as QgsPointXY `node_layer` : a point vector layer that contains the node. Naturally it's located in input_data_path `input_data_path` : a path to directory with nodes and edges layer. `output_file` : a path to the output shape file. """ # Get the nearest node from start and end start_node = get_nearest_feature(node_layer, start_point) print('start nodeID:', start_node['nodeID']) end_node = get_nearest_feature(node_layer, end_point) print('end nodeID:', end_node['nodeID']) # generate path with the `algorithm` start_node_id = (node_id_attribute, start_node['nodeID']) end_node_id = (node_id_attribute, end_node['nodeID']) path = algorithm(start_node_id, end_node_id, input_data_path, output_file) # Sort the path coordinates = [start_point] G = nx.Graph(nx.read_shp(input_data_path, strict=False, geom_attrs=True)) # Read and convert to Graph for i in range(len(path) - 1): node1 = path[i] node2 = path[i + 1] edge_key = [node1, node2] # print('edge key: ', edge_key) points = get_points(G, edge_key) # print(points) if i == 0: for p in points: coordinates.append(QgsPointXY(p[0], p[1])) else: start_point_path = QgsPointXY(points[0][0], points[0][1]) if start_point_path == coordinates[-1]: # Same end point, add a usual for p in points[1:]: coordinates.append(QgsPointXY(p[0], p[1])) else: # Different endpoint, reverse for p in points[::-1][1:]: coordinates.append(QgsPointXY(p[0], p[1])) # Append end point coordinates.append(end_point) # Spatial reference spatial_reference = get_spatial_reference(input_data_path) # Write result to a shapefile (TODO: put it in a function) # Create geometry for the whole line line_geometry = QgsGeometry.fromPolylineXY(coordinates) # Convert to Wkt for ogr line_wkt = line_geometry.asWkt() # set up the shapefile driver driver = ogr.GetDriverByName("ESRI Shapefile") # create the data source data_source = driver.CreateDataSource(output_file) # create the layer layer = data_source.CreateLayer("A Star Shortest Path", spatial_reference, ogr.wkbLineString) feature = ogr.Feature(layer.GetLayerDefn()) geom = ogr.CreateGeometryFromWkt(line_wkt) # Set the feature geometry using the geom feature.SetGeometry(geom) # Create the feature in the layer (shapefile) layer.CreateFeature(feature) # Dereference the feature feature = None data_source = None print(output_file)
recipient = final_s.replace('\r', '') msg = admin.give_points(recipient, amount) send_message(s, msg) break if message == '!give\r': if user not in admin: send_message( s, '@{} you dont have acces to that command.'.format(user)) break send_message(s, 'Usage is !give <user> <amount>') break # Points command # if message == '!points\r': points = get_points(user) send_message(s, 'You have {} points. @{}'.format(points, user)) break # End # if message.startswith('!points '): points = get_points(user) send_message(s, 'You have {} points. @{}'.format(points, user)) break # Time command # if message.startswith('!time '): k = message.split(' ') final_s = k[1] usr = final_s.replace('\r', '') msg = usr_time(usr)
import utils import numpy as np import cv2 from parameter import * if __name__ == '__main__': points = utils.get_points("data/20210116/1.csv") #[frame][3][37] print(points.shape) points = points[:, 0, :] #[frame][50] print(points.shape) vs = [] for i in range(1, points.shape[0]): v = [] for j in range(points.shape[1]): if points[i][j] == np.inf or points[i - 1][j] == np.inf: continue d = points[i][j] - points[i - 1][j] v.append(int(d * 120 * TIME / GAP) + MAX_V) vs.append(v) img = np.zeros((MAX_V * 2, len(vs))) for i in range(len(vs)): for j in range(len(vs[i])): try: img[vs[i][j]][i] += 10 except Exception: pass print(img.shape) # cv2.imshow("stft1", img)
import cv2 import numpy as np from constants import POSE_PAIRS from utils import get_points cap = cv2.VideoCapture("res/vid/single.mp4") hasFrame, frame = cap.read() while cv2.waitKey(1) < 0: hasFrame, frame = cap.read() frameCopy = np.copy(frame) if not hasFrame: cv2.waitKey() break pts = get_points(frame, 368, 368)[0] frame_copy = np.copy(frame) for i in range(len(pts)): x, y = pts[i] cv2.circle(frame_copy, (int(x), int(y)), 8, (0, 255, 255), thickness=-1, lineType=cv2.FILLED) cv2.putText(frame_copy, "{}".format(i), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, lineType=cv2.LINE_AA) for (a, b) in POSE_PAIRS: if pts[a] and pts[b]: cv2.line(frame_copy, pts[a], pts[b], (0, 255, 255), 3, lineType=cv2.LINE_AA) cv2.circle(frame_copy, pts[a], 8, (0, 0, 255), thickness=-1, lineType=cv2.FILLED) cv2.circle(frame_copy, pts[b], 8, (0, 0, 255), thickness=-1, lineType=cv2.FILLED) cv2.imshow('Key points', frame_copy) cv2.waitKey(0)
def spawn_workers(workers, status_bar=True): allPoints = utils.get_points() sections = utils.split_points_into_grid(allPoints) count = len(sections) workersWeHave = len(config.ACCOUNTS) subWorkersWeHave = len(config.SUB_ACCOUNTS) logger.info("Have " + str(workersWeHave) + " of the " + str(count) + " workers we need") if count > workersWeHave: print str(count - workersWeHave) + " MORE WORKERS REQUIRED" sys.exit(1) if (config.SLEEP == 1): ratio = utils.getSubMultiplier() logger.info("Have " + str(subWorkersWeHave) + " of the " + str(ratio * count) + " workers we need") if ratio * count > subWorkersWeHave: print str((ratio * count) - subWorkersWeHave) + " MORE SUB WORKERS REQUIRED" sys.exit(1) start_date = datetime.now() for worker_no in range(count): print "starting worker: " + str(worker_no) start_worker(worker_no, sections[worker_no], count) lenghts = [len(p) for p in sections] points_stats = { 'max': max(lenghts), 'min': min(lenghts), 'avg': sum(lenghts) / float(len(lenghts)), } last_cleaned_cache = time.time() last_workers_checked = time.time() workers_check = [(worker, worker.total_seen) for worker in workers.values() if worker.running] while True: now = time.time() # Clean cache if now - last_cleaned_cache > (30 * 60): # clean cache db.SIGHTING_CACHE.clean_expired() last_cleaned_cache = now # Check up on workers if now - last_workers_checked > (5 * 60): # Kill those not doing anything for worker, total_seen in workers_check: if not worker.running: continue if worker.total_seen <= total_seen: #worker.kill() logger.info("This worker isn't seeing any pokemon") # Prepare new list workers_check = [(worker, worker.total_seen) for worker in workers.values()] last_workers_checked = now if status_bar: if sys.platform == 'win32': _ = os.system('cls') else: _ = os.system('clear') print(get_status_message(workers, count, start_date, points_stats)) time.sleep(0.5)
if __name__ == '__main__': # start the capture stdscr = curses.initscr() curses.noecho() curses.cbreak() cap = cv2.VideoCapture(0) cv2.namedWindow("test") cv2.createTrackbar("level", "test", 150, 255, nope) cv2.createTrackbar("inv", "test", 0, 1, nope) while(1): (un,src) = cap.read() rects = gen_grid(src) r = cv2.getTrackbarPos("level","test") if cv2.getTrackbarPos("inv", "test") == 1: mask = threshold(src, r, False) else: mask = threshold(src, r) points = get_points(mask) rows = {i:[] for i in range(8)} for p in points: (i,j) = get_grid_cell(src, p) cv2.circle(mask, (p[1],p[0]), 10, (100,100,100,200)) cv2.circle(mask, (p[1],p[0]), 5, (100,100,100,200)) rows[i].append(j) print_dic(rows) stdscr.refresh() draw_grid(mask,rects) cv2.imshow("test", mask) cv2.waitKey(1)
def command_currency(self, data): points = get_points(self, self.user) return '%s you have %i %s' % (self.user, points, self.fmt_currency_name(points))