Пример #1
0
int main(void){
    int    **R, **G, **B, **Y, **F, **L;
    int    hist[256];
    int    boader;
    int    label_num;

    R = (int **)IAllocImage(640,480);   // 画像領域(赤)を確保
    G = (int **)IAllocImage(640,480);   // 画像領域(緑)を確保
    B = (int **)IAllocImage(640,480);   // 画像領域(青)を確保
    Y = (int **)IAllocImage(640,480);   // 画像領域(グレースケール)を確保
    F = (int **)IAllocImage(640,480);   // 画像領域(二値)を確保
    L = (int **)IAllocImage(640,480);   // 画像領域(ラベル付)を確保

    GInit(640,480);                     // Windowの生成
    ILoadPpmImage("abstmix.ppm",R,G,B); // ppmファイルの読み込み
    TranslateGrayScale(R,G,B,Y);        // グレースケールに変換
    MakeHistogram(Y,hist);              // ヒストグラム作成
    DisplayColorImage(Y,Y,Y);

    boader = Percentile(Y,hist,0.92);
    TranslateBoolScale(Y,F,boader);     // パーセンタイル法で2値化
    remove_noise(F,13);
    label_num=labeling(F,L);
    DisplayColorImage(F,F,F);
    printf("label_num=%d\n",label_num);
    printLabelingData(L,label_num);

    GWaitLoop();                        // 終了処理

    exit(EXIT_SUCCESS);
}
Пример #2
0
void analyze(flow * flowrec) {

	if (flowrec->datapkts==pktlimit) {
		if (action==ACTION_LABEL) {
			if (!flowrec->isSSL) {
				flowrec->label=labeling(assign(flowrec->pkt_sizes,threshold),flowrec->dport);
			} else {
				flowrec->label=SSL_labeling(assign(flowrec->pkt_sizes,threshold),flowrec->dport);
			}
		} else {
			flowrec->label=LABEL_PARSED;
		}
		
		if (sslparsing && flowrec->label>0 && flowrec->label<=model.nbapplis && model.SSLapplis[flowrec->label-1]) {
		//If connection is SSL we continue the parsing
			flowrec->isSSL=1;
			flowrec->SSLdata=0;
			flowrec->datapkts=0;
			bzero(flowrec->pkt_sizes,pktlimit*sizeof(int16_t));
			flowrec->labelSSL=flowrec->label;
			flowrec->label=LABEL_NONE;
			return;
		}

		if (memory>=OPT_NOSTORE) {
			//If we want to minimize memory usage, we print information about the connection and remove it from the hashtable
			print_flow(flowrec);
			clear_hash_entry(flow_hash,flowrec);
		}
	}
}
Пример #3
0
void LabelingModel::saveLabeling(const QString &filename)
{
	Labeling labeling(full_labels);
	cv::Mat3b output = labeling.bgr();

	GerbilIO io(nullptr, "Labeling As Image File", "labeling image");
	io.setFileCategory("LabelFile");
	io.setFileSuffix(".png");
	io.writeImage(output);
}
 int main(int argc, char* argv[])
 { 
 	std::srand(2342);

 	using ValueType = double;
 	using IndexType = size_t;
 	//using LabelType = size_t;
 	using LabelType = size_t;
 	using VarIdMapType = std::map<IndexType,IndexType>;

	// Parameters
	constexpr size_t nx = 256; //width of the grid
	constexpr size_t ny = 256; //height of the grid
	constexpr auto eps = 1e-05;
	int noIterations = 1;

	if(argc > 2) {
		noIterations = atoi(argv[2]); 
	}

	using Model = TST::GraphicalModel;
	Model gm;
	opengm::hdf5::load(gm, argv[1], "gm");

	std::vector<LabelType> labeling(gm.numberOfVariables());

	// initialize communication framework
	int mpi_myRank = 0;
	MPI_Init(NULL, NULL);
	MPI_Comm_rank(MPI_COMM_WORLD, &mpi_myRank);
	Diffusion_MPI_Rewrite<Model,opengm::Adder> mpiDiffusion(gm, noIterations, eps, nx, ny);
	if(mpi_myRank == 0) {
		std::cout << "** Diffusion MPI" << std::endl;
	}

	// infer labelling
	mpiDiffusion.infer();
	mpiDiffusion.arg(labeling);

	// shutdown mpi
	MPI_Barrier(MPI_COMM_WORLD);
	MPI_Finalize();

	 if(mpi_myRank > 0) {
	 	return 0; 
	 }
	 std::cout << "------------------------------------------------" << std::endl << "------------------------------------------------" << std::endl;

	 return 0;
	}
