void draw_scene(void){
  clear_window();
  change_observer();
  draw_axis();
  draw_objects();
  glutSwapBuffers();
}
Exemplo n.º 2
0
void print_map()
{
	clear_window();
	printf(" [x] 0  1  2  3  4  5  6  7  8  9\t[x] 0  1  2  3  4  5  6  7  8  9\n");
	printf(" --------------------------------\t--------------------------------\n");
	for (int i = 0; i < 10; i++) {
		printf("%d    ", i);
		for (int x = 0; x <= 1; x++) {
			if (x == 1) {
				printf("\t    ");
			}
			for (int y = 0; y != 10; y++) {
				switch(game_map[x][i][y]) {
					case UNKOWN_WATER:
					case UNKOWN_SHIP:
						printf("?  ");
						break;
					case WATER:
						printf(BLUE);
					case WATER_IA:
						printf("#  \e[m");
						break;
					case SHIP:
						printf(RED);
					case SHIP_IA:
						printf("X  \e[m");
						break;
				}
			}
		}
		printf("\n");
	}
}
Exemplo n.º 3
0
bool CDetectLine::RunThreshold()
{
	try
	{
		threshold(m_Image, &m_Region, m_minGray, m_maxGray);
		if (HDevWindowStack::IsOpen())
		{
			clear_window(HDevWindowStack::GetActive());
			set_color(HDevWindowStack::GetActive(),"red");
			disp_obj(m_Region, HDevWindowStack::GetActive());

			connection(m_Region, &m_ConnectedRegions);

			//为了设定参数方便,显示面积在m_MinCirleArea/10~m_MaxCirleArea*10(Pixel)的区域面积值
			Hobject selectRegions;
			HTuple RegionCount, Area, Row, Column;
			select_shape(m_ConnectedRegions, &selectRegions, "area", "and", m_minArea/10, m_maxArea*10);
			count_obj(selectRegions, &RegionCount);
			area_center(selectRegions, &Area, &Row, &Column);
			set_color(HDevWindowStack::GetActive(),"blue");
			for (int i=1; i<=RegionCount; i+=1)
			{
				set_tposition(HDevWindowStack::GetActive(), HTuple(Row[i-1]), HTuple(Column[i-1]));
				write_string(HDevWindowStack::GetActive(), Area[i-1].D());
			}
		}
	}
	catch(...)
	{
		AfxMessageBox("二值化失败!");
		return false;
	}

	return true;
}
Exemplo n.º 4
0
void	check_first(char **argv, char **envp, pid_t pid, t_shell *shell)
{
  int	i;

  i = 0;
    if (shell->buffer[0] == 'l' && shell->buffer[1] == 's'
	&& shell->buffer[3] == ' ' && shell->buffer[4] == '\0')
    {
      execve(path_dir("/bin/", "ls"), argv, NULL);
      exit(1);
    }
  if (my_strncmp(shell->buffer, "cd", 2) == 0)
    {
      i = chdir(shell->reader[1]);
      exit(1);
    }
  else if (my_strcmp(shell->buffer, "exit") == 0)
    {
      kill(pid, 1);
      exit(1);
    }
  else if (my_strcmp(shell->buffer, "env") == 0)
    show_env(envp);
  else if (my_strcmp(shell->buffer, "clear") == 0)
    clear_window();
}
Exemplo n.º 5
0
bool CDetectLine::RunSelectTarget()
{
	if(RunThreshold())
	{
		try
		{
			select_shape(m_ConnectedRegions, &m_SelectedRegions, 
				(((((HTuple("area").Append("roundness")).Append("row")).Append("column")).Append("ra")).Append("rb")), "and", 
				(((((HTuple(m_minArea).Append(m_minRectangularity)).Append(m_minRow)).Append(m_minColumn)).Append(m_minRA)).Append(m_minRB)), 
				(((((HTuple(m_maxArea).Append(m_maxRectangularity)).Append(m_maxRow)).Append(m_maxColumn)).Append(m_maxRA)).Append(m_maxRB)));

			fill_up(m_SelectedRegions, &m_RegionFillUp);
			gen_contour_region_xld(m_RegionFillUp, &m_RectangleContours, "border");
			distance_pc(m_RectangleContours, m_ImageHeight/2, m_ImageWidth/2, &m_DistanceMin, &m_DistanceMax);

			if (HDevWindowStack::IsOpen())
			{
				clear_window(HDevWindowStack::GetActive());
				set_color(HDevWindowStack::GetActive(),"red");
				disp_obj(m_RectangleContours, HDevWindowStack::GetActive());

				set_color(HDevWindowStack::GetActive(),"green");
				disp_cross(HDevWindowStack::GetActive(), m_ImageHeight/2, m_ImageWidth/2, 20, 0);
				//disp_cross(HDevWindowStack::GetActive(), m_ImageHeight/2 + m_DistanceMin, m_ImageWidth/2, 20, 0);
			}
			return true;
		}
		catch(...)
		{
			AfxMessageBox("检测直线失败!");
		}
	}

	return false;
}
Exemplo n.º 6
0
/* ARGSUSED */
void model_confirm ( Widget w, long which, XtPointer call )
{

    switch (which) {

	case	0:     /* Select */
		if ( ( SelectFileNo == -1 ) |
			( SelectModelNo == -1) )return;
		strcpy(MetaFile,
		  ModelStr[SelectModelNo].file_fullnames[SelectFileNo - 1]);
		XmListDeselectAllItems(model_listW);
		if ( !MpanelMode )
		    clear_window();
		load_meta();
		break;

	case	1:	/* HELP */
		NxmHelp_helpBtnCb( NULL, 8, NULL);
		break;

	case	2:	/* CANCEL */
		XtUnmanageChild(model_toplevel);
		break;

    }
}
Exemplo n.º 7
0
void process_command(char* command)
{
    if (is_command(command, "ps")) {
	print_all_processes(&shell_wnd);
	return;
    }
    
    if (is_command(command, "clear")) {
	clear_window(&shell_wnd);
	return;
    }

    if (is_command(command, "pacman")) {
	run_pacman_app(&pacman_wnd);
	return;
    }

    if (is_command(command, "train")) {
	run_train_app(&train_wnd);
	return;
    }

	if (is_command(command, "macaddr")) {
		ne2k_print_mac(&ne2k_wnd, &ne2k_phy);
		return;
	}

    if (is_command(command, "go")) {
	set_train_speed("4");
	return;
    }
    
    if (is_command(command, "stop")) {
	set_train_speed("0");
	return;
    }
    
    if (is_command(command, "rev")) {
	set_train_speed("D");
	return;
    }
    
    if (is_command(command, "help")) {
	wprintf(&shell_wnd, "Commands:\n");
	wprintf(&shell_wnd, "  - help   show this help\n");
	wprintf(&shell_wnd, "  - clear  clear window\n");
	wprintf(&shell_wnd, "  - ps     show all processes\n");
	wprintf(&shell_wnd, "  - pacman start PacMan\n");
	wprintf(&shell_wnd, "  - go     make the train go\n");
	wprintf(&shell_wnd, "  - stop   make the train stop\n");
	wprintf(&shell_wnd, "  - rev    reverse train direction\n");
	wprintf(&shell_wnd, "  - train  start train application\n");
	wprintf(&shell_wnd, "  - macaddr  get the MAC address of your NE2K\n\n");
	return;
    }
    
    /* Room for more commands! */
    wprintf(&shell_wnd, "Syntax error! Type 'help' for help.\n");
}
Exemplo n.º 8
0
int sudoku(unsigned int numbers_def[16])
{
	clear_window();
	unsigned int numbers[16];
	for (int i = 0; i < 16; i++) {
		numbers[i] = numbers_def[i];
	}
	char option = 'a';
	for (int i = 0; option != EXIT;) {
		print_sudoku(numbers, i);
		option = getchar();
		if (option == FIX) {
			clear_window();
			if (checkSudoku(numbers)) {
				printf("\n\t\t\t\tYou win!\n");
			}
			else {
				printf("\n\t\t\t\tYou lost\n");
			}
			printf("\t\t\t\tPress any key to exit\n");
			getchar();
			return 0;
		}
		else if (option == UP && i >= 4) {
			i -= 4;
		}
		else if (option == DOWN && i <= 11) {
			i += 4;
		}
		else if (option == LEFT && i > 0) {
			i--;
		}
		else if (option == RIGHT && i < 15) {
			i++;
		}
		else if (option >= '1' && option <= '4' && numbers_def[i] == 0) {
			numbers[i] = (option - '0');
		}
		else if (option == NEW) {
			return 1;
		}
	}
	return 0;
}
Exemplo n.º 9
0
void shell_process(PROCESS self, PARAM param)
{
    char buffer[80];
    int i;

    clear_window(&shell_wnd);
    clear_window(&train_wnd);
    clear_window(&divider_wnd);
    for (i = 0; i < 79; i++) output_char(&divider_wnd, 196);

    wprintf(&shell_wnd, "TOS Shell\n");
    wprintf(&shell_wnd, "---------\n\n");
    
    while (1) {
	print_prompt();
	read_line(buffer, 80);
	process_command(buffer);
    }
}
Exemplo n.º 10
0
/*
** Allows user to design a vehicle.
*/
design_vehicle()
{
	Vdesc *d;

	/* Initialize everything */
	d = &design_vdesc;
	clear_window(ANIM_WIN);
	init_vdesign_interface();
	init_vdesc(d);		/* relocated this (HAK 3/93) */
	vdesign_specials_hil(d);
	vdesign_interface(d);
}
Exemplo n.º 11
0
  void tracking_thread<Tnet>::draw(bbox *b) {
#ifdef __GUI__
    disable_window_updates();
    clear_window();
    draw_matrix(frame, "in");
    draw_matrix(tpl, "tpl", 0, frame.dim(1));
    if (b) {
      ubyte red = 0, green = 0, blue = 0;
      if (b->class_id == -42)
	green = 255;
      else
	blue = 255;
      draw_box(b->h0, b->w0, b->width, b->height, red, green, blue);
    }
    enable_window_updates();
#endif
  }
