def __init__(self, sequences, plotter_args=None, drawer_args=None): self.sequences = [ Sequence.from_fasta_file(sequences.file1), Sequence.from_fasta_file(sequences.file2) ] self.plotter = Plotter(plotter_args) self.drawer = Drawer(drawer_args)
def __init__(self, size, bombs_proportion, no_cursor=False, no_drawing=False): random.seed(time.time()) self.__no_cursor = no_cursor self.__no_drawing = no_drawing self.__size = size if self.__size < MIN_SIZE: self.__size = MIN_SIZE if self.__size > MAX_SIZE: self.__size = MAX_SIZE if bombs_proportion < MIN_BOMBS: bombs_proportion = MIN_BOMBS if bombs_proportion > MAX_BOMBS: bombs_proportion = MAX_BOMBS self.__bombs_count = int(bombs_proportion * self.__size**2) self.__hidden_count = self.__size**2 - self.__bombs_count self.__grid = [[0 for _ in range(self.__size)] for _ in range(self.__size)] self.__grid_mask = [[0 for _ in range(self.__size)] for _ in range(self.__size)] self.__bombs_placed = False self.__cursor = {'x': 0, 'y': 0} self.__status = 'in_game' self.__drawer = Drawer(self.__size, self.__bombs_count) self.__drawer.draw(self.__grid, self.__grid_mask, self.__cursor)
def on_drawing_area_draw(self, da, ctx): r = da.get_allocation() (xmin, xmax) = (self.xmin_spin.get_value(), self.xmax_spin.get_value()) (ymin, ymax) = (xmin * r.height / r.width, xmax * r.height / r.width) viewport = Viewport( Camera( Vector(self.camx_spin.get_value(), self.camy_spin.get_value(), self.camz_spin.get_value()), Vector(self.originx_spin.get_value(), self.originy_spin.get_value(), self.originz_spin.get_value()), self.d_spin.get_value(), Vector(0, 0, 1) ), xmin, xmax, ymin, ymax ) ctx.set_line_width(1) drw = Drawer(viewport, da, ctx) drw.draw_mesh() drw.draw_polyhedron(self.polyhedron)
def run(): x0, y0 = (IMG_WDT // 2) - 1, (IMG_HGT // 2) - 1 a0, b0 = 0, 0 color = 0 state = 0 for i in range(1280): # Change color here r = (color >> 8) & 0xf g = (color >> 4) & 0xf b = (color >> 0) & 0xf Drawer.draw_ellipse(IMAGE_ARR, x0, y0, a0, b0, (r, g, b)) if phase == 0: if a0 == (IMG_WDT // 2) - 4: state = 1 else: a0 += 4 b0 += 3 else: if a0 == 0: state = 0 else: a0 -= 4 b0 -= 3 color = (color + 1) % (1 << COLOR_DEPTH) # Save image scipy.misc.imsave('img/img_%04d.png' % i, IMAGE_ARR)
def g_display(self): self.name = 'timeline ' + QString(self.node.name()) if not self.node.hasChildren(): self.setStateInfo(self.node.absolute() + ' doesn\'t have any children.') else: self.vfs = vfs.vfs() self.vlayout = QVBoxLayout() self.vlayout.setMargin(0) self.vlayout.setSpacing(0) self.hsplitter = QSplitter() self.ploter = PaintArea(self) self.options = OptionsLayout(self) self.hsplitter.addWidget(self.ploter) self.hsplitter.addWidget(self.options) self.vlayout.addWidget(self.hsplitter) self.setLayout(self.vlayout) self.draw = Drawer(self) # CountThread compute node amount self.countThread = CountThread(self, self.countThreadOver) self.populateThread = DataThread(self, self.dataThreadOver) self.maxOccThread = MaxOccThread(self, self.maxOccThreadOver) self.workerThread = WorkerThread(self) #comment it to avoid redraw everytime painter is resized self.connect(self.workerThread, SIGNAL('refresh'), self.reDraw)
def generation(self, population_size=100): benchmarks_generation = [] print(colored("[BENCHMARKS]", "yellow"), "Gathering computation time for different generation numbers") for size in self.__size: print(colored("[BENCHMARKS]", "yellow"), "Current max generation =", size) start = timeit.default_timer() temp_machines_list, temp_jobs_list = copy.deepcopy( self.__machines_list), copy.deepcopy(self.__jobs_list) s = GeneticScheduler(temp_machines_list, temp_jobs_list) total_time = s.run_genetic(total_population=population_size, max_generation=size, verbose=False) stop = timeit.default_timer() print(colored("[BENCHMARKS]", "yellow"), "Done in", stop - start, "seconds") benchmarks_generation.append( (population_size, size, stop - start, total_time)) del s, temp_machines_list, temp_jobs_list print(colored("[BENCHMARKS]", "yellow"), "Gathering for different population sizes completed") Drawer.plot2d( self.__name + "_benchmarks_generation", [element[1] for element in benchmarks_generation], [element[2] for element in benchmarks_generation], "Time as a function of max generation for " + self.__name + " (" + str(population_size) + " individuals)", "Max generation", "Time (in seconds)") return benchmarks_generation
def process_file(path_to_file: str, save_path: str, assistant: AimAssistant, file_type: str) -> None: try: cap = cv2.VideoCapture(path_to_file) except Exception as e: print("Failed while creating a cap. Error: {e}") raise e if not cap.isOpened(): raise Exception("Cap's not opened") cv2.namedWindow("", cv2.WINDOW_NORMAL) if file_type == "video": output_name = os.path.join( save_path, os.path.splitext(os.path.basename(path_to_file))[0] + '.avi') try: video_writter = cv2.VideoWriter( output_name, cv2.VideoWriter_fourcc("M", "J", "P", "G"), 10, (round(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), round(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))) except Exception as e: print("Failed while initializing the video writer. Error: {e}") raise e else: output_name = os.path.join( save_path, os.path.splitext(os.path.basename(path_to_file))[0] + '.jpg') # Process file frame_counter = 0 while True: has_frame, frame = cap.read() if not has_frame: break # Run neural net once in N frames if frame_counter % N == 0: output = assistant.aim(frame) Drawer.visualise_results(output, frame) # Save results if file_type == "video": video_writter.write(frame) frame_counter += 1 else: try: cv2.imwrite(output_name, frame) except Exception as e: print(f"Failed while saving a processed photo. Error: {e}") raise e cv2.imshow("", frame) if cv2.waitKey(1) == 27: break cap.release() cv2.destroyAllWindows() return
def play(self, n_turns, delay): for turn in range(0, n_turns): print("turn: " + str(turn) + " ", end="") Drawer.draw(self.life_grid) if turn < (n_turns - 1): time.sleep(delay) self.life_grid = self.life_algo.play(self.life_grid) exit(0)
def draw_subsection(self, layer, target): """ :param layer: the index of the layer to draw :param target: a dict of co-ordinate and tile target key-value pairs :return: an image with only the targeted selection of the targeted layer updated. """ draw = Drawer(self.layers.get_layer(layer)) self.layer_cache[layer] = draw.draw_sub_section( self.layer_cache[layer], target) return self.draw_cache()
def __init__(self): self.game_size = 50 self.ticks_per_second = 120 screen_size_x = 800 screen_size_y = 800 self.land = Land(self.game_size) self.drawer = Drawer(screen_size_x, screen_size_y, self.land) self.controller = Controller(self.land, self.drawer)
def main(): # tk = Track('tracks/simple_straight/simple_straight.tk') # rl = Racingline('tracks/simple_straight/rl01.rl') # tk = Track('tracks/simple_90/simple_90.tk') # rl = Racingline('tracks/simple_90/rl01.rl') tk = Track('tracks/simple_90_narrow/simple_90_narrow.tk') rl = Racingline('tracks/simple_90_narrow/rl01.rl') # d = Drawer(tk, [rl]) # d.draw() rls = [rl] evolution_generation_cnt = 1200 for generation in range(evolution_generation_cnt): rls = Evolutioner.evolution(rls) results = [] for rl in rls: res = RacingResult(tk, rl) res.race() if not res.finished: continue else: results.append(res) results.sort(key=lambda x: x.time) j = 1 while True: if j >= len(results): break elif results[j] == results[j - 1]: del results[j] else: j += 1 if generation < 500: max_len = 1 elif generation < 800: max_len = 2 elif generation < 1000: max_len = 5 elif generation < 1100: max_len = 10 elif generation < 1150: max_len = 20 else: max_len = 50 if len(results) > max_len: results = results[:max_len] rls.clear() for res in results: rls.append(res.racingline) print('generation: %4d, best time: %7.3f' % (generation, results[0].time)) d = Drawer(tk, rls[:1]) d.draw()
def initialize_agent(self): """ Callback from BaseAgent.__init__() TODO does this nested class affect performance? """ # TODO self.initialize_log() self.controller_state = SimpleControllerState() self.S = State(self.index) self.D = Drawer(self.renderer) self.P = PygameDrawer() self.strategy = None
def on_drawing_area_draw(self, da, ctx): viewport = Viewport( self.xmin_spin.get_value(), self.xmax_spin.get_value(), self.ymin_spin.get_value(), self.ymax_spin.get_value(), ) ctx.set_line_width(1) drw = Drawer(viewport, da, ctx) drw.draw_axes() for poly in self.polys: drw.draw_polygon(poly) ctx.set_source_rgb(random(), random(), random())
def write(self): output = json.dumps( output_schema.dump({ 'search_results': self.search_results }), indent=2, sort_keys=True ) filename = (self.filename[:-5] if self.filename.endswith('.json') else self.filename) + '_output.json' with open(filename, 'w') as f: f.write(output) drawer = Drawer() drawer.write(self.map, self.search_results, self.filename) self.logger.info('Results saved!')
def mainLoop(clock, window, sprites, audio): run = True status = Status.inMenu tick = 0 drawer = Drawer(window) hitBoxe = HitBoxe(audio.hitSound, audio.dieSound, audio.pointSound) base = Base(sprites.base) bird = Bird(sprites.bird, audio.wingSound, hitBoxe) pipes = Pipes(sprites.pipe, hitBoxe) score = Score(sprites.numbers) while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): run = False if status == Status.inMenu and event.type == pygame.KEYUP and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): status = Status.inGame if status == Status.inGame and event.type == pygame.KEYDOWN and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): bird.jump() if status == Status.inGameOver and event.type == pygame.KEYUP and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): status = Status.inMenu tick = 0 base = Base(sprites.base) bird = Bird(sprites.bird, audio.wingSound, hitBoxe) pipes = Pipes(sprites.pipe, hitBoxe) score = Score(sprites.numbers) if status == Status.inGame: hitBase = hitBoxe.birdHitBase(bird, base) hitPipe = hitBoxe.birdHitPipes(bird, pipes) hitBoxe.birdPassPipe(bird, pipes.pipes, score) if hitBase or hitPipe: status = Status.inGameOver bird.die() if status == Status.inMenu: drawer.drawInMenu(sprites.background, sprites.message, base, bird, tick) elif status == Status.inGame: drawer.drawInGame(sprites.background, base, bird, pipes, score, tick) else: drawer.drawInGameOver(sprites.background, sprites.gameOver, base, bird, pipes, score, tick) if tick < FPS: tick += 1 else: tick = 0
def draw_all(self): """ Method that draws every cell in every layer in the stack and returns the complete map object """ base = Drawer(self.layers.stack[0]).draw_full_layer() for i, layer in enumerate(self.layers.stack): if isinstance(layer, Layer): draw = Drawer(layer) layer_image = draw.draw_full_layer() base = Image.alpha_composite(base, layer_image) self.layer_cache[i] = layer_image else: layer_image = layer.image base = Image.alpha_composite(base, layer_image) self.layer_cache[i] = layer_image return base
def restoreGUI(self): """ * restores already drawn hanging tree from saved game * and restores already pressed buttons from saved game """ missed = len(self.__hp.missed) if missed > 0: drawer = Drawer(self.turtle_screen, self.raw_turtle) for i in range(1, missed + 1): step_to_draw = { 1: drawer.basement, 2: drawer.main_bar, 3: drawer.upper_bar, 4: drawer.rope, 5: drawer.head, 6: drawer.body, 7: drawer.left_foot, 8: drawer.right_foot, 9: drawer.left_arm, 10: drawer.right_arm } step_to_draw[i]() if missed > 0 or len(self.__hp.corrects) > 0: for button in self.Buttons.buttons: letter = button['text'].lower() if letter in self.__hp.missed or letter in self.__hp.corrects: button.config(state='disabled')
def main(): points = generate_points() drawer = Drawer(WIDTH, HEIGHT, b"Mandelbrot") drawer.init_screen() count = 0 for point in points: (r, g, b) = hsv_to_rgb(point['color'], 1, 1) drawer.draw_point(point['r'], point['i'], r, g, b) count += 1 if count % 1000 == 0: print("{0} tys punktów".format(count / 1000)) drawer.refresh() drawer.wait()
class Dotplot(object): def __init__(self, sequences, plotter_args=None, drawer_args=None): self.sequences = [ Sequence.from_fasta_file(sequences.file1), Sequence.from_fasta_file(sequences.file2) ] self.plotter = Plotter(plotter_args) self.drawer = Drawer(drawer_args) def make_plot(self): self.plot = self.plotter.plot(self.sequences) def draw(self, plot=None): if not plot: plot = self.plot self.drawer.draw(plot)
def __init__(self, world, window = None, do_draw = False, use_simple_physics = False, fps = 60, dt_eps = 0.005, max_dt = 0.25): # Constants: self.fps = fps self.fixed_dt = 1.0 / float(fps) self.dt_eps = dt_eps self.max_dt = max_dt # TODO: Copy bitmap so we can reset walls later? # self.initial_wall_bitmap = list(world.initial_wall_bitmap) # const copy # Variables: self.ps = PhysicsState(world) # TODO: if use_simple_physics: self.ps = SimplePhysicsState(...) self.unused_dt = None self.window = window if do_draw: assert(window is not None) self.drawer = Drawer(window) # if use_simple_physics: # ... # else: # self.ps_to_draw = PhysicsState(None) # Scratch memory else: self.ps_to_draw = None self.drawer = None self.is_paused = True self.last_toggle_time = None
def __init__(self, controller): """ Initializes pygame window, including the drawing space and control panel """ self.controller = controller pygame.init() pygame.display.set_caption("Desktop CNC Miller") #create the screen self.max_x = 1200 self.max_y = 600 self.window = pygame.display.set_mode((self.max_x, self.max_y)) #set background #self.window.fill( (30, 30, 255) ) self.window.fill((0, 0, 0)) midpnt = int(self.max_x * 0.6) self.drawer_bounds = pygame.Rect(0, 0, midpnt, self.max_y) self.control_panel_bounds = pygame.Rect(midpnt, 0, self.max_x - midpnt, self.max_y) self.control_panel = ControlPanel(self.window, self.control_panel_bounds, self.controller) self.drawer = Drawer(self.window) self.control_panel.draw()
def run(self, pos1, vel1, pos2, vel2): self.screen = pygame.display.set_mode(self.size) self.coord_converter = CoordConverter((-10, 10), (-10, 10), (0, self.screen.get_size()[0]), (0, self.screen.get_size()[1])) pygame.display.set_caption('Relativistic') self.engine = Engine(pos1, vel1, pos2, vel2) self.time_multiplier = 1.0 self._drawer = Drawer(self.screen, self.coord_converter) self._grapher = Grapher(self.screen, self.coord_converter) #self.drawer = Drawer(self.screen, self.coord_converter) self.drawer = self._drawer self.clock = pygame.time.Clock() self.clock.tick(60) self.running = True while self.running: for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False else: self.interface.handle_event(event) self.clock.tick(60) if self.drawer is self._drawer: self.engine.adjust_bodies() self.engine.update(self.clock.get_time() / 1000 * self.time_multiplier) self.draw()
def population_and_generation(self): import itertools benchmarks_population_and_generation = [] params = itertools.product(self.__size, repeat=2) print( colored("[BENCHMARKS]", "yellow"), "Gathering times for different couples of population size and max generation" ) for population, generation in params: print(colored("[BENCHMARKS]", "yellow"), "Current population size =", population, ", max generation =", generation) start = timeit.default_timer() temp_machines_list, temp_jobs_list = copy.deepcopy( self.__machines_list), copy.deepcopy(self.__jobs_list) s = GeneticScheduler(temp_machines_list, temp_jobs_list) total_time = s.run_genetic(total_population=population, max_generation=generation, verbose=False) stop = timeit.default_timer() print(colored("[BENCHMARKS]", "yellow"), "Done in", stop - start, "seconds") benchmarks_population_and_generation.append( (population, generation, stop - start, total_time)) del s, temp_machines_list, temp_jobs_list print(colored("[BENCHMARKS]", "yellow"), "Gathering for different couples completed") # Plot graph with solution time as Z axis Drawer.plot3d( self.__name + "_benchmarks_generation_with_solution_time", [element[0] for element in benchmarks_population_and_generation], [element[1] for element in benchmarks_population_and_generation], [element[3] for element in benchmarks_population_and_generation], "Best time found as a function of population size and max generation", "Population size", "Max generation", "Total time") # Plot graph with computation time as Z axis Drawer.plot3d( self.__name + "_benchmarks_generation_with_computation_time", [element[0] for element in benchmarks_population_and_generation], [element[1] for element in benchmarks_population_and_generation], [element[2] for element in benchmarks_population_and_generation], "Computation time as a function of population size and max generation", "Population size", "Max generation", "Computation time") return benchmarks_population_and_generation
def init_agent(self): self.drawer = Drawer(self) self.goal = 0 self.goal_integral = 0 self.foods_eaten = 0 self.food_pos = [random.uniform(0, 1) for _ in range(2)] self.agent_pos = [random.uniform(0, 1) for _ in range(2)] self.agent_vel = [random.uniform(0, 1) for _ in range(2)]
def draw_cache(self): """ Method that draws cached layer images sequentially. :return: The cached map image """ cache_base = Drawer(self.layers.stack[0]).draw_full_layer() for i in self.layer_cache: cache_base = Image.alpha_composite(cache_base, self.layer_cache[i]) return cache_base
def __init__(self, attack_team, defense_team): self.player_histograms = [] self.buckets_per_color = 200 self.teams_set = False self.attacking_idx = 0 self.teams = [] self.drawer = Drawer() self.attack_team = attack_team self.defense_team = defense_team
def main(): seq = [] images = glob.glob(path + '*.tif') for i in images: image = cv2.imread(i, cv2.IMREAD_GRAYSCALE) seq.append(image) preprocessor = Preprocessor(seq) detector = Detector(preprocessor) matcher = Matcher(detector) drawer = Drawer(matcher, preprocessor) masks = preprocessor.get_masks() print('Generating all frames and cell states...') drawer.load() print('Successfully loaded all images') # Save all generated images and their masks to disk counter = 1 for g in drawer.get_gen_images(): annotated = cv2.imwrite(path + f'gen/{counter}.tif', g) mask = cv2.imwrite(path + f'gen/{counter}_mask.tif', masks[counter - 1]) if not annotated or not mask: print(f'Failed to save') counter += 1 print('Saved all images') # Now standby for user to issue commands for retrieval while True: string = input( 'Input a frame and cell ID (optional) separated by a space...\n') if string: string = string.split(' ') frame = int(string[0]) if len(string) > 1: try: id = int(string[1]) display_image = drawer.serve(frame, id) except ValueError: print(f'Not an integer') display_image = drawer.serve(frame) else: display_image = drawer.serve(frame) # plt.imshow(display_image) # plt.axis('off') # plt.show() # cv2.imshow('image',display_image) # cv2.waitKey(0) # cv2.destroyAllWindows() else: break
def draw(self, maze, solution): drawer = Drawer(self.h, self.mx, self.my) image = drawer.prepare(maze) pixels = image.load() draw = ImageDraw.Draw(image) prev = None for step in [(0,-1)] + solution + [(self.mx - 1, self.my)]: if prev: kx1 = prev[0] * self.h + self.h / 2 ky1 = prev[1] * self.h + self.h / 2 kx2 = step[0] * self.h + self.h / 2 ky2 = step[1] * self.h + self.h / 2 draw.line((kx1, ky1, kx2, ky2), fill="red") prev = step image.save("SolvedMaze_" + str(self.mx) + "x" + str(self.my) + ".png", "PNG")
class UntitledSideProject(BaseAgent): def initialize_agent(self): """ Callback from BaseAgent.__init__() TODO does this nested class affect performance? """ # TODO self.initialize_log() self.controller_state = SimpleControllerState() self.S = State(self.index) self.D = Drawer(self.renderer) self.P = PygameDrawer() self.strategy = None def get_output(self, packet: GameTickPacket) -> SimpleControllerState: """ Recieves: 1/60 second of new game information Returns: what buttons to push """ print("FRAME") self.D._start_frame() self.P._start_frame() self.S.update(packet) strategy = select_strategy(self.S, self.D, self.P) ball_prediction = self.get_ball_prediction_struct() # print(ball_prediction) target = strategy.calculate_target(ball_prediction) # pygame_drawer.draw_circle(location) # print("Car location", self.S.car_location) if self.S.impact_event is not None: self.P.draw_target(self.S.impact_event["predicted_ball_location"]) self.P.draw_path(self.S.car_location, target.location) self.P.draw_my_car(self.S.ball_location, color=(255, 0, 255)) self.P.draw_my_car(self.S.car_location) # print(packet) buttons_to_push = get_to_target(target, self.S, self.D, self.controller_state) self.D._finish_frame() self.P._finish_frame() return buttons_to_push
def get_active_tile_image(self): drawer = Drawer(self.layerlist.get_layer(self.active_layer)) if self.active_tile_array: distances = {} for key in self.active_tile_array: distances[key[0] * 2 + key[1] * 2] = key start_d = min(distances.keys()) end_d = max(distances.keys()) start = distances[start_d] end = distances[end_d] width = end[0] + 1 - start[0] height = end[1] + 1 - start[1] image_size = (width * self.layerlist.get_grid_res(), height * self.layerlist.get_grid_res()) base = Image.new('RGBA', image_size, color=(0, 0, 0, 0)) self.active_tile_image = drawer.draw_tile_array( base, self.active_tile_array) else: self.active_tile_image = drawer.get_cell_image(self.active_tile) return self.active_tile_image
def setup_enigmapol(stdscr): global drawer, screen, bash curses.start_color() curses.use_default_colors() for i in range(0, curses.COLORS): curses.init_pair(i + 1, i, -1) screen = stdscr enigmapol = EnigmaPol() bash = Bash() drawer = Drawer(screen) enigmapol.make_choice()
def _trackbar_change(self, val): hOrSOrV = cv2.getTrackbarPos('H/S/V', 'hsv_trackbars') h, s, v = cv2.split(self.hsv) low = cv2.getTrackbarPos("LOW", 'hsv_trackbars') high = cv2.getTrackbarPos("HIGH", 'hsv_trackbars') if hOrSOrV == 0: what = h self.color_lower[0] = low self.color_upper[0] = high elif hOrSOrV == 1: what = s self.color_lower[1] = low self.color_upper[1] = high else: what = v self.color_lower[2] = low self.color_upper[2] = high cv2.imshow("h", what) # cv2.imshow("h", whatMask) mask = self._get_threshold_mask(self.hsv, self.color_lower, self.color_upper) vis = Drawer(mask, "whatMask", cv2.COLOR_GRAY2RGB) vis.draw_text(str(self.color_lower) + "|" + str(self.color_upper)) vis.show()
def __init__(self, keys=None, theme=None): """ initilizes the gui """ import __builtin__ __builtin__.gui = self self.node = aspect2d self.id = "root" self.dragWidget = None self.dragPos = Vec2(0, 0) self.dragFun = None self.dragSnap = False self.lastDragMoue = Vec2(0, 0) self.hoveringOver = None self.parent = False self.children = [] self.idToFrame = {} self.pos = Vec2(0, 0) self.windowsize = 800, 600 self.size = Vec2(*self.windowsize) self.mouse = Vec2(0, 0) self.node.setBin("fixed", 2) self.node.setDepthWrite(False) self.node.setDepthTest(False) if not keys: self.keys = Keys() else: self.keys = keys if not theme: self.theme = Theme() else: self.theme = theme self.layout = Layout() self.drawer = Drawer() task(self._doMouse, -10) self._reSize() task(self._doDrag, 10) task(self._reSize, 20) task(self._layout, 30) task(self._draw, 40)
def Detect(img, overlay_text): # converting RGB image to grey scale grey_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # locate face and face landmarks face = face_recognition.face_locations(grey_img) landmarks = face_recognition.face_landmarks(grey_img) # calculate (reorder) x1, x2, y1, y2 for top, right, bottom, left in face: x1, x2, y1, y2 = left, right, top, bottom # draw the results Drawer(img, landmarks, overlay_text, (x1, x2, y1, y2))
def process(self): while (self.cap.isOpened()): _, self.frame = self.cap.read() if _: draw_script, ms, fps = self.obj_det.process(self.frame) drawer = Drawer() self.frame = drawer.process(self.frame, draw_script) cv2.putText(self.frame, f"INFERENCE TIME/FPS: {ms} ms/{fps} fps", (2, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2, cv2.FILLED) cv2.imshow("TensorTV+", self.frame) if cv2.waitKey(25) & 0xFF == ord('q'): break else: self.cap = cv2.VideoCapture(self.input_video) self.cap.release() cv2.destroyAllWindows() self.obj_det.close()
def main(stdscr): quitting_time = False start_time = time.time() last_update = time.time() drawer = Drawer(stdscr, []) lookup(drawer) draw(drawer) while not quitting_time: c = stdscr.getch() t = time.time() if t >= last_update + 30.0 or c == ord('r'): lookup(drawer) draw(drawer) last_update = time.time() if c == curses.KEY_LEFT: drawer.update_cursor(0, -1) draw(drawer) if c == curses.KEY_RIGHT: drawer.update_cursor(0, 1) draw(drawer) if c == ord('j'): drawer.update_cursor(1, 0) draw(drawer) if c == ord('k'): drawer.update_cursor(-1, 0) draw(drawer) if c == curses.KEY_ENTER: item = drawer.items[drawer.cursor[0]] subprocess.call(['vim', '+%s' % item[3], item[2]]) if c == ord('q'): quitting_time = True continue
class Main: def __init__(self, width, height, caption): self.width = width self.height = height self.caption = caption self.drawer = Drawer(self) self.logic = Logic() def init(self): pygame.init() pygame.display.set_caption(self.caption) self.screen = pygame.display.set_mode((self.width, self.height)) self.drawer.init() # start game with clear surface self.drawer.clear() self.draw_info() pygame.display.flip() # spwn number in one second after game start pygame.time.set_timer(SPAWN, 1000) def quit(self): pygame.quit() def loop(self): running = True while running: event = pygame.event.wait() if event.type == pygame.QUIT: running = False elif event.type == SPAWN: self.spawn() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False else: self.submit(event.key) def spawn(self): pygame.time.set_timer(SPAWN, 0) self.logic.start_test() transform = self.logic.current_transform self.drawer.draw(transform) self.draw_info() pygame.display.flip() def submit(self, key): if key in (pygame.K_SPACE, pygame.K_r, pygame.K_f): # neither rotated nor flipped if key == pygame.K_SPACE: self.logic.submit_result(False, False) elif key == pygame.K_r: self.logic.submit_result(True, False) else: # key == pygame.K_f self.logic.submit_result(False, True) # make number disappear self.drawer.clear() self.draw_info() pygame.display.flip() # spawn another test in one second pygame.time.set_timer(SPAWN, 1000) def draw_info(self): text = "Tests Completed: %d\nTests Failed: %d\nAverage Time: %f sec" % (self.logic.tests_completed, self.logic.tests_failed, (float(self.logic.average_time)/1000.0)) self.drawer.render_text(text, False) self.drawer.render_text("Press R if rotated\nPress F if flipped\nPress SPACE if neither apply", True)
class Timeline(QWidget, Script): def __init__(self): Script.__init__(self, 'timeline') QWidget.__init__(self, None) self.type = 'timeline' self.nodeCount = 0 self.timesCount = 0 self.timeMap = {} self.m = 40 # Padding self.lineHeight = 4 # Pixel height of line self.metricOk = False self.colors = [['blue', Qt.blue], ['red', Qt.red], ['green', Qt.green], ['yellow', Qt.yellow], ['magenta', Qt.magenta], ['cyan', Qt.cyan]] self.stateinfo = 'Initialized' self.dateMin = long(0xffffffffffffffff) self.dateMax = long(0) self.baseDateMin = self.dateMin self.baseDateMax = self.dateMax self.selDateMin = None self.selDateMax = None self.maxOcc = 0 self.maxOccZoom = 0 self.xHop = 0 self.xRange = 0 self.dataListsCreated = False def start(self, args): self.node = args['file'].value() def status(self): return 0 def updateWidget(self): pass def g_display(self): self.name = 'timeline ' + QString(self.node.name()) if not self.node.hasChildren(): self.setStateInfo(self.node.absolute() + ' doesn\'t have any children.') else: self.vfs = vfs.vfs() self.vlayout = QVBoxLayout() self.vlayout.setMargin(0) self.vlayout.setSpacing(0) self.hsplitter = QSplitter() self.ploter = PaintArea(self) self.options = OptionsLayout(self) self.hsplitter.addWidget(self.ploter) self.hsplitter.addWidget(self.options) self.vlayout.addWidget(self.hsplitter) self.setLayout(self.vlayout) self.draw = Drawer(self) # CountThread compute node amount self.countThread = CountThread(self, self.countThreadOver) self.populateThread = DataThread(self, self.dataThreadOver) self.maxOccThread = MaxOccThread(self, self.maxOccThreadOver) self.workerThread = WorkerThread(self) #comment it to avoid redraw everytime painter is resized self.connect(self.workerThread, SIGNAL('refresh'), self.reDraw) def fromUSec(self, usec2): usec = int(usec2) days = usec / (86400 * 1000000) seconds = (usec - days * 86400 * 1000000) / 1000000 misec = usec - days * 86400 * 1000000 - seconds * 1000000 if days >= 1 and datetime.fromordinal(days) >= datetime.fromordinal(1): return datetime.fromordinal(days) + timedelta(seconds = seconds, microseconds = misec) return None def toUSec(self, dtime): return dtime.toordinal() * 86400 * 1000000 + dtime.hour * 3600 * 1000000 + dtime.minute * 60 * 1000000 + dtime.second * 1000000 + dtime.microsecond def dumpTimeMap(self): print self.timeMap for k in self.timeMap.keys(): print 'module:', k for attr in self.timeMap[k]: sAttrPath = '/' for v in attr[:-1]: sAttrPath += v + '/' print ' ', sAttrPath, ':', attr[-1] def countThreadOver(self): if not self.nodeCount: self.setStateInfo('No timestamp found any subset of ' + self.node.absolute()) # self.disconnect(self.workerThread, SIGNAL('refresh'), self.reDraw) return self.setStateInfo(str(self.nodeCount) + ' nodes found') # self.dumpTimeMap() # Find/virtual draw maximum size of Y text painter = QPainter() nullPixmap = QPixmap(self.ploter.width, self.ploter.height) painter.begin(nullPixmap) rect = painter.drawText(self.draw.paddingYText, 10, 0, 0, 0, str(self.nodeCount) + '.0') painter.end() self.draw.yLeftMargin = self.draw.paddingYText * 2 + rect.width() self.options.newInformations() self.options.createMetricTools() self.metricOk = True # self.createFullTimeLists() self.workerThread.render() def createFullTimeLists(self): self.populateThread = DataThread(self, self.dataThreadOver) self.populateThread.start() def dataThreadOver(self): self.dataListsCreated = True for family in self.options.configuration: # family[0] = extended|static|usual for time in family[1]: if time[1][5][1]: dateMin = time[1][6][1][0] dateMax = time[1][6][1][1] if dateMin < self.baseDateMin: self.baseDateMin = dateMin if dateMax > self.baseDateMax: self.baseDateMax = dateMax self.options.newInformations() self.workerThread.render() def findMaxValue(self): self.xRange = (self.ploter.width - self.m - self.draw.yLeftMargin) / self.lineHeight self.xHop = (self.baseDateMax - self.baseDateMin) / self.xRange def maxOccThreadOver(self): self.updatePaintingArea() def zoomMaxOcc(self): self.xRange = (self.ploter.width - self.m - self.draw.yLeftMargin) / self.lineHeight xHop = (self.selDateMax - self.selDateMin) / self.xRange newMaxOcc = 0 for family in self.options.configuration: for time in family[1]: timeChecked = self.selDateMin if timeChecked == self.selDateMax: # Every nodes have the same time, setting maxOcc computing time + 100usec occ = self.elementsInRange(time[1][5][1], timeChecked, timeChecked + 100) if occ > newMaxOcc: newMaxOcc = occ while timeChecked <= self.selDateMax: occ = self.elementsInRange(time[1][5][1], timeChecked, timeChecked + xHop) if occ > newMaxOcc: newMaxOcc = occ timeChecked += xHop self.maxOccZoom = newMaxOcc def reDraw(self, resized = False): if resized: self.updatePaintingArea(True) def updatePaintingArea(self, resized = False): if not self.maxOcc: return self.painter = QPainter() self.mainPixmap = QPixmap(self.ploter.width, self.ploter.height) self.mainPixmap.fill(Qt.white) self.gridPixmap = QPixmap(self.ploter.width, self.ploter.height) self.gridPixmap.fill(Qt.transparent) self.painter.begin(self.gridPixmap) if self.options.zoom and not self.maxOccZoom: self.zoomMaxOcc() self.draw.setDynamicValues(self) self.draw.drawInfos() self.draw.drawGrid() self.painter.end() for family in self.options.configuration: for time in family[1]: if resized: time[1][8][1][0] = True time[1][7][1][0] = True if self.options.zoom and time[1][8][1][0]: # Create zoom pixmaps time[1][8][1][1] = QPixmap(self.ploter.width, self.ploter.height) time[1][8][1][1].fill(Qt.transparent) penColor = None for color in self.colors: if color[0] == time[1][1][1]: penColor = QColor(color[1]) penColor.setAlpha(163) break if penColor: self.painter.begin(time[1][8][1][1]) pen = self.painter.pen() pen.setColor(penColor) pen.setWidth(self.lineHeight) self.painter.setPen(pen) self.draw.drawTimeline(self.painter, time[1][5][1]) self.painter.end() time[1][8][1][0] = False elif not time[1][7][1][1] or time[1][7][1][0]: # Create main (original sized) pixmaps time[1][7][1][1] = QPixmap(self.ploter.width, self.ploter.height) time[1][7][1][1].fill(Qt.transparent) penColor = None for color in self.colors: if color[0] == time[1][1][1]: penColor = QColor(color[1]) penColor.setAlpha(163) break if penColor: self.painter.begin(time[1][7][1][1]) pen = self.painter.pen() pen.setColor(penColor) pen.setWidth(self.lineHeight) self.painter.setPen(pen) self.draw.drawTimeline(self.painter, time[1][5][1]) self.painter.end() time[1][7][1][0] = False self.painter.begin(self.mainPixmap) # Draw grid self.painter.drawImage(QPointF(0, 0), self.gridPixmap.toImage(), QRectF(0, 0, self.ploter.width, self.ploter.height)) for family in self.options.configuration: for time in family[1]: # Draw each time pixmap if not self.options.zoom: # Draw global view, if zoom not enabled if time[1][7][1][1] and time[1][0][1]: self.painter.drawImage(QPointF(0, 0), time[1][7][1][1].toImage(), QRectF(0, 0, self.ploter.width, self.ploter.height)) else: # Draw zoom pixmaps if time[1][8][1][1] and time[1][0][1]: self.painter.drawImage(QPointF(0, 0), time[1][8][1][1].toImage(), QRectF(0, 0, self.ploter.width, self.ploter.height)) self.painter.end() self.ploter.scene.clear() self.ploter.scene.addPixmap(self.mainPixmap) self.ploter.setEnabled(True) self.update() def setStateInfo(self, sinfo): self.stateinfo = str(sinfo) def stateInfo(self): if self.nodeCount: return self.stateinfo + ' - ' + str(self.nodeCount) + ' nodes' else: return self.stateinfo def nodesInRange(self, x1, x2): if not self.selDateMin: timeCheck = self.baseDateMin timeMax = self.baseDateMax else: timeCheck = self.selDateMin timeMax = self.selDateMax count = 0 while timeCheck < timeMax: for family in self.options.configuration: for time in family[1]: occ = self.elementsInRange(time[1][5][1], timeCheck, timeCheck + self.xHop) if occ: if self.lineMatched(timeCheck, occ, x1, x2) and time[1][0][1]: count += occ timeCheck += self.xHop if count: self.options.zoomButton.setEnabled(True) self.options.exportButton.setEnabled(True) if count > 1: self.options.selectedNodes.setText(str(count) + ' time values selected') else: self.options.selectedNodes.setText('One time value selected') else: self.options.zoomButton.setEnabled(False) self.options.exportButton.setEnabled(False) self.options.selectedNodes.setText('Nothing selected') def lineMatched(self, usec, occ, x1, x2): if not self.selDateMin: dateMin = self.baseDateMin dateMax = self.baseDateMax else: dateMin = self.selDateMin dateMax = self.selDateMax if (dateMax - dateMin) > 0: x = ((usec - dateMin) * (self.ploter.width - self.m - self.draw.yLeftMargin)) / (dateMax - dateMin) + self.draw.yLeftMargin if x <= self.draw.yLeftMargin: x += 3 x_min = x - 2 x_max = x + 2 if x_min >= x1 and x_max <= x2: return True return False def elementsInRange(self, root, tMin, tMax): ''' Returns amount of node in a date range, given as long Dichotomic search, but this can be improved because we only search for smaller timestamp and decrease index if greather. ''' if not tMin or not tMax: return 0 nodesCount = 0 iMin, iMax = 0, len(root['dates']) - 1 iCurrent = iMax / 2 # Sync cursor in dates list on tMin ; should be improved while iMin != iMax or not iMax: if tMin >= root['dates'][iCurrent] or not iCurrent: while iCurrent and tMin >= root['dates'][iCurrent]: # Should be improved iCurrent -= 1 break elif tMin < root['dates'][iCurrent]: iMax = iCurrent iCurrent = iMin + ((iCurrent - iMin) / 2) # Count amount of nodes between tMin and tMax endOfList = len(root['dates']) while iCurrent < endOfList and tMax >= root['dates'][iCurrent]: if tMin <= root['dates'][iCurrent]: nodesCount += len(root['nodes'][iCurrent]) iCurrent += 1 return nodesCount def elementsInRangeToNodeList(self, root, tMin, tMax): ''' Returns a list of nodes pointer, made of nodes in given date range. Dichotomic search, but this can be improved because we only search for smaller timestamp and decrease index if greather. ''' if not tMin or not tMax: return 0 nodesList = [] iMin, iMax = 0, len(root['dates']) - 1 iCurrent = iMax / 2 # Sync cursor in dates list on tMin ; should be improved while iMin != iMax or not iMax: if tMin >= root['dates'][iCurrent] or not iCurrent: while iCurrent and tMin >= root['dates'][iCurrent]: # Should be improved iCurrent -= 1 break elif tMin < root['dates'][iCurrent]: iMax = iCurrent iCurrent = iMin + ((iCurrent - iMin) / 2) # Count amount of nodes between tMin and tMax endOfList = len(root['dates']) while iCurrent < endOfList and tMax >= root['dates'][iCurrent]: if tMin <= root['dates'][iCurrent]: nodesList.append(root['nodes'][iCurrent]) iCurrent += 1 return nodesList
class Gui(Holder): """ core of the treegui system handles most of the events prods other ui system such as layout and drawing into doing stuff """ def __init__(self,keys=None,theme=None): """ initilizes the gui """ import __builtin__ __builtin__.gui = self self.node = aspect2d self.id = "root" self.dragWidget = None self.dragPos = Vec2(0,0) self.dragFun = None self.dragSnap = False self.lastDragMoue = Vec2(0,0) self.hoveringOver = None self.parent = False self.children = [] self.idToFrame = {} self.pos = Vec2(0,0) self.windowsize = 800,600 self.size = Vec2(*self.windowsize) self.mouse = Vec2(0,0) self.node.setBin("fixed",2) self.node.setDepthWrite(False) self.node.setDepthTest(False) if not keys: self.keys = Keys() else: self.keys = keys if not theme: self.theme = Theme() else: self.theme = theme self.layout = Layout() self.drawer = Drawer() task(self._doMouse,-10) self._reSize() task(self._doDrag,10) task(self._reSize,20) task(self._layout,30) task(self._draw,40) def byId(self,name): if name in self.idToFrame: return self.idToFrame[name] def _layout(self): """ prods layout to do its thing """ # compute children's real positions self.layout.do() def _draw(self): """ prods drawer to do its thing """ self.drawer.draw(self.children) def _reSize(self): """ resize the window via panda3d internal events""" self.windowsize = base.win.getXSize(),base.win.getYSize() self.size = Vec2(*self.windowsize) self.aspect = float(self.windowsize[0]) / float(self.windowsize[1]) self.node.setScale(2./base.win.getXSize(), 1, -2./base.win.getYSize()) self.node.setPos(-1, 0, 1) self.node.reparentTo(render2d) self._x = 0 self._y = 0 self._width = self.size[0] self._height = self.size[1] def baseMouseEvent(self,key): """ acts like user clicked mouse with key """ md = base.win.getPointer( 0 ) self.mouseX = md.getX() self.mouseY = md.getY() m = self.mouseEvent(key,self.mouseX,self.mouseY) return m def _doMouse(self): """ treegui's low level mouse interface """ used = self.baseMouseEvent("hover") if not used: if gui.hoveringOver and gui.hoveringOver.onOut: gui.hoveringOver.onOut() gui.hoveringOver = None def drag(self,widget,dragSnap=False): """ drags a widget """ if not self.dragWidget : self.dragWidget = widget self.dragSnap = dragSnap self.dragPosX = widget._x-gui.mouseX self.dragPosY = widget._y-gui.mouseY widget.parent.toFront(widget) def _doDrag(self): """ task that does dragging at low level """ if self.dragWidget: self.dragWidget.x = self.dragPosX+gui.mouseX self.dragWidget.y = self.dragPosY+gui.mouseY if self.dragWidget.onDrag: self.dragWidget.onDrag() if self.dragSnap: def close(a,b): return abs(a-b) < 15 if close(self.dragWidget.x,0): self.dragWidget.x = "left" elif close( self.dragWidget.x + self.dragWidget._width, self.dragWidget.parent._width): self.dragWidget.x = "right" if close(self.dragWidget.y,0): self.dragWidget.y = "top" elif close( self.dragWidget.y + self.dragWidget._height, self.dragWidget.parent._height): self.dragWidget.y = "bottom" def focusOn(self,focus): if self.keys.focus: self.keys.focus.onUnFocus() focus.onFocus() self.keys.focus = focus return focus def focusNext(self,focus): i = focus.parent.children.index(focus) i -= 1 if i == -1 : i = len(focus.parent.children) - 1 newFocus = focus.parent.children[i] while not newFocus.control and newFocus != focus: i = newFocus.parent.children.index(newFocus) i -= 1 if i == -1 : i = len(focus.parent.children) - 1 newFocus = focus.parent.children[i] print "new",newFocus return self.focusOn(newFocus) def toggle(self): if self.node.isHidden(): self.node.show() else: self.node.hide()
def __init__(self, width, height, caption): self.width = width self.height = height self.caption = caption self.drawer = Drawer(self) self.logic = Logic()