Пример #5
0
void LabelingModel::loadLabeling(const QString &filename)
{
	GerbilIO io(nullptr, "Labeling From Image File", "labeling image");
	io.setFileCategory("LabelFile");
	io.setFileSuffix(".png");
	/* we are properly initialized with the image dimensions
	 * so we take these frome our initialization */
	io.setWidth(full_labels.cols);
	io.setHeight(full_labels.rows);
	io.setFileName(filename);
	cv::Mat input = io.readImage();
	if (input.empty())
		return;

	Labeling labeling(input, false);
	setLabels(labeling, true);
}
Пример #6
0
    void computeWordFrequencies(AddressableMatrixT const & points, U * histogram, double const * point_weights = NULL,
                                typename std::enable_if<
                                    std::is_base_of< AbstractAddressableMatrix<typename AddressableMatrixT::Value>,
                                                     AddressableMatrixT >::value >::type * dummy = NULL) const
    {
      long num_points = points.rows();
      Array<long> labeling((size_t)num_points);
      vocabulary.mapToClusters(points, &labeling[0]);

      long num_words = numWords();
      for (long i = 0; i < num_words; ++i)
        histogram[i] = 0;

      for (size_t i = 0; i < labeling.size(); ++i)
      {
        if (labeling[i] >= 0)
          histogram[labeling[i]] += static_cast<U>(point_weights ? point_weights[i] : 1);
      }
    }