Exemplo n.º 12
0
void draw_maze()
{
    int x, y;
    
    clear_window(pacman_wnd);
    y = 0;
    while (maze[y] != NULL) {
	char* row = maze[y];
	x = 0;
	while (row[x] != '\0') {
	    char ch = row[x];
	    draw_maze_char(ch);
	    x++;
	}
	y++;
    }
    wprintf(pacman_wnd, "PacMan ");
}
Exemplo n.º 13
0
DWORD WINAPI thread_play(void *data)
{
	int winner;
	int seed;

	seed = time(NULL);
	srand(seed);
	while(end == 0)
	{
		one_game();
		SDL_Delay(1000);
		clear_window();
		winner = is_end_game();
		if (winner != -1)
		{
			end = 1;
			printf("%s\n", p[winner].name);
		}	
	}
}
Exemplo n.º 14
0
/* ARGSUSED */
void menu_select_models ( Widget w, long file_id, XtPointer call )
{
long	in, lm;

/*-----------------------------------------------------------------------*/

	OpenModel = 1;

	XtVaGetValues(w, XmNuserData, &lm, NULL);
	in = file_id;

	strcpy(MetaFile,
		  ModelStr[lm].file_fullnames[in]);

	if(MetaFile[0] != '\0') {
		if ( !MpanelMode )
		    clear_window();
		load_meta();
	}
}
Exemplo n.º 15
0
int
maintime::idle_progress (midipulse ticks)
{
    if (ticks >= 0)                     /* ca 2016-03-17 to make bar appear */
    {
        const int yoff = 4;
        int tick_x = (ticks % m_ppqn) * m_box_width / m_ppqn;
        int beat_x = ((ticks / m_beat_width) % m_ppqn) * m_box_less_pill / m_ppqn;
        int bar_x  = ((ticks / m_bar_width)  % m_ppqn) * m_box_less_pill / m_ppqn;
        m_tick = ticks;
        clear_window();
        draw_rectangle(black(), 0, yoff, m_box_width, m_box_height, false);
        if (tick_x <= m_flash_x)       /* for flashing the maintime bar     */
            draw_rectangle(grey(), 2, yoff+2, m_flash_width, m_flash_height);

        draw_rectangle(black(), beat_x + 2, yoff+2, m_pill_width, m_flash_height);
        draw_rectangle(bar_x + 2, yoff+2, m_pill_width, m_flash_height);
    }
    return true;
}
Exemplo n.º 16
0
void print_sudoku(unsigned int *numbers, int act_pos)
{
	char *output = new char[1024];
	clear_window();
	strcpy(output, "\n\t\t\t\t");
	for (int i = 0; i < 16; i++) {
		strcat(output, "|");
		if (i == act_pos) {
			strcat(output, "<");
		}
		else {
			strcat(output, " ");
		}
		if (numbers[i] == 0) {
			strcat(output, "X");
		}
		if (numbers[i] != 0) {
			char *c = new char[2];
			c[0] = numbers[i]+'0';
			c[1] = '\0';
			strcat(output, c);
			delete c;
		}
		if (i == act_pos) {
			strcat(output, ">");
		}
		else {
			strcat(output, " ");
		}
		if ((i+1) % 4 == 0) {
			strcat(output, "|\n\t\t\t\t");
		}
	}
	strcat(output, "\n\t\t\t\tw\n\t\t\t      a   d     move cursor\n\t\t\t\ts");
	strcat(output, "\n\t\t\t\tf\tfix squares");
	strcat(output, "\n\t\t\t\tq\tquit game");
	strcat(output, "\n\t\t\t\tn\tnew board");
	printf("%s\n", output);
	delete output;
}
Exemplo n.º 17
0
int display_net(list<string>::iterator &ifname,
		bool signd, bool load, list<string> *mats) {
  // create network
  idx<ubyte> classes(1,1);
  load_matrix<ubyte>(classes, conf->get_cstring("classes"));
  answer_module<T,T,T> *answer = create_answer<T,T,T>(*conf, classes.dim(0));
  if (!answer) eblerror("no answer module found");
  uint noutputs = answer->get_nfeatures();
  parameter<T> theparam;
  intg thick;
  module_1_1<T> *net = create_network<T>(theparam, *conf, thick, noutputs);
  cout << "Network parameters: " << theparam << endl;
  vector<string> weights =
      string_to_stringvector(conf->get_string("weights_file"));
  // loading weights
  theparam.load_x(weights);
  // displaying internals
  uint h0 = 0, w0 = 0;
#ifdef __GUI__
  disable_window_updates();
  clear_window();
  if (show_filename) {
    gui << at(h0, w0) << black_on_white() << ifname->c_str();
    h0 += 16;
  }
  if (autorange) // automatic range
    lg.display_internals(*net, h0, w0, zoom, (T) 0, (T) 0, maxwidth);
  else // fixed range
    lg.display_internals(*net, h0, w0, zoom, (T) range[0], (T) range[1],
			 maxwidth);
  // update title
  string title;
  title << "matshow: " << ebl::basename(ifname->c_str());
  set_window_title(title.c_str());
  enable_window_updates();
#endif
  return 1;
}
Exemplo n.º 18
0
/*-----------------------------------------------------------------------*/
void display_help(char *HelpLines[], char *AnyKey, struct window_parms *wp)
{
   int i, scrnline;
   char mybl[BLSIZE+1];

   for (i = scrnline = 0; strcmp(HelpLines[i], ""); i++)
     {
       VioWrtCharStr(HelpLines[i], strlen(HelpLines[i]), scrnline++, 0, (HVIO)0);
       if (scrnline == wp->display_rows)
         {
           VioWrtCharStr(AnyKey, strlen(AnyKey), wp->window_rows - 1, 0, (HVIO)0);
           getch();
           clear_window(wp);
           scrnline = 0;
         }
      }
   if (scrnline > 0)
     {
       for (i = 0; i < BLSIZE; mybl[i++] = SPACE);
       strncpy(mybl, AnyKey, strlen(AnyKey));
       VioWrtCharStr(mybl, BLSIZE, wp->window_rows - 1, 0, (HVIO)0);
       getch();
     }
}
Exemplo n.º 19
0
void train_process(PROCESS self, PARAM param)
{

	COM_Message msg;
	char buffer [128];
	msg.input_buffer = buffer;
	
	//	clear train window
	clear_window(&train_wnd);
	
	//	set up track to ensure safety of trains
	init_track();
	
	//	determine disposition of Zamboni
	int zamboniConfig = get_zamboni_condition();
	//int zamboniConfig = 0;
	
	//	determine config of train/wagon
	int trainConfig = get_train_wagon_config();
	
	get_wagon(trainConfig, zamboniConfig);
	
	while(1);
}
Exemplo n.º 20
0
void detection_thread<T>::execute() {
  try {
    bool	display        = false;
#ifdef __GUI__
    display = conf.exists_true("display")
        && conf.exists_true("display_threads");
    bool	mindisplay     = conf.exists_true("minimal_display");
    bool       save_video     = conf.exists_true("save_video");
    bool	display_states = conf.exists_true("display_states");
    uint       wid	       = 0;	// window id
    uint       wid_states     = 0;	// window id
#endif
    uint	display_sleep  = conf.try_get_uint("display_sleep", 0);
    //      if (!display && save_video) {
    //        // we still want to output images but not show them
    //        display = true;
    // #ifdef __GUI__
    //        set_gui_silent();
    // #endif
    //      }
    // load network and weights in a forward-only parameter
    parameter<T> theparam;
    theparam.set_forward_only();
    idx<ubyte> classes(1,1);
    //try { // try loading classes names but do not stop upon failure
    load_matrix<ubyte>(classes, conf.get_cstring("classes"));
    // } catch(std::string &err) {
    //   merr << "warning: " << err;
    //   merr << std::endl;
    // }
    std::vector<std::string> sclasses = ubyteidx_to_stringvector(classes);
    answer_module<T> *ans = create_answer<T,T,T>(conf, classes.dim(0));
    uint noutputs = ans->get_nfeatures();
    intg thick = -1;
    module_1_1<T> *net = create_network<T>(theparam, conf, thick, noutputs,
                                           "arch", this->_id);
    // loading weights
    if (conf.exists("weights")) { // manual weights
      // concatenate weights if multiple ones
      std::vector<std::string> w =
          string_to_stringvector(conf.get_string("weights"));
      mout << "Loading weights from: " << w << std::endl;
      theparam.load_x(w);
      // permute weights by blocks
      if (conf.exists("weights_permutation")) {
        std::string sblocks = conf.get_string("weights_blocks");
        std::string spermut = conf.get_string("weights_permutation");
        std::vector<intg> blocks = string_to_intgvector(sblocks.c_str());
        std::vector<uint> permut = string_to_uintvector(spermut.c_str());
        theparam.permute_x(blocks, permut);
      }
    } else {
      if (conf.exists_true("manual_load")) { // manual load
        eblwarn("\"weights\" variable not defined, loading manually "
                << "if manual_load defined");
        manually_load_network(*((layers<T>*)net), conf);
      } else { // random weights
        int seed = dynamic_init_drand();
        eblwarn("No weights to load, randomizing weights with seed " << seed);
        forget_param_linear fgp(1, 0.5, seed);
        net->forget(fgp);
      }
    }
    DEBUGMEM_PRETTY("before detection");
    // detector
    detector<T> detect(*net, sclasses, ans, NULL, NULL, mout, merr);
    init_detector(detect, conf, outdir, silent);
    // keep pointer to detector
    pdetect = &detect;
    bootstrapping<T> boot(conf);

    // when a bbox file is given, ignore the processing, load the pre-computed
    // bboxes and feed them to the nms (non-maximum suppression).
    bboxes boxes(bbox_all, NULL, mout, merr);
    boxes.print_saving_type(); // inform user how we save boxes
    bool precomputed_boxes = false;
    if (conf.exists("bbox_file")) {
      precomputed_boxes = true;
      std::string bbfile = conf.get_string("bbox_file");
      boxes.load_eblearn(bbfile);
    }
    bool bmask_class = false;
    if (conf.exists("mask_class"))
      bmask_class = detect.set_mask_class(conf.get_cstring("mask_class"));

    std::string viddir = outdir;
    viddir += "video/";
    mkdir_full(viddir);
    // gui
#ifdef __GUI__
    uint display_wmax = conf.try_get_uint("display_max_width", 3000);
    T display_min = (T) conf.try_get_double("display_min", -1.7);
    T display_max = (T) conf.try_get_double("display_max", 1.7);
    T display_in_max = (T) conf.try_get_double("display_in_max", 255);
    T display_in_min = (T) conf.try_get_double("display_in_min", 0);
    float display_transp = conf.try_get_float("display_bb_transparency", 0);
    uint qstep1 = conf.try_get_uint("qstep1", 0);
    uint qheight1 = conf.try_get_uint("qheight1", 0);
    uint qwidth1 = conf.try_get_uint("qwidth1", 0);
    uint qstep2 = conf.try_get_uint("qstep2", 0);
    uint qheight2 = conf.try_get_uint("qheight2", 0);
    uint qwidth2 = conf.try_get_uint("qwidth2", 0);
    module_1_1_gui	netgui;
    wid_states  = display_states ? new_window("network states"):0;
    night_mode();
    std::string title = "EBLearn detector: ";
    title += _name;
    if (display) {
      wid = new_window(title.c_str());
      mout << "displaying in window " << wid << std::endl;
      night_mode();
    }
    float zoom = conf.try_get_float("display_zoom", 1);
    bool bbox_show_conf = !conf.exists_false("bbox_show_conf");
    bool bbox_show_class = !conf.exists_false("bbox_show_class");
    detector_gui<T>
        dgui(conf.try_get_uint("show_extracted", 0),
             conf.exists_bool("queue1"), qstep1, qheight1,
             qwidth1, conf.exists_bool("queue2"), qstep2, qheight2, qwidth2,
             bbox_show_class, bbox_show_conf);
    if (bmask_class)
      dgui.set_mask_class(conf.get_cstring("mask_class"),
                          (T) conf.try_get_double("mask_threshold", 0));
#endif
    // timing variables
    timer tpass, toverall;
    long ms;
    // loop
    toverall.start();
    // we're ready
    bavailable = true;
    while(!this->_stop) {
      // wait until a new image is made available
      while (!in_updated && !_stop) {
        millisleep(1);
      }
      tpass.restart();
      if (_stop) break ;
      // we got a new frame, reset new frame flag
      in_updated = false; // no need to lock mutex
      // check if this frame should be skipped
      if (boot.skip_frame(frame_name)) {
        skip_frame();
        continue ;
      } else if (!frame_loaded) {
        uframe = load_image<ubyte>(frame_fullname);
        mout << "loaded image " << frame_fullname << std::endl;
      }
      if (!silent) mout << "processing " << frame_name << std::endl;
      // check frame is correctly allocated, if not, allocate.
      if (frame.order() != uframe.order())
        frame = idx<T>(uframe.get_idxdim());
      else if (frame.get_idxdim() != uframe.get_idxdim())
        frame.resize(uframe.get_idxdim());
      // copy frame
      idx_copy(uframe, frame);
      // run detector
      if (!display) { // fprop without display
        if (precomputed_boxes) {
          try {
            bboxes *bb = boxes.get_group(frame_name);
            idxdim d = boxes.get_group_dims(frame_name);
            d.insert_dim(0, 1);
            bboxes pruned;
            detect.init(d);
            detect.fprop_nms(*bb, pruned);
            copy_bboxes(pruned); // make a copy of bounding boxes
            // resize frame so that caller knows the size of the frame
            idxdim framedim = frame.get_idxdim();
            if (d.dim(1) == -1 || d.dim(2) == -1)
              eblerror("pre-computed boxes must contain full image size, "
                       << "but found: " << d);
            framedim.setdim(0, d.dim(1));
            framedim.setdim(1, d.dim(2));
            frame.resize(framedim);
          } catch(eblexception &e) {
#ifdef __NOEXCEPTIONS__
            merr << "exception" << std::endl;
#else
            merr << e << std::endl;
#endif
          }
        } else {
          try {
            mout << "starting processing of frame " << frame_name << std::endl;
            bboxes &bb = detect.fprop(frame, frame_name.c_str(), frame_id);
            copy_bboxes(bb); // make a copy of bounding boxes
          } catch(ebl::eblexception &e) { // detection failed
#ifdef __NOEXCEPTIONS__
            eblwarn("detection failed");
#else
            eblwarn("detection failed: " << e);
#endif
            clear_bboxes();
          }
        }
      }
#ifdef __GUI__
      else { // fprop and display
        if (precomputed_boxes) eblerror("not implemented for nms only (TODO)");
        disable_window_updates();
        select_window(wid);
        clear_window();
        std::string title = _name;
        title << ": " << frame_name;
        set_window_title(title.c_str());
        //	 clear_resize_window();
        try {
          if (mindisplay) {
            bboxes &bb =
                dgui.display(detect, frame, frame_name.c_str(), frame_id,
                             0, 0, zoom, display_min, display_max,
                             wid, _name.c_str(), display_transp);
            copy_bboxes(bb); // make a copy of bounding boxes
          } else {
            // extract & display boxes
            bboxes &bb =
                dgui.display_inputs_outputs(detect, frame, frame_name.c_str(),
                                            frame_id, 0, 0, zoom,
                                            display_min, display_max, wid,
                                            _name.c_str(),
                                            display_in_min, display_in_max,
                                            display_transp, display_wmax);
            // make a copy of bounding boxes
            copy_bboxes(bb);
          }
        } catch(ebl::eblexception &e) { // detection failed
          eblwarn("detection failed: " << e);
          clear_bboxes();
        }
        enable_window_updates();
      }
      if (display_states) {
        dgui.display_current(detect, frame, wid_states, NULL, zoom);
        select_window(wid);
      }
      if (save_video && display) {
        std::string fname = viddir;
        fname += frame_name;
        save_window(fname.c_str());
        if (!silent) mout << "saved " << fname << std::endl;
      }
#endif
      if (!silent)
        mout << "processing done for frame " << frame_name << std::endl;
      // bootstrapping
      if (conf.exists_true("bootstrapping")) {
        boot.fprop(detect, frame_name);
        // add multiple scales if positives and scales are defined
        if (conf.exists("gt_scales") && boot.extract_positives()) {
          std::vector<double> scales =
              string_to_doublevector(conf.get_cstring("gt_scales"));
          for (uint s = 0; s < scales.size(); ++s) {
            double f = scales[s];
            // downsample input by f
            detect.set_resolution(f);
            detect.init(frame.get_idxdim(), frame_name.c_str());
            detect.fprop(frame, frame_name.c_str(), frame_id);
            boot.fprop(detect, frame_name, false, f);
          }
          detect.set_scaling_original();
          detect.init(frame.get_idxdim(), frame_name.c_str());
        }
        copy_bootstrapping(boot.get_all(), boot.get_bball());
#ifdef __GUI__
        // display groundtruth
        if (conf.exists_true("display_bootstrapping"))
          dgui.display_groundtruth(detect, frame, boot.get_gtall(),
                                   boot.get_gtclean(), boot.get_gtrest(),
                                   boot.get_bbpos(), boot.get_bbneg(),
                                   boot.get_pos(), boot.get_neg(), 0, 0, zoom,
                                   display_min, display_max);
#endif
      }
      total_saved = detect.get_total_saved();
      ms = tpass.elapsed_milliseconds();
      if (!silent) {
        mout << bbs.pretty_short(detect.get_labels());
        mout << "processing=" << ms << " ms ("
             << tpass.elapsed() << ")" << std::endl;
      }
      DEBUGMEM_PRETTY("after detection");
      // switch 'updated' flag on to warn we just added new data
      set_out_updated();
      // display sleep
      if (display_sleep > 0) {
        mout << "sleeping for " << display_sleep << "ms." << std::endl;
        millisleep(display_sleep);
      }
      if (conf.exists("save_max") &&
          detect.get_total_saved() > conf.get_uint("save_max"))
        break ; // limit number of detection saves
    }
    mout << "detection finished. Execution time: " << toverall.elapsed()<<std::endl;
    // free variables
    if (net) delete net;
    if (ans) delete ans;
  } eblcatcherror();
}
Exemplo n.º 21
0
int main() {
    int button_code;
    int pause_state = 0;
    int reset_state = 0;

    setup_gui();

    // Seed random num generator
    srand (time(NULL));

    box_fam = create_gen(gen_size);
    randomise_gen(box_fam);    

    ifit = -1;

    for (int i=0; i<ngen; i++) {
        // Score generation
        score_gen(box_fam);

        printf("gen %i\r", i);
        fflush(stdout);
        // Draw fittest of the fit
        jfit = fittest_cov(box_fam);
        if (ifit != jfit) {
            ifit = jfit;
            clear_window();
            draw_boarder();
            draw_cover(& box_fam[ifit]);
            draw_pause_button(pause_state);
            draw_reset_button(reset_state);
            flush_window();
            printf("gen %i, %f\n", i, nboxes*pow(box_fam[ifit].l,2));
            add_score(i, nboxes*pow(box_fam[ifit].l,2));
        } 
        if (window_redraw_required()) {
            clear_window();
            draw_boarder();
            draw_cover(& box_fam[ifit]);
            draw_pause_button(pause_state);
            draw_reset_button(reset_state);
            draw_scores();
            flush_window();
        }

        button_code = handle_button_presses();
        while (button_code != 0 || pause_state || reset_state) {
            if (pause_state || reset_state)
                button_code = blocking_handle_button_presses();

            switch (button_code) {
                case -1:
                    // Redraw Required
                    clear_window();
                    draw_boarder();
                    draw_cover(& box_fam[ifit]);
                    draw_pause_button(pause_state);
                    draw_reset_button(reset_state);
                    draw_scores();
                    flush_window();
                    break;
                case 1:
                    // Play/Pause Button
                    if (pause_state) {
                        printf("\rPlay!         \n");
                        pause_state = 0;
                    } else {
                        printf("\rPause!        \n");
                        pause_state = 1;
                    }

                    draw_pause_button(pause_state);
                    flush_window();
                    break;
                case 2:
                    // Reset/Start Button  
                    if (reset_state) {
                        printf("\rStart!             \n");
                        reset_state = 0;
                    } else {
                        printf("\rReset!             \n");
                        print_best();
                        i = 0;
                        randomise_gen(box_fam);
                        score_gen(box_fam);            
                        reset_state = 1;
                        reset_scores();
                        flush_window();
                    }
                    clear_window();
                    draw_boarder();
                    draw_cover(& box_fam[ifit]);

                    draw_pause_button(pause_state);
                    draw_reset_button(reset_state);
                    flush_window();
                    break;
                default:
                    printf("\rButton Error %i\n         ", button_code);
                    exit(button_code);
            }
            button_code = handle_button_presses();
        }

        // Evolve Generation
        new_gen(box_fam); 
    }
    // Clear last gen n line
    printf("                  \r");
    fflush(stdout);

    close_gui();
    print_best();

    printf("Press enter to close\n");
    while( getchar() != '\n' );
    return 0;
}
Exemplo n.º 22
0
void Ending(void)
{
    char stuff[][2][32] = 
    {
    {"XSoldier staff",      ""},
    {"Producer",            "Y.Hashimoto"},
    {"Program",             "R.Masuda"},
    {"",                    "Y.Hashimoto"},
    {"Character Algorithm", "K.Inomata"},
    {"",                    "H.Yokobori"},
    {"",                    "M.Nakayama"},
    {"",                    "Y.Hashimoto"},
    {"Character Design",    "H.Hayakawa"},
    {"",                    "Y.Hashimoto"},
    {"1.x Series Developer", "Oohara Yuuma"},
    {"Special Thanks",      "N.Oohashi"},
    {"",                    "T.Yamada"},
    {"",                    "T.Igari"},
    {"",                    "RAKI all members"},
    {"",                    ".... and YOU."},
    };

    char msg[][30] = 
    {
	"Try Next Stage!!",
	"You are a great soldier!!!",
	"crazy ........"
    };

    /* number of staffs */
    int stfnumber = 16;
    int count = 0;
    int time = (stfnumber + 6) * 100;
    int len;
    int i;

    while (1)
    {
        if (waittime && (signal_delivered==0))
	    pause();
        signal_delivered = 0;

	if (count < time)
        {
            count++;
        }

        if (event_handle_ending() == 0)
          return;

        clear_window();
	DrawStar(StarPtn1);
	DrawStar(StarPtn2);

	for (i=0; i<stfnumber; i++)
	{
	    if (i == 0)
	    {
		draw_string(210, FieldH - count + 100 * i,
                            stuff[i][0], strlen(stuff[i][0]));
		draw_string(450, FieldH - count + 100 * i,
                            stuff[i][1], strlen(stuff[i][1]));
	    }
	    else
	    {
		draw_string(100, FieldH - count + 100 * i,
                            stuff[i][0], strlen(stuff[i][0]));
		draw_string(300, FieldH - count + 100 * i + 30,
                            stuff[i][1], strlen(stuff[i][1]));
	    }
	}
	
	if (count > time-30)
	{
	    len = count - (time-30);

	    if (manage->Loop < 3)
	    {
		if (len >= strlen(msg[manage->Loop-1]))
                {
                  draw_string(200, 440, "Press space key",
                              strlen("Press space key"));
                  len = strlen(msg[manage->Loop-1]);
                }
                
		draw_string(200, 400, msg[manage->Loop-1], len);
	    }
	    else
	    {
		if (len >= strlen(msg[2]))
                {
                  draw_string(200, 440, "Press space key",
                              strlen("Press space key"));
                  len = strlen(msg[2]);
                }
	    }
	}

        redraw_window();
    }
}
Exemplo n.º 23
0
int main(int argc, char **argv)
{
	log_options_t opts = LOG_OPTS_STDERR_ONLY;
	node_info_msg_t *node_info_ptr = NULL;
	node_info_msg_t *new_node_ptr = NULL;
	int error_code;
	int height = 40;
	int width = 100;
	int startx = 0;
	int starty = 0;
	int end = 0;
	int i;
	int rc;

	slurm_conf_init(NULL);
	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_DAEMON, NULL);
	parse_command_line(argc, argv);
	if (params.verbose) {
		opts.stderr_level += params.verbose;
		log_alter(opts, SYSLOG_FACILITY_USER, NULL);
	}

	if (params.cluster_dims == 4) {
		min_screen_width = 92;
	} else if (params.cluster_dims == 3)
		min_screen_width = 92;

	/* no need for this if you are resolving */
	while (slurm_load_node((time_t) NULL,
			       &new_node_ptr, SHOW_ALL)) {
		if (params.resolve || (params.display == COMMANDS)) {
			new_node_ptr = NULL;
			break;		/* just continue */
		}
		error_code = slurm_get_errno();
		printf("slurm_load_node: %s\n",
		       slurm_strerror(error_code));
		if (params.iterate == 0)
			exit(1);
		sleep(10);	/* keep trying to reconnect */
	}

	select_g_ba_init(new_node_ptr, 0);

	if (dim_size == NULL) {
		dim_size = get_cluster_dims(new_node_ptr);
		if ((dim_size == NULL) || (dim_size[0] < 1))
			fatal("Invalid system dimensions");
	}
	_init_colors();

	if (params.resolve) {
		char *ret_str = resolve_mp(params.resolve, new_node_ptr);
		if (ret_str) {
			printf("%s", ret_str);
			xfree(ret_str);
		}
		_smap_exit(0);	/* Calls exit(), no return */
	}
	if (!params.commandline) {
		int check_width = min_screen_width;

		initscr();
		init_grid(new_node_ptr, COLS);
		signal(SIGWINCH, (void (*)(int))_resize_handler);

		if (params.cluster_dims == 4) {
			height = dim_size[2] * dim_size[3] + dim_size[2] + 3;
			width = (dim_size[1] + dim_size[3] + 1) * dim_size[0]
				 + 2;
			check_width += width;
		} else if (params.cluster_dims == 3) {
			height = dim_size[1] * dim_size[2] + dim_size[1] + 3;
			width = dim_size[0] + dim_size[2] + 3;
			check_width += width;
		} else {
			height = 10;
			width = COLS;
		}

	        if ((COLS < check_width) || (LINES < height)) {
			endwin();
			error("Screen is too small make sure the screen "
			      "is at least %dx%d\n"
			      "Right now it is %dx%d\n",
			      check_width,
			      height,
			      COLS,
			      LINES);
			_smap_exit(1);	/* Calls exit(), no return */
		}

		raw();
		keypad(stdscr, true);
		noecho();
		cbreak();
		curs_set(0);
		nodelay(stdscr, true);
		start_color();
		_set_pairs();

		grid_win = newwin(height, width, starty, startx);
		max_display = (getmaxy(grid_win) - 1) * (getmaxx(grid_win) - 1);

		if (params.cluster_dims == 4) {
			startx = width;
			width = COLS - width - 2;
			height = LINES;
		} else if (params.cluster_dims == 3) {
			startx = width;
			width = COLS - width - 2;
			height = LINES;
		} else {
			startx = 0;
			starty = height;
			height = LINES - height;
		}

		text_win = newwin(height, width, starty, startx);
        }
	while (!end) {
		if (!params.commandline) {
			_get_option();
redraw:
			clear_window(text_win);
			clear_window(grid_win);
			move(0, 0);

			update_grid(new_node_ptr);
			main_xcord = 1;
			main_ycord = 1;
		}

		if (!params.no_header)
			print_date();

		clear_grid();
		switch (params.display) {
		case JOBS:
			get_job();
			break;
		case RESERVATIONS:
			get_reservation();
			break;
		case SLURMPART:
			get_slurm_part();
			break;
		case COMMANDS:
#ifdef HAVE_BG
			wclear(text_win);
			get_command();
#else
			error("Must be on a real BG SYSTEM to "
			      "run this command");
			if (!params.commandline)
				endwin();
			_smap_exit(1);	/* Calls exit(), no return */
#endif
			break;
		case BGPART:
			if (params.cluster_flags & CLUSTER_FLAG_BG)
				get_bg_part();
			else {
				error("Must be on a BG SYSTEM to "
				      "run this command");
				if (!params.commandline)
					endwin();
				_smap_exit(1);	/* Calls exit(), no return */
			}
			break;
		}

		if (!params.commandline) {
			box(text_win, 0, 0);
			wnoutrefresh(text_win);

			print_grid();
			box(grid_win, 0, 0);
			wnoutrefresh(grid_win);

			doupdate();

			node_info_ptr = new_node_ptr;
			if (node_info_ptr) {
				error_code = slurm_load_node(
					node_info_ptr->last_update,
					&new_node_ptr, SHOW_ALL);
				if (error_code == SLURM_SUCCESS)
					slurm_free_node_info_msg(
						node_info_ptr);
				else if (slurm_get_errno()
					 == SLURM_NO_CHANGE_IN_DATA) {
					error_code = SLURM_SUCCESS;
					new_node_ptr = node_info_ptr;
				}
			} else {
				error_code = slurm_load_node(
					(time_t) NULL,
					&new_node_ptr, SHOW_ALL);
			}
			if (error_code && (quiet_flag != 1)) {
				if (!params.commandline) {
					mvwprintw(
						text_win,
						main_ycord,
						1,
						"slurm_load_node: %s",
						slurm_strerror(
							slurm_get_errno()));
					main_ycord++;
				} else {
					printf("slurm_load_node: %s",
					       slurm_strerror(
						       slurm_get_errno()));
				}
			}
		}

		if (params.iterate) {
			for (i = 0; i < params.iterate; i++) {
				sleep(1);
				if (!params.commandline) {
					if ((rc = _get_option()) == 1)
						goto redraw;
					else if (resize_screen) {
						resize_screen = 0;
						goto redraw;
					}
				}
			}
		} else
			break;

	}

	if (!params.commandline) {
		nodelay(stdscr, false);
		getch();
		endwin();
	}

	_smap_exit(0);	/* Calls exit(), no return */
	exit(0);	/* Redundant, but eliminates compiler warning */
}
Exemplo n.º 24
0
static void *_resize_handler(int sig)
{
	int startx = 0, starty = 0;
	int height = 40, width = 100;
	int check_width = min_screen_width;
	main_ycord = 1;

	/* clear existing data and update to avoid ghost during resize */
	clear_window(text_win);
	clear_window(grid_win);
	doupdate();
	delwin(grid_win);
	delwin(text_win);

	endwin();
	initscr();
	doupdate();	/* update now to make sure we get the new size */

	if (params.cluster_dims == 4) {
		height = dim_size[2] * dim_size[3] + dim_size[2] + 3;
		width = (dim_size[1] + dim_size[3] + 1) * dim_size[0];
		check_width += width;
	} else if (params.cluster_dims == 3) {
		height = dim_size[1] * dim_size[2] + dim_size[1] + 3;
		width = dim_size[0] + dim_size[2] + 3;
		check_width += width;
	} else {
		height = 10;
		width = COLS;
	}

	if (COLS < check_width || LINES < height) {
		endwin();
		error("Screen is too small make sure "
		      "the screen is at least %dx%d\n"
		      "Right now it is %dx%d\n", width, height, COLS, LINES);
		_smap_exit(0);	/* Calls exit(), no return */
	}

	grid_win = newwin(height, width, starty, startx);
	max_display = (getmaxy(grid_win) - 1) * (getmaxx(grid_win) - 1);

	if (params.cluster_dims == 4) {
		startx = width;
		width = COLS - width - 2;
		height = LINES;
	} else if (params.cluster_dims == 3) {
		startx = width;
		width = COLS - width - 2;
		height = LINES;
	} else {
		startx = 0;
		starty = height;
		height = LINES - height;
	}

	text_win = newwin(height, width, starty, startx);

	print_date();
	switch (params.display) {
	case JOBS:
		get_job();
		break;
	case RESERVATIONS:
		get_reservation();
		break;
	case SLURMPART:
		get_slurm_part();
		break;
	case COMMANDS:
#ifdef HAVE_BG
		get_command();
#endif
		break;
	case BGPART:
		if (params.cluster_flags & CLUSTER_FLAG_BG)
			get_bg_part();
		break;
	}

	print_grid();
	box(text_win, 0, 0);
	box(grid_win, 0, 0);
	wnoutrefresh(text_win);
	wnoutrefresh(grid_win);
	doupdate();
	resize_screen = 1;
	return NULL;
}
Exemplo n.º 25
0
void put_ship_on_map(int mode)
{
	int pos1, pos2;
	if (mode == ONE_PLAYER) {
		for (int i = 0; i < 10; i++) {
			for (int x = 0; x < 10; x++) {
				game_map[1][i][x] = WATER_IA;
			}
		}
		pos1 = getRandomNumber(10);
		pos1++;
		pos2 = getRandomNumber(pos1);
		pos2++;
	}
	for (int z = 0; z <= 1; z++) {
		clear_window();
		if (mode == ONE_PLAYER && z == 0) {
			continue;
		}
		for (int i = 1; i <= 4; i++) {
			printf("Barco %d\nX: ", i);
			int x = getnum();
			printf("%d\nY: ", x);
			int y = getnum();
			printf("%d\n", y);
			char option;
			do {
				printf("Horizontal o Vertical (h/v): ");
				option = getchar();
				printf("%c\n", option);
			} while(option != 'h' && option != 'v');
			game_map[z][y][x] = SHIP_IA;
			if (mode == ONE_PLAYER) {
				for (int p = 0; p < (i+1); p++) {
					if (x+p <= 9 && option == 'h') {
						game_map[z][y][x+p] = SHIP_IA;
					}
					if (y+p <= 9 && option == 'v') {
						game_map[z][y+p][x] = SHIP_IA;
					}
				}
				x -= pos1;
				y -= pos2;
				if (x < 0) {
					x *= -1;
				}
				if (y < 0) {
					y *= -1;
				}
				game_map[0][x][y] = UNKOWN_SHIP;
				for (int p = 0; p < (i+1); p++) {
					if (y+p <= 9) {
						game_map[0][x][y+p] = UNKOWN_SHIP;
					}
				}
			}
			else if (mode == MULTI_PLAYER) {
				for (int p = 0; p < (i+1); p++) {
					if (x+p <= 9 && option == 'h') {
						game_map[z][y][x+p] = UNKOWN_SHIP;
					}
					if (y+p <= 9 && option == 'v') {
						game_map[z][y+p][x] = UNKOWN_SHIP;
					}
				}
			}
		}
	}
}
Exemplo n.º 26
0
void shell_process(PROCESS self, PARAM param)
{
	clear_window(&shell_wnd);
	//print_all_processes(&shell_wnd);
	
	//testStringCompare();
	
	char inBuf[128] = "";
	char param1[128] = "\0";
	char param2[128] = "\0";
	char param3[128] = "\0";
	int bufSize = sizeof(inBuf)/sizeof(char);
	int bufCurs = 0;
	int i;
	
	char ch;
 	Keyb_Message msg; 	
	
 	//	Command
 	int (*func)(param1, param2);

	while (1) {
		//	reset vars after each command is processed
		ch = 0;
		bufCurs = 0;
		for(i = 0; i < 128; i++)
		{
			inBuf[i] = 0;
			param1[i] = 0;
			param2[i] = 0;
			param3[i] = 0;
		}
		//	output command prompt
		wprintf(&shell_wnd, "SamOS >>> ");
		
	 	//read command from keyboard, terminate upon reading newline
		while(ch != 13)
		{
			//	check for buffer overflow
			if(bufCurs > 126)
			{
				wprintf(&shell_wnd, "\nTrying to overflow the buffer? Try again, Bub\n");
				break;
			}
			
			msg.key_buffer = &ch;
 			send(keyb_port, &msg);
		 	
			//	cover case of backspace
			if(ch == '\b')
			{
				//	do nothing if buffer is empty
				if(bufCurs == 0)
				{
					continue;
				}
				else
				{
				inBuf[bufCurs] = 0;
				bufCurs--;
				}
			}
			else if(ch != 13)
			{
				//	commit entered character to buffer, increment cursor
				inBuf[bufCurs] = ch;
				bufCurs++;
			}
			//	output entered character to console
			output_char(&shell_wnd, ch);
		}
		//	input buffer debug
		//wprintf(&shell_wnd,inBuf);
		get_params(inBuf,param1,param2,param3);
		
		executeCommand(param1,param2,param3);
	}
} 
Exemplo n.º 27
0
void clear_func(int argc, char *argv)
{
	clear_window(shell_window);
}
Exemplo n.º 28
0
MAIN_QTHREAD(int, argc, char **, argv) { // macro to enable multithreaded gui
#else
  int main(int argc, char **argv) { // regular main without gui
#endif
    try {
      // check input parameters
      if ((argc != 2) && (argc != 3) ) {
	cerr << "wrong number of parameters." << endl;
	cerr << "usage: objdetect <config file> [directory or file]" << endl;
	return -1;
      }
#ifdef __LINUX__
      feenableexcept(FE_DIVBYZERO | FE_INVALID); // enable float exceptions
#endif
      ipp_init(1); // limit IPP (if available) to 1 core
      // load configuration
      configuration	conf(argv[1], true, true, false);
      if (!conf.exists("root2")) {
	string dir;
	dir << dirname(argv[1]) << "/";
	cout << "Looking for trained files in: " << dir << endl;
	conf.set("root2", dir.c_str());
	conf.set("current_dir", dir.c_str());
      }
      conf.resolve();
      if (conf.exists_true("show_conf")) conf.pretty();
      bool		color	      = conf.exists_bool("color");
      uint		norm_size     = conf.get_uint("normalization_size");
      Tnet		threshold     = (Tnet) conf.get_double("threshold");
      bool		display       = false;
      bool		display_states= false;
      bool		mindisplay    = false;
      uint		display_sleep = 0;
      bool		save_video    = false;
      string		cam_type      = conf.get_string("camera");
      int		height        = -1;
      int		width         = -1;
      if (conf.exists("input_height")) height = conf.get_int("input_height");
      if (conf.exists("input_width")) width = conf.get_int("input_width");
      bool              input_random  = conf.exists_true("input_random");
      uint              npasses       = 1;
      char              next_on_key   = 0;
      uint              wid           = 0; // window id
      uint              wid_states    = 0; // window id
      string		outdir        = "out_";
      if (conf.exists("next_on_key")) {
	next_on_key = conf.get_char("next_on_key");
	cout << "Press " << next_on_key << " to process next frame." << endl;
      }
      outdir += tstamp();
      outdir += "/";
      cout << "Saving outputs to " << outdir << endl;

      // load network and weights
      parameter<fs(Tnet)> theparam;
      idx<ubyte> classes(1,1);
      try {
	load_matrix<ubyte>(classes, conf.get_cstring("classes"));
      } catch(string &err) { cerr << "warning: " << err << endl; }
      vector<string> sclasses = ubyteidx_to_stringvector(classes);
      answer_module<SFUNC2(Tnet)> *ans =
       create_answer<SFUNC2(Tnet)>(conf, classes.dim(0));
      uint noutputs = ans->get_nfeatures();
      module_1_1<SFUNC(Tnet)> *net =
	create_network<SFUNC(Tnet)>(theparam, conf, noutputs);
      // loading weights
      if (!conf.exists("weights")) { // manual weights
	cerr << "warning: \"weights\" variable not defined, loading manually "
	     << "if manual_load defined" << endl;
       if (conf.exists_true("manual_load"))
	 manually_load_network(*((layers<SFUNC(Tnet)>*)net), conf);
      } else { // multiple-file weights
	// concatenate weights if multiple ones
	vector<string> w =
	  string_to_stringvector(conf.get_string("weights"));
	cout << "Loading weights from: " << w << endl;
	theparam.load_x(w);
      }
      
      // detector
      detector<fs(Tnet)> detect(*net, sclasses, *ans, NULL, NULL);
      // multi-scaling parameters      
      double maxs = conf.exists("max_scale")?conf.get_double("max_scale") : 1.0;
      double mins = conf.exists("min_scale")?conf.get_double("min_scale") : 1.0;
      t_scaling scaling_type = SCALES_STEP;
      vector<idxdim> scales;
      if (conf.exists("scaling_type"))
       scaling_type = (t_scaling) conf.get_uint("scaling_type");
      switch (scaling_type) {
      case MANUAL:
	if (!conf.exists("scales"))
	  eblerror("expected \"scales\" variable to be defined in manual mode");
	scales = string_to_idxdimvector(conf.get_cstring("scales"));
	detect.set_resolutions(scales);
	break ;
      case ORIGINAL: detect.set_scaling_original(); break ;
      case SCALES_STEP:
	detect.set_resolutions(conf.get_double("scaling"), maxs, mins);
	break ;
      case SCALES_STEP_UP:
	detect.set_resolutions(conf.get_double("scaling"), maxs, mins);
	detect.set_scaling_type(scaling_type);
	break ;
      default:
	detect.set_scaling_type(scaling_type);
      }
     // optimize memory usage by using only 2 buffers for entire flow
     SBUF<Tnet> input(1, 1, 1), output(1, 1, 1);
     if (!conf.exists_false("mem_optimization"))
       detect.set_mem_optimization(input, output, true);
     // zero padding
     float hzpad = 0, wzpad = 0;
     if (conf.exists("hzpad")) hzpad = conf.get_float("hzpad");
     if (conf.exists("wzpad")) wzpad = conf.get_float("wzpad");
     detect.set_zpads(hzpad, wzpad);
      
      bool bmask_class = false;
      if (conf.exists("mask_class"))
	bmask_class = detect.set_mask_class(conf.get_cstring("mask_class"));
      if (conf.exists("input_min")) // limit inputs size
	detect.set_min_resolution(conf.get_uint("input_min")); 
      if (conf.exists("input_max")) // limit inputs size
	detect.set_max_resolution(conf.get_uint("input_max"));
      detect.set_silent();
      if (conf.exists_bool("save_detections")) {
	string detdir = outdir;
	detdir += "detections";
	detdir = detect.set_save(detdir);
	if (conf.exists("save_max_per_frame"))
	  detect.set_save_max_per_frame(conf.get_uint("save_max_per_frame"));
      }
      // nms
      detect.set_cluster_nms(conf.exists_true("cluster_nms"));
      detect.set_scaler_mode(conf.exists_true("scaler_mode"));
      if (conf.exists("nms"))
	detect.set_pruning((t_pruning)conf.get_uint("nms"), 
			   conf.exists("min_hcenter_dist") ? 
			   conf.get_float("min_hcenter_dist") : 0.0,
			   conf.exists("min_wcenter_dist") ? 
			   conf.get_float("min_wcenter_dist") : 0.0,
			   conf.exists("bbox_max_overlap") ? 
			   conf.get_float("bbox_max_overlap") : 1.0,
			   conf.exists_true("share_parts"),
			   conf.exists("threshold2") ? 
			   (Tnet) conf.get_float("threshold2") : 0.0,
			   conf.exists("bbox_max_center_dist") ? 
			   conf.get_float("bbox_max_center_dist") : 0.0,
			   conf.exists("bbox_max_center_dist2") ? 
			   conf.get_float("bbox_max_center_dist2") : 0.0,
			   conf.exists("bbox_max_wcenter_dist") ? 
			   conf.get_float("bbox_max_wcenter_dist") : 0.0,
			   conf.exists("bbox_max_wcenter_dist2") ? 
			   conf.get_float("bbox_max_wcenter_dist2") : 0.0,
			   conf.exists("min_wcenter_dist2") ? 
			   conf.get_float("min_wcenter_dist2") : 0.0,
			   conf.exists("bbox_max_overlap2") ? 
			   conf.get_float("bbox_max_overlap2") : 0.0,
			   conf.exists_true("mean_bb"),
			   conf.exists("same_scale_mhd") ? 
			   conf.get_float("same_scale_mhd") : 0.0,
			   conf.exists("same_scale_mwd") ? 
			   conf.get_float("same_scale_mwd") : 0.0,
			   conf.exists("min_scale_pred") ? 
			   conf.get_float("min_scale_pred") : 0.0,
			   conf.exists("max_scale_pred") ? 
			   conf.get_float("max_scale_pred") : 0.0
			   );
      if (conf.exists("bbox_hfactor") && conf.exists("bbox_wfactor"))
	detect.set_bbox_factors(conf.get_float("bbox_hfactor"),
				conf.get_float("bbox_wfactor"),
				conf.exists("bbox_woverh") ?
				conf.get_float("bbox_woverh") : 1.0,
				conf.exists("bbox_hfactor2") ?
				conf.get_float("bbox_hfactor2") : 1.0,
				conf.exists("bbox_wfactor2") ?
				conf.get_float("bbox_wfactor2") : 1.0);
      if (conf.exists("max_object_hratio"))
	detect.set_max_object_hratio(conf.get_double("max_object_hratio"));
      if (conf.exists("net_min_height") && conf.exists("net_min_width"))
	detect.set_min_input(conf.get_int("net_min_height"),
			     conf.get_int("net_min_width"));
      if (conf.exists("smoothing"))
	detect.set_smoothing(conf.get_uint("smoothing"));
      if (conf.exists("background_name"))
	detect.set_bgclass(conf.get_cstring("background_name"));
      // image search can be configured with a search pattern
      const char *fpattern = IMAGE_PATTERN_MAT;
      if (conf.exists("file_pattern"))
	fpattern = conf.get_cstring("file_pattern");

      // initialize camera (opencv, directory, shmem or video)
      idx<ubyte> frame;
      camera<ubyte> *cam = NULL, *cam2 = NULL;
      if (!strcmp(cam_type.c_str(), "directory")) {
	string dir;
	if (argc >= 3) // read input dir from command line
	  dir = argv[2];
	else if (conf.exists("input_dir"))
	  dir = conf.get_string("input_dir");
	// given list
	list<string> files;
	if (conf.exists("input_list")) {
	  files = string_to_stringlist(conf.get_string("input_list"));
	  cam = new camera_directory<ubyte>(dir.c_str(), height, width,
					    input_random, npasses,
					    std::cout, std::cerr,
					    fpattern, &files);
	} else // given directory only
	  cam = new camera_directory<ubyte>(dir.c_str(), height, width,
					    input_random, npasses,
					    std::cout, std::cerr,
					    fpattern, &files);
      } else if (!strcmp(cam_type.c_str(), "opencv"))
	cam = new camera_opencv<ubyte>(-1, height, width);
#ifdef __LINUX__
      else if (!strcmp(cam_type.c_str(), "v4l2"))
	cam = new camera_v4l2<ubyte>(conf.get_cstring("device"),
				     height, width,
				     conf.exists_true("camera_grayscale"));
#endif
      else if (!strcmp(cam_type.c_str(), "shmem"))
	cam = new camera_shmem<ubyte>("shared-mem", height, width);
      else if (!strcmp(cam_type.c_str(), "video")) {
	if (argc >= 3)
	  cam = new camera_video<ubyte>
	    (argv[2], height, width, conf.get_uint("input_video_sstep"),
	     conf.get_uint("input_video_max_duration"));
	else eblerror("expected 2nd argument");
      } else eblerror("unknown camera type");
      // a camera directory may be used first, then switching to regular cam
      if (conf.exists_bool("precamera"))
	cam2 = new camera_directory<ubyte>(conf.get_cstring("precamdir"),
					   height, width);

      // answer variables & initializations
      vector<bbox*> bboxes;
      vector<bbox*>::iterator ibboxes;
      ostringstream answer_fname;
      mkdir_full(outdir);
      answer_fname << outdir << "bbox.txt";
      // open file      
      ofstream fp(answer_fname.str().c_str());
      if (!fp) {
	cerr << "failed to open " << answer_fname.str() << endl;
	eblerror("open failed");
      }
    
      // gui
#ifdef __GUI__
      display	     = conf.exists_bool("display");
      mindisplay     = conf.exists_bool("minimal_display");
      display_sleep  = conf.get_uint("display_sleep");
      display_states = conf.exists_bool("display_states");
      save_video     = conf.exists_bool("save_video");
      uint qstep1 = 0, qheight1 = 0, qwidth1 = 0,
	qheight2 = 0, qwidth2 = 0, qstep2 = 0;
      if (conf.exists_bool("queue1")) {
	qstep1 = conf.get_uint("qstep1");
	qheight1 = conf.get_uint("qheight1");
	qwidth1 = conf.get_uint("qwidth1"); }
      if (conf.exists_bool("queue2")) {
	qstep2 = conf.get_uint("qstep2");
	qheight2 = conf.get_uint("qheight2");
	qwidth2 = conf.get_uint("qwidth2"); }
      module_1_1_gui netgui;
      wid_states  = display_states ? new_window("network states"):0;
      night_mode();
      wid  = display ? new_window("eblearn object recognition") : 0;
      night_mode();
      float	zoom = 1;
      detector_gui<fs(Tnet)> dgui(conf.exists_bool("queue1"), qstep1, qheight1,
				   qwidth1, conf.exists_bool("queue2"), qstep2,
				   qheight2, qwidth2);
      if (bmask_class)
	dgui.set_mask_class(conf.get_cstring("mask_class"),
			    (Tnet) conf.get_double("mask_threshold"));
      if (save_video) {
	string viddir = outdir;
	viddir += "video";
	cam->start_recording(wid, viddir.c_str());
      }
#endif  
      // timing variables
      timer tpass, toverall;
      long ms;
  
      // loop
      toverall.start();
      while(!cam->empty()) {
	// get a new frame
	tpass.restart();
	// if the pre-camera is defined use it until empty
	if (cam2 && !cam2->empty())
	  frame = cam2->grab();
	else // empty pre-camera, use regular camera
	  frame = cam->grab();
	string frame_name = cam->frame_name();
	// run detector
	if (!display) { // fprop without display
	  bboxes = detect.fprop(frame, threshold, frame_name.c_str());
	}
#ifdef __GUI__
	else { // fprop and display
	  disable_window_updates();
	  clear_window();
	  if (mindisplay)
	    bboxes = dgui.display(detect, frame, threshold, frame_name.c_str(),
				  0, 0, zoom, (Tnet)0, (Tnet)255, wid);
	  else
	    bboxes =
	      dgui.display_inputs_outputs(detect, frame, threshold,
					  frame_name.c_str(), 0, 0, zoom,
					  (Tnet)-1.1, (Tnet)1.1, wid);
	  enable_window_updates();
	  if (display_states) {
	    dgui.display_current(detect, frame, wid_states);
	    select_window(wid);
	  }
	  if (save_video)
	    cam->record_frame();
	}	    
#endif
	ms = tpass.elapsed_milliseconds();
	cout << "processing: " << ms << " ms." << endl;
	cout << "fps: " << cam->fps() << endl;
	// save bounding boxes
	for (ibboxes = bboxes.begin(); ibboxes != bboxes.end(); ++ibboxes) {
	  fp << cam->frame_name() << " " << (*ibboxes)->class_id << " "
	     << (*ibboxes)->confidence << " ";
	  fp << (*ibboxes)->w0 << " " << (*ibboxes)->h0 << " ";
	  fp << (*ibboxes)->w0 + (*ibboxes)->width << " ";
	  fp << (*ibboxes)->h0 + (*ibboxes)->height << endl;
	}
	// sleep display
	if (display_sleep > 0) {
	  cout << "sleeping for " << display_sleep << "ms." << endl;
	  millisleep(display_sleep);
	}
	if (conf.exists("save_max") && 
	    detect.get_total_saved() > conf.get_uint("save_max")) {
	  cout << "Reached max number of detections, exiting." << endl;
	  break ; // limit number of detection saves
	}
      }
      cout << "Execution time: " << toverall.elapsed_minutes() <<" mins" <<endl;
      if (save_video)
	cam->stop_recording(conf.exists_bool("use_original_fps") ?
			    cam->fps() : conf.get_uint("save_video_fps"));
      // free variables
      if (net) delete net;
      if (cam) delete cam;
      // close files
      fp.close();
#ifdef __GUI__
      if (!conf.exists_true("no_gui_quit")) {
	cout << "Closing windows..." << endl;
	quit_gui(); // close all windows
	cout << "Windows closed." << endl;
      }
#endif
    } eblcatcherror();
  return 0;
}
Exemplo n.º 29
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //this code is dark and full of terrors
    //BEWARE
    //I don't like it either
    //*shrug*

    ui->setupUi(this);

    this->setWindowTitle("Reading Calculator");

    int current_line = 0;

    clear_window();
    remove_window_resize();

    widget = new QWidget(this);
    layout = new QGridLayout(widget);
    line_layout = new QGridLayout(widget); //the sub layout is used for every line so that it looks better

    line_layout->addWidget(new QLabel("Include selected date?", widget), 0, 0);

    include_selected_date_check_box = new QCheckBox(widget);
    include_selected_date_check_box->setChecked(false);
    line_layout->addWidget(include_selected_date_check_box, 0, 1);

    layout->addLayout(line_layout, current_line, 0, 1, GRID_WIDTH);
    current_line++;
    line_layout = new QGridLayout(widget); //clear layout

    line_layout->addWidget(new QLabel("Include current date?", widget), 0, 0);

    include_current_date_check_box = new QCheckBox(widget);
    include_current_date_check_box->setChecked(false);
    line_layout->addWidget(include_current_date_check_box, 0, 1);

    layout->addLayout(line_layout, current_line, 0, 1, GRID_WIDTH);
    current_line++;
    line_layout = new QGridLayout(widget); //clear layout

    layout->addWidget(new QLabel("Select deadline:", widget), current_line, 0, 1, GRID_WIDTH);
    current_line++;

    //date combo box
    day_combo_box = new QComboBox(widget);

    for(int i = 0; i < 31; i++){
        day_combo_box->addItem(QString::number(i + 1));
    }

    line_layout->addWidget(day_combo_box, 0, 0);

    //month combo box
    month_combo_box = new QComboBox(widget);
    month_combo_box->addItem("January");
    month_combo_box->addItem("February");
    month_combo_box->addItem("March");
    month_combo_box->addItem("April");
    month_combo_box->addItem("May");
    month_combo_box->addItem("June");
    month_combo_box->addItem("July");
    month_combo_box->addItem("August");
    month_combo_box->addItem("September");
    month_combo_box->addItem("October");
    month_combo_box->addItem("November");
    month_combo_box->addItem("December");
    line_layout->addWidget(month_combo_box, 0, 1);

    //year text box
    year_combo_box = new QComboBox(widget);

    for(int i = 2015; i <= 2050; i++){
        year_combo_box->addItem(QString::number(i));
    }

    line_layout->addWidget(year_combo_box, 0, 2);
    layout->addLayout(line_layout, current_line, 0, 1, GRID_WIDTH);
    current_line++;
    line_layout = new QGridLayout(widget); //clear layout

    line_layout->addWidget(new QLabel("I have read", widget), 3, 0);

    read_pages_text_edit = new QLineEdit(widget);
    line_layout->addWidget(read_pages_text_edit, 3, 1);

    line_layout->addWidget(new QLabel("from", widget), 3, 2);

    all_pages_text_edit = new QLineEdit(widget);
    line_layout->addWidget(all_pages_text_edit, 3, 3);

    line_layout->addWidget(new QLabel("pages", widget), 3, 4);
    layout->addLayout(line_layout, current_line, 0, 1, GRID_WIDTH);
    current_line++;
    line_layout = new QGridLayout(widget);

    submit_push_button = new QPushButton("Calculate", widget);
    layout->addWidget(submit_push_button, current_line, 0, 1, GRID_WIDTH);
    current_line++;
    connect(submit_push_button, SIGNAL(clicked()), this, SLOT(submit()));

    result_label = new QLabel("You should read ... pages per day", widget);
    layout->addWidget(result_label, current_line, 0, 1, GRID_WIDTH);
    current_line++;

    widget->setLayout(layout);
    setCentralWidget(widget);
}
Exemplo n.º 30
0
int sw()
{
	int mode = ONE_PLAYER;
	char option;
	clear_window();
	printf("=== MODO ===\n");
	printf("1. Un Jugador\n");
	printf("2. Dos Jugadores\n");
	do {
		option = getchar();
	} while(option != '1' && option != '2');
	switch (option) {
		case '2':
			mode = MULTI_PLAYER;
			break;
		default:
			mode = ONE_PLAYER;
	}
	clear_window();
	int result = EXIT_SUCCESS;
	put_ship_on_map(mode);
	int x = 0;
	int y = 0;
	int state = PLAYING;
	while (state == PLAYING) {
		print_map();
		printf("Pulse 'e' para cerrar Sea War.\nX: ");
		x = getnum();
		printf("%d\nY: ", x);
		y = getnum();
		printf("%d\n", y);
		if (x < 0 || y < 0) {
			state = EXIT_SW;
		}
		if (game_map[0][y][x] == UNKOWN_WATER || game_map[0][y][x] == UNKOWN_SHIP) {
			game_map[0][y][x]++;
			game_map[0][y][x]++;
		}
		if (mode == ONE_PLAYER) {
			x = getRandomNumber(10);
			y = getRandomNumber(x+1);
			if (game_map[1][x][y] != WATER && game_map[1][x][y] != SHIP) {
				game_map[1][x][y]++;
			}
			else {
				for (x = 0, y = 0; game_map[1][y][x] == WATER || game_map[1][y][x] == SHIP; x++) {
					if (x == 9) {
						x = 0;
						y++;
					}
				}
				game_map[1][y][x]++;
			}
		}
		else if (mode == MULTI_PLAYER) {
			printf("Player 2\nX: ");
			x = getnum();
			printf("%d\nY: ", x);
			y = getnum();
			printf("%d\n", y);
			if (x < 0 || y < 0) {
				state = EXIT_SW;
			}
			if (game_map[1][y][x] == UNKOWN_WATER || game_map[1][y][x] == UNKOWN_SHIP) {
				game_map[1][y][x]++;
				game_map[1][y][x]++;
			}
		}
		if (state != EXIT_SW) {
			state = CheckGameStatus();
		}
	}
	print_map();
	switch (state) {
		case WIN:
			printf("La flota enemiga ha sido destruida.\n");
			break;
		case LOSE:
			printf("La flota aliada ha sido destruida.\n");
			break;
		case EXIT_SW:
			printf("Cerrando Sea War.\n");
			break;
		case EQUAL:
			printf("Las dos flotas han sido destruidas. [EMPATE]\n");
			break;
		default:
			printf("Sea War Error.\n");
			result = EXIT_FAILURE;
			break;
	}
	return result;
}