Пример #7
0
int tricam_process(int argc, char *argv[])
{
  int i, j, w, h, bpp;
  bytemap_t *up_image, *mid_image, *dn_image;
  bytemap_t *gray, *se;
  bitmap_t *up_roi, *mid_roi, *dn_roi;
  bitmap_t *bin, *roi, *tmp;
  char *fn, *ptr;
  real_t value;
  FILE *fd;
  label_info_t *label_info;
  dwordmap_t *labelmap;
  point_t *centroid;
  int label, area;
  uint8_t vmin, vmax;
  real_t vmean;

  bytemap_t *op1, *op2, *op3;
  char *path;
  int next_option;
  char *token1, *token2, *token3;
  real_t cutup = -2550000, cutdown = -4748;

  program_name = argv[0];
  do {
    next_option = getopt_long(argc, argv, short_options, long_options, NULL);
    switch (next_option) {
    case 'h': print_usage(stdout, 0); break;
    case 'o': token1 = strdup(optarg); break;
    case 's': token2 = strdup(optarg); break;
    case 'd': token3 = strdup(optarg); break;
    case 'f': cutup = strtod(optarg, NULL); break;
    case 't': cutdown = strtod(optarg, NULL); break;
    case 'v': verbose = 1; break;
    case 'n': path = strdup(optarg); break;
    case '?': print_usage(stderr, 1); break;
    case -1: break;
    default: abort();
    }
  } while (next_option != -1);

  //  printf("(%s - %s) / %s, %lf, %lf, %s\n", token1, token2, token3, cutup, cutdown, path);

  w = WIDTH; h = HEIGHT; bpp = BPP;

  initialize_screen(w, h, bpp);

  up_image = bytemap_new(w, h);
  mid_image = bytemap_new(w, h);
  dn_image = bytemap_new(w, h);

  gray = bytemap_new(w, h);

  up_roi = bitmap_new(w, h);
  mid_roi = bitmap_new(w, h);
  dn_roi = bitmap_new(w, h);

  bin = bitmap_new(w, h);
  tmp = bitmap_new(w, h);
  roi = bitmap_new(w, h);

  se = bytemap_new(3, 3);
  bytemap_fill(se, 0, 0, 3, 3, 1);

  labelmap = dwordmap_new(w, h);

  path = (char *)malloc(256 * sizeof(char));

  // Up display image ////////////////////
  strcpy(path, argv[1]);
  strcat(path, "_up.bmp");
  fn = strrchr(path, '/') + 1;
  printf("Filename: %s\n", fn);
  printf("Display image\n");
  load_and_display_BMP(path);
  read_bytemap_in_screen(up_image, NULL, NULL);
  bytemap_clear(gray);
  bytemap_copy(gray, UP_DX, UP_DY, up_image, 0, 0, w, h);
  write_bytemap_to_screen(gray, gray, gray);
  wait_keyhit();

  printf("Mean filtering \n");
  mean_smooth(up_image, gray, 3);
  write_bytemap_to_screen(up_image, up_image, up_image);
  wait_keyhit();
  ////////////////////////////////////////

  // MID display image ///////////////////
  strcpy(path, argv[1]);
  strcat(path, "_mid.bmp");
  fn = strrchr(path, '/') + 1;
  printf("Filename: %s\n", fn);
  printf("Display image\n");
  load_and_display_BMP(path);
  read_bytemap_in_screen(mid_image, NULL, NULL);
  bytemap_clear(gray);
  bytemap_copy(gray, MID_DX, MID_DY, mid_image, 0, 0, w, h);
  write_bytemap_to_screen(gray, gray, gray);
  wait_keyhit();

  printf("Mean filtering \n");
  mean_smooth(mid_image, gray, 3);
  write_bytemap_to_screen(mid_image, mid_image, mid_image);
  wait_keyhit();
  /////////////////////////////////////////

  // DN display image /////////////////////
  strcpy(path, argv[1]);
  strcat(path, "_dn.bmp");
  fn = strrchr(path, '/') + 1;
  printf("filename: %s\n", fn);
  printf("Display image\n");
  load_and_display_BMP(path);
  read_bytemap_in_screen(dn_image, NULL, NULL);
  bytemap_clear(gray);
  bytemap_copy(gray, DN_DX, DN_DY, dn_image, 0, 0, w, h);
  write_bytemap_to_screen(gray, gray, gray);
  wait_keyhit();

  printf("Mean filtering \n");
  mean_smooth(dn_image, gray, 3);
  write_bytemap_to_screen(dn_image, dn_image, dn_image);
  wait_keyhit();
  ///////////////////////////////////////

  printf("Up Image thresholding\n");
  bytemap_threshold(bin, up_image, UP_FROM, UP_TO);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();

  printf("Big blobs greping\n");
  bitmap_clear(roi);
  label_info = label_info_new();
  labeling(labelmap, label_info, bin, NEIGHBOR_8);
  for (label = 0; label < label_info_get_count(label_info); label++) {
    label_info_glimpse(&area, label, label_info);
    //printf("area:%d\n", area);
    if (area > 3000) {
      for (i = 0; i < h; i++) {
	for (j = 0; j < w; j++) {
	  if (dwordmap_get_value(labelmap, j, i) == label) {
	    bitmap_set_value(roi, j, i);
	  }
	}
      }
    }
  }
  label_info_destroy(label_info);
  write_bitmap_to_screen(roi, roi, roi);
  wait_keyhit();

  printf("Fill holes\n");
  bitmap_complement(bin, roi);
  labeling_grep_big_blob(roi, bin);
  bitmap_complement(bin, roi);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();

  printf("Image Morphology\n");
  binary_closing(tmp, bin, se);
  binary_opening(up_roi, tmp, se);
  write_bitmap_to_screen(up_roi, up_roi, up_roi);
  wait_keyhit();

  ///////////////////////////////////////
  printf("Mid Image thresholding\n");
  bytemap_threshold(bin, mid_image, MID_FROM, MID_TO);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();

  printf("Big blobs greping\n");
  bitmap_clear(roi);
  label_info = label_info_new();
  labeling(labelmap, label_info, bin, NEIGHBOR_8);
  for (label = 0; label < label_info_get_count(label_info); label++) {
    label_info_glimpse(&area, label, label_info);
    //printf("area:%d\n", area);
    if (area > 3000) {
      for (i = 0; i < h; i++) {
	for (j = 0; j < w; j++) {
	  if (dwordmap_get_value(labelmap, j, i) == label) {
	    bitmap_set_value(roi, j, i);
	  }
	}
      }
    }
  }
  label_info_destroy(label_info);
  write_bitmap_to_screen(roi, roi, roi);
  wait_keyhit();

  printf("Fill holes\n");
  bitmap_complement(bin, roi);
  labeling_grep_big_blob(roi, bin);
  bitmap_complement(bin, roi);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();

  printf("Image Morphology\n");
  binary_closing(tmp, bin, se);
  binary_opening(mid_roi, tmp, se);
  write_bitmap_to_screen(mid_roi, mid_roi, mid_roi);
  wait_keyhit();

  ///////////////////////////////////////////////////
  printf("Dn Image thresholding\n");
  bytemap_threshold(bin, dn_image, DN_FROM, DN_TO);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();

  printf("Big blobs greping\n");
  bitmap_clear(roi);
  label_info = label_info_new();
  labeling(labelmap, label_info, bin, NEIGHBOR_8);
  for (label = 0; label < label_info_get_count(label_info); label++) {
    label_info_glimpse(&area, label, label_info);
    //printf("area:%d\n", area);
    if (area > 3000) {
      for (i = 0; i < h; i++) {
	for (j = 0; j < w; j++) {
	  if (dwordmap_get_value(labelmap, j, i) == label) {
	    bitmap_set_value(roi, j, i);
	  }
	}
      }
    }
  }
  label_info_destroy(label_info);
  write_bitmap_to_screen(roi, roi, roi);
  wait_keyhit();

  printf("Fill holes\n");
  bitmap_complement(bin, roi);
  labeling_grep_big_blob(roi, bin);
  bitmap_complement(bin, roi);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();

  printf("Image Morphology\n");
  binary_closing(tmp, bin, se);
  binary_opening(dn_roi, tmp, se);
  write_bitmap_to_screen(dn_roi, dn_roi, dn_roi);
  wait_keyhit();
  ///////////////////////////////////////////////

  bitmap_clear(roi);
  bitmap_or(roi, up_roi);
  bitmap_or(roi, mid_roi);
  bitmap_or(roi, dn_roi);
  write_bitmap_to_screen(up_roi, mid_roi, dn_roi);
  wait_keyhit();
  write_bitmap_to_screen(roi, roi, roi);
  wait_keyhit();

  /*
  //write_bitmap_to_screen(up_roi, mid_roi, dn_roi);
  //read_bytemap_in_screen(up_image, mid_image, dn_image);

  strcpy(path, argv[1]);
  strcat(path, "_up_roi.bmp");
  save_bytemap_as_BMP(up_image, path);

  strcpy(path, argv[1]);
  strcat(path, "_mid_roi.bmp");
  save_bytemap_as_BMP(mid_image, path);

  strcpy(path, argv[1]);
  strcat(path, "_dn_roi.bmp");
  save_bytemap_as_BMP(dn_image, path);

  read_bytemap_in_screen(gray, NULL, NULL);
  strcpy(path, argv[1]);
  strcat(path, "_roi.bmp");
  save_bytemap_as_BMP(gray, path);
  */

#if 0
  // up image statistic /////////////////////////
  bytemap_get_min_max_on_roi(&vmin, &vmax, up_image, roi);
  bytemap_get_mean_on_roi(&vmean, up_image, roi);
  printf("Up image statistics are min: %d, mean: %lf, max: %d\n", vmin, vmean, vmax);

  fd = fopen("up_stat.txt", "a+");
  fprintf(fd, "%d, %lf, %d\n", vmin, vmean, vmax);
  fclose(fd);
  ////////////////////////////////////////////////

  // mid image statistic /////////////////////////
  bytemap_get_min_max_on_roi(&vmin, &vmax, mid_image, roi);
  bytemap_get_mean_on_roi(&vmean, mid_image, roi);
  printf("Mid image statistics are min: %d, mean: %lf, max: %d\n", vmin, vmean, vmax);

  fd = fopen("mid_stat.txt", "a+");
  fprintf(fd, "%d, %lf, %d\n", vmin, vmean, vmax);
  fclose(fd);
  /////////////////////////////////////////////////

  // dn image statistic ///////////////////////////
  bytemap_get_min_max_on_roi(&vmin, &vmax, dn_image, roi);
  bytemap_get_mean_on_roi(&vmean, dn_image, roi);
  printf("Dn image statistics are min: %d, mean: %lf, max: %d\n", vmin, vmean, vmax);

  fd = fopen("dn_stat.txt", "a+");
  fprintf(fd, "%d, %lf, %d\n", vmin, vmean, vmax);
  fclose(fd);
  /////////////////////////////////////////////////

  return 0;
#endif

#if 1
  // Up image normalization
  printf("Up-Image global normalization\n");
  for (i = 0; i < h; i++) {
    for (j = 0; j < w; j++) {
      if (bitmap_isset(roi, j, i)) {
	value = bytemap_get_value(up_image, j, i);
	if (value < UP_MEAN) {
	  value = round(128.0 / (UP_MEAN - UP_MIN) * (value - UP_MIN));
	} else {
	  value = round(128.0 / (UP_MAX - UP_MEAN) * (value - UP_MEAN) + 128.0);
	}
	if (value < 0) value = 0;
	if (value > 255) value = 255;
	bytemap_put_value(value, up_image, j, i);
      } else {
	bytemap_put_value(0, up_image, j, i);
      }
    }
  }
  write_bytemap_to_screen(up_image, up_image, up_image);
  strcpy(path, argv[1]);
  strcat(path, "_up_normal.bmp");
  save_bytemap_as_gray_BMP(up_image, path);
  wait_keyhit();
  //////////////////////////////////////////

  // Mid image normalization
  printf("MID-Image global normalization\n");
  for (i = 0; i < h; i++) {
    for (j = 0; j < w; j++) {
      if (bitmap_isset(roi, j, i)) {
	value = bytemap_get_value(mid_image, j, i);
	if (value < MID_MEAN) {
	  value = round(128.0 / (MID_MEAN - MID_MIN) * (value - MID_MIN));
	} else {
	  value = round(128.0 / (MID_MAX - MID_MEAN) * (value - MID_MEAN) + 128.0);
	}
	if (value < 0) value = 0;
	if (value > 255) value = 255;
	bytemap_put_value(value, mid_image, j, i);
      } else {
	bytemap_put_value(0, mid_image, j, i);
      }
    }
  }
  write_bytemap_to_screen(mid_image, mid_image, mid_image);
  strcpy(path, argv[1]);
  strcat(path, "_mid_normal.bmp");
  save_bytemap_as_gray_BMP(mid_image, path);
  wait_keyhit();
  ///////////////////////////////////////////////

  // Dn image normalization
  printf("Dn image global normalization\n");
  for (i = 0; i < h; i++) {
    for (j = 0; j < w; j++) {
      if (bitmap_isset(roi, j, i)) {
	value = bytemap_get_value(dn_image, j, i);
	if (value < DN_MEAN) {
	  value = round(128.0 / (DN_MEAN - DN_MIN) * (value - DN_MIN));
	} else {
	  value = round(128.0 / (DN_MAX - DN_MEAN) * (value - DN_MEAN) + 128.0);
	}
	if (value < 0) value = 0;
	if (value > 255) value = 255;
	bytemap_put_value(value, dn_image, j, i);
      } else {
	bytemap_put_value(0, dn_image, j, i);
      }
    }
  }
  write_bytemap_to_screen(dn_image, dn_image, dn_image);
  strcpy(path, argv[1]);
  strcat(path, "_dn_normal.bmp");
  save_bytemap_as_gray_BMP(dn_image, path);
  wait_keyhit();
  ////////////////////////////////////////////

  return 0;
#endif

#if 0
  printf("Image subtraction between DN and MID for bruise-detection\n");
  for (i = 0; i < h; i++) {
    for (j = 0; j < w; j++) {
      if (bitmap_isset(roi, j, i)) {
	value = ((real_t)bytemap_get_value(dn_image, j, i) - (real_t)bytemap_get_value(mid_image, j, i) + 255.0) / 2.0;
	if (value < 0) value = 0;
	if (value > 255) value = 255;
	bytemap_put_value(value, gray, j, i);
      } else {
	bytemap_put_value(0, gray, j, i);
      }
    }
  }
  write_bytemap_to_screen(gray, gray, gray);
  wait_keyhit();

  bytemap_threshold(bin, gray, 142, 255);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();

  printf("Image subtraction between UP and MID for spot-detection\n");
  for (i = 0; i < h; i++) {
    for (j = 0; j < w; j++) {
      if (bitmap_isset(roi, j, i)) {
	value = ((real_t)bytemap_get_value(up_image, j, i) - (real_t)bytemap_get_value(mid_imageb, j, i) + 255.0) / 2.0;
	if (value < 0) value = 0;
	if (value > 255) value = 255;
	bytemap_put_value(value, gray, j, i);
      } else {
	bytemap_put_value(0, gray, j, i);
      }
    }
  }
  write_bytemap_to_screen(gray, gray, gray);
  wait_keyhit();
  
  bytemap_threshold(bin, gray, 1, 110);
  write_bitmap_to_screen(bin, bin, bin);
  wait_keyhit();
#endif

  dwordmap_destroy(labelmap);

  bytemap_destroy(se);
  return 0;

  bitmap_destroy(roi);
  bitmap_destroy(tmp);
  bitmap_destroy(bin);

  bitmap_destroy(dn_roi);
  bitmap_destroy(mid_roi);
  bitmap_destroy(up_roi);

  bytemap_destroy(gray);

  bytemap_destroy(dn_image);
  bytemap_destroy(mid_image);
  bytemap_destroy(up_image);

  return 0;
}
Пример #8
0
int main(int argc, char **argv) {
    util::system::print_build_timestamp(argv[0]);
    util::system::register_segfault_handler();

#ifdef RESEARCH
    std::cout << "******************************************************************************" << std::endl
              << " Due to use of the -DRESEARCH=ON compile option, this program is licensed "     << std::endl
              << " for research purposes only. Please pay special attention to the gco license."  << std::endl
              << "******************************************************************************" << std::endl;
#endif

    Timer timer;
    util::WallTimer wtimer;

    Arguments conf;
    try {
        conf = parse_args(argc, argv);
    } catch (std::invalid_argument & ia) {
        std::cerr << ia.what() << std::endl;
        std::exit(EXIT_FAILURE);
    }

    if (!util::fs::dir_exists(util::fs::dirname(conf.out_prefix).c_str())) {
        std::cerr << "Destination directory does not exist!" << std::endl;
        std::exit(EXIT_FAILURE);
    }

    std::cout << "Load and prepare mesh: " << std::endl;
    mve::TriangleMesh::Ptr mesh;
    try {
        mesh = mve::geom::load_ply_mesh(conf.in_mesh);
    } catch (std::exception& e) {
        std::cerr << "\tCould not load mesh: "<< e.what() << std::endl;
        std::exit(EXIT_FAILURE);
    }
    mve::MeshInfo mesh_info(mesh);
    tex::prepare_mesh(&mesh_info, mesh);

    std::cout << "Generating texture views: " << std::endl;
    tex::TextureViews texture_views;
    tex::generate_texture_views(conf.in_scene, &texture_views);

    write_string_to_file(conf.out_prefix + ".conf", conf.to_string());
    timer.measure("Loading");

    std::size_t const num_faces = mesh->get_faces().size() / 3;

    std::cout << "Building adjacency graph: " << std::endl;
    tex::Graph graph(num_faces);
    tex::build_adjacency_graph(mesh, mesh_info, &graph);

    if (conf.labeling_file.empty()) {
        std::cout << "View selection:" << std::endl;
        util::WallTimer rwtimer;

        tex::DataCosts data_costs(num_faces, texture_views.size());
        if (conf.data_cost_file.empty()) {
            tex::calculate_data_costs(mesh, &texture_views, conf.settings, &data_costs);

            if (conf.write_intermediate_results) {
                std::cout << "\tWriting data cost file... " << std::flush;
                    ST::save_to_file(data_costs, conf.out_prefix + "_data_costs.spt");
                std::cout << "done." << std::endl;
            }
        } else {
            std::cout << "\tLoading data cost file... " << std::flush;
            try {
                ST::load_from_file(conf.data_cost_file, &data_costs);
            } catch (util::FileException e) {
                std::cout << "failed!" << std::endl;
                std::cerr << e.what() << std::endl;
                std::exit(EXIT_FAILURE);
            }
            std::cout << "done." << std::endl;
        }
        timer.measure("Calculating data costs");

        tex::view_selection(data_costs, &graph, conf.settings);
        timer.measure("Running MRF optimization");
        std::cout << "\tTook: " << rwtimer.get_elapsed_sec() << "s" << std::endl;

        /* Write labeling to file. */
        if (conf.write_intermediate_results) {
            std::vector<std::size_t> labeling(graph.num_nodes());
            for (std::size_t i = 0; i < graph.num_nodes(); ++i) {
                labeling[i] = graph.get_label(i);
            }
            vector_to_file(conf.out_prefix + "_labeling.vec", labeling);
        }
    } else {
        std::cout << "Loading labeling from file... " << std::flush;

        /* Load labeling from file. */
        std::vector<std::size_t> labeling = vector_from_file<std::size_t>(conf.labeling_file);
        if (labeling.size() != graph.num_nodes()) {
            std::cerr << "Wrong labeling file for this mesh/scene combination... aborting!" << std::endl;
            std::exit(EXIT_FAILURE);
        }

        /* Transfer labeling to graph. */
        for (std::size_t i = 0; i < labeling.size(); ++i) {
            const std::size_t label = labeling[i];
            if (label > texture_views.size()){
                std::cerr << "Wrong labeling file for this mesh/scene combination... aborting!" << std::endl;
                std::exit(EXIT_FAILURE);
            }
            graph.set_label(i, label);
        }

        std::cout << "done." << std::endl;
    }

    tex::TextureAtlases texture_atlases;
    {
        /* Create texture patches and adjust them. */
        tex::TexturePatches texture_patches;
        tex::VertexProjectionInfos vertex_projection_infos;
        std::cout << "Generating texture patches:" << std::endl;
        tex::generate_texture_patches(graph, mesh, mesh_info, &texture_views, &vertex_projection_infos, &texture_patches);

        if (conf.settings.global_seam_leveling) {
            std::cout << "Running global seam leveling:" << std::endl;
            tex::global_seam_leveling(graph, mesh, mesh_info, vertex_projection_infos, &texture_patches);
            timer.measure("Running global seam leveling");
        } else {
            ProgressCounter texture_patch_counter("Calculating validity masks for texture patches", texture_patches.size());
            #pragma omp parallel for schedule(dynamic)
            for (std::size_t i = 0; i < texture_patches.size(); ++i) {
                texture_patch_counter.progress<SIMPLE>();
                TexturePatch::Ptr texture_patch = texture_patches[i];
                std::vector<math::Vec3f> patch_adjust_values(texture_patch->get_faces().size() * 3, math::Vec3f(0.0f));
                texture_patch->adjust_colors(patch_adjust_values);
                texture_patch_counter.inc();
            }
            timer.measure("Calculating texture patch validity masks");
        }

        if (conf.settings.local_seam_leveling) {
            std::cout << "Running local seam leveling:" << std::endl;
            tex::local_seam_leveling(graph, mesh, vertex_projection_infos, &texture_patches);
        }
        timer.measure("Running local seam leveling");

        /* Generate texture atlases. */
        std::cout << "Generating texture atlases:" << std::endl;
        tex::generate_texture_atlases(&texture_patches, &texture_atlases);
    }

    /* Create and write out obj model. */
    {
        std::cout << "Building objmodel:" << std::endl;
        tex::Model model;
        tex::build_model(mesh, texture_atlases, &model);
        timer.measure("Building OBJ model");

        std::cout << "\tSaving model... " << std::flush;
        tex::Model::save(model, conf.out_prefix);
        std::cout << "done." << std::endl;
        timer.measure("Saving");
    }

    std::cout << "Whole texturing procedure took: " << wtimer.get_elapsed_sec() << "s" << std::endl;
    timer.measure("Total");
    if (conf.write_timings) {
        timer.write_to_file(conf.out_prefix + "_timings.csv");
    }

    if (conf.write_view_selection_model) {
        texture_atlases.clear();
        std::cout << "Generating debug texture patches:" << std::endl;
        {
            tex::TexturePatches texture_patches;
            generate_debug_embeddings(&texture_views);
            tex::VertexProjectionInfos vertex_projection_infos; // Will only be written
            tex::generate_texture_patches(graph, mesh, mesh_info, &texture_views, &vertex_projection_infos, &texture_patches);
            tex::generate_texture_atlases(&texture_patches, &texture_atlases);
        }

        std::cout << "Building debug objmodel:" << std::endl;
        {
            tex::Model model;
            tex::build_model(mesh, texture_atlases, &model);
            std::cout << "\tSaving model... " << std::flush;
            tex::Model::save(model, conf.out_prefix + "_view_selection");
            std::cout << "done." << std::endl;
        }
    }

    return EXIT_SUCCESS;
}
Пример #9
0
/*************************************************
  vision-serverの本体
    Cameraデータの取得、画像処理、ソケット通信待ち受けを行う
************************************************/
int main (int argc, char **argv){
  CvSize size;
  int step;
  CvCapture *cap;
  IplImage *capture_image;
  IplImage *frame_image;
  IplImage *processed_image;
  IplImage *grayImage; 
  IplImage *binaryImage;
  unsigned char* binarydata;

  CvFont font;
  char text[50];
  char hostname[30];
  int s, i, port = 9000;
  pthread_t tid;

  /*** socket通信のための処理(ここから) ***/
  for (i=1;i<argc;i++){
    if (strcmp("-port", argv[i]) == 0) {
      port=atoi(argv[++i]);
    }}
  gethostname(hostname, sizeof(hostname));
  s = init_socket_server(hostname, &port);
  fprintf(stderr, "hostname %s\n", hostname);
  for (i=0; i< MAX_SOCKET ; i++) sockets[i].type=0;
  //threadで待ちうけ
  fprintf(stderr, "Waiting connection...\n");
  pthread_create(&tid, NULL, acceptor, (void *)s);
  /*** socket通信のための処理(ここまで) ***/

  /** semaphoreの準備 ***/
  raw_semaphore = semget((key_t)1111, 1, 0666|IPC_CREAT);
  if(raw_semaphore == -1){
    perror("semget failure");
    exit(EXIT_FAILURE);
  }
  process_semaphore = semget((key_t)1111, 1, 0666|IPC_CREAT);
  if(process_semaphore == -1){
    perror("semget failure");
    exit(EXIT_FAILURE);
  }
  union semun semunion;
  semunion.val = 0;  //semaphoreの初期値
  if(semctl(raw_semaphore, 0, SETVAL, semunion) == -1){
    perror("semctl(init) failure");
    exit(EXIT_FAILURE);
  }
  if(semctl(process_semaphore, 0, SETVAL, semunion) == -1){
    perror("semctl(init) failure");
    exit(EXIT_FAILURE);
  }
  /** semaphoreの準備(ここまで) ***/

  /** cameraや画像取得の用意(ここから) ***/
  //camera initialization 
  if((cap = cvCreateCameraCapture(-1))==NULL){
    printf("Couldn't find any camera.\n");
    return -1;
  }
  capture_image = cvQueryFrame(cap);
  width = capture_image->width;
  height = capture_image->height;
  fprintf(stderr, "height %d, width %d\n", height, width);
  fprintf(stderr, "process height %d, process width %d\n", process_height, process_width);
  /** cameraや画像取得の用意(ここまで) ***/

  /** 画像処理(赤色抽出)の準備 ***/
  //fontの設定(しないとSegfaultで落ちる)
  float hscale = 1.0f;
  float vscale = 1.0f;
  float italicscale = 0.0f;
  int thickness = 3;
  cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, hscale, vscale, italicscale, thickness, CV_AA);
  //font設定ここまで
  // Set threshold
  rgb_thre[0] = R_MIN_THRE;
  rgb_thre[1] = R_MAX_THRE;
  rgb_thre[2] = G_MIN_THRE;
  rgb_thre[3] = G_MAX_THRE;
  rgb_thre[4] = B_MIN_THRE;
  rgb_thre[5] = B_MAX_THRE;


  //画像処理するイメージ領域を確保
  frame_image = cvCreateImage(cvSize(process_width, process_height), IPL_DEPTH_8U, 3);
  processed_image = cvCreateImage(cvSize(process_width, process_height), IPL_DEPTH_8U, 3);
  /** 画像処理(赤色抽出)の準備(ここまで) ***/

  
  /**** 面積を出すための2値化 ***/
  grayImage = cvCreateImage(cvGetSize(frame_image), IPL_DEPTH_8U, 1);
  binaryImage = cvCreateImage(cvGetSize(frame_image), IPL_DEPTH_8U, 1);
  
  //Labeling init
  label_buf = (int*)malloc(sizeof(int)*frame_image->width*frame_image->height);

  /**** main loop(本体) ****/
  while(1){
    CvPoint centroid;
    //カメラ画像をcaptureする
    capture_image = cvQueryFrame(cap);
    if (capture_image==NULL) {
      fprintf(stderr, "capture_image is %p\n", capture_image);
      continue;
    }
    cvResize(capture_image, frame_image, CV_INTER_LINEAR);

    //カメラ画像を処理する
    maskRGB(frame_image, processed_image, rgb_thre);          //赤色抽出
    // Binarize
    myBinarize(processed_image, grayImage, binaryImage);
    cvDilate(binaryImage, grayImage, NULL, 10); //ぼうちょう
    cvErode(grayImage, binaryImage, NULL, 15);  //収縮
    // Labeling
    cvGetRawData(binaryImage, &binarydata, &step, &size);
    labeling(binarydata, frame_image->height, frame_image->width, label_buf, step);
    label_num = labeling_result(&linfo, label_buf, frame_image->height, frame_image->width);
    //処理結果を書き込む
    {
      int i,n;
      n=25;
      //fprintf(stderr, "num is %d\n", label_num);
      for(i=0; i<label_num; i++){
        //fprintf(stderr, "area %d, x %d y %d\n", linfo[i].area, (int)linfo[i].xpos, (int)linfo[i].ypos);
        centroid.x = (int) linfo[i].xpos;
        centroid.y = (int) linfo[i].ypos;
        drawCross(processed_image, &centroid, CV_RGB(0, 255, 0));                                 //×印をいれる
        sprintf(text, "X: %d Y: %d AREA: %d", centroid.x, centroid.y, linfo[i].area);             //値をかく
        cvPutText(processed_image, text, cvPoint(n, (height-n*(i+1))), &font, CV_RGB(0, 255, 0)); //
      }
    }
    // image -> rawdata
    sema_wait(raw_semaphore);
    cvGetRawData(frame_image, &rawdata, &step, &size);
    
    // process image -> process data
    sema_wait(process_semaphore);
    cvGetRawData(processed_image, &processdata, &step, &size);

    //sleep
    usleep(30000);
  }
  //release the capture object
  cvReleaseCapture(&cap);
  return 0;